diff --git a/.ci/teamcity/checks/doc_api_changes.sh b/.ci/teamcity/checks/doc_api_changes.sh index 821647a39441c..43b65d4e188ba 100755 --- a/.ci/teamcity/checks/doc_api_changes.sh +++ b/.ci/teamcity/checks/doc_api_changes.sh @@ -4,4 +4,5 @@ set -euo pipefail source "$(dirname "${0}")/../util.sh" -yarn run grunt run:checkDocApiChanges +checks-reporter-with-killswitch "Check Doc API Changes" \ + node scripts/check_published_api_changes diff --git a/.ci/teamcity/checks/eslint.sh b/.ci/teamcity/checks/eslint.sh new file mode 100755 index 0000000000000..d7282b310f81c --- /dev/null +++ b/.ci/teamcity/checks/eslint.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +set -euo pipefail + +source "$(dirname "${0}")/../util.sh" + +checks-reporter-with-killswitch "Lint: eslint" \ + node scripts/eslint --no-cache diff --git a/.ci/teamcity/checks/file_casing.sh b/.ci/teamcity/checks/file_casing.sh index 66578a4970fec..5c0815bdd9551 100755 --- a/.ci/teamcity/checks/file_casing.sh +++ b/.ci/teamcity/checks/file_casing.sh @@ -4,4 +4,5 @@ set -euo pipefail source "$(dirname "${0}")/../util.sh" -yarn run grunt run:checkFileCasing +checks-reporter-with-killswitch "Check File Casing" \ + node scripts/check_file_casing --quiet diff --git a/.ci/teamcity/checks/i18n.sh b/.ci/teamcity/checks/i18n.sh index f269816cf6b95..62ea3fbe9b04d 100755 --- a/.ci/teamcity/checks/i18n.sh +++ b/.ci/teamcity/checks/i18n.sh @@ -4,4 +4,5 @@ set -euo pipefail source "$(dirname "${0}")/../util.sh" -yarn run grunt run:i18nCheck +checks-reporter-with-killswitch "Check i18n" \ + node scripts/i18n_check --ignore-missing diff --git a/.ci/teamcity/checks/licenses.sh b/.ci/teamcity/checks/licenses.sh index 2baca87074630..136d281647cc5 100755 --- a/.ci/teamcity/checks/licenses.sh +++ b/.ci/teamcity/checks/licenses.sh @@ -4,4 +4,5 @@ set -euo pipefail source "$(dirname "${0}")/../util.sh" -yarn run grunt run:licenses +checks-reporter-with-killswitch "Check Licenses" \ + node scripts/check_licenses --dev diff --git a/.ci/teamcity/checks/verify_dependency_versions.sh b/.ci/teamcity/checks/sasslint.sh similarity index 51% rename from .ci/teamcity/checks/verify_dependency_versions.sh rename to .ci/teamcity/checks/sasslint.sh index 4c2ddf5ce8612..45b90f6a8034e 100755 --- a/.ci/teamcity/checks/verify_dependency_versions.sh +++ b/.ci/teamcity/checks/sasslint.sh @@ -4,4 +4,5 @@ set -euo pipefail source "$(dirname "${0}")/../util.sh" -yarn run grunt run:verifyDependencyVersions +checks-reporter-with-killswitch "Lint: sasslint" \ + node scripts/sasslint diff --git a/.ci/teamcity/checks/telemetry.sh b/.ci/teamcity/checks/telemetry.sh index 6413584d2057d..034dd6d647ad3 100755 --- a/.ci/teamcity/checks/telemetry.sh +++ b/.ci/teamcity/checks/telemetry.sh @@ -4,4 +4,5 @@ set -euo pipefail source "$(dirname "${0}")/../util.sh" -yarn run grunt run:telemetryCheck +checks-reporter-with-killswitch "Check Telemetry Schema" \ + node scripts/telemetry_check diff --git a/.ci/teamcity/checks/test_hardening.sh b/.ci/teamcity/checks/test_hardening.sh index 21ee68e5ade70..5799a0b44133b 100755 --- a/.ci/teamcity/checks/test_hardening.sh +++ b/.ci/teamcity/checks/test_hardening.sh @@ -4,4 +4,5 @@ set -euo pipefail source "$(dirname "${0}")/../util.sh" -yarn run grunt run:test_hardening +checks-reporter-with-killswitch "Test Hardening" \ + node scripts/test_hardening diff --git a/.ci/teamcity/checks/ts_projects.sh b/.ci/teamcity/checks/ts_projects.sh index 8afc195fee555..9d1c898090def 100755 --- a/.ci/teamcity/checks/ts_projects.sh +++ b/.ci/teamcity/checks/ts_projects.sh @@ -4,4 +4,5 @@ set -euo pipefail source "$(dirname "${0}")/../util.sh" -yarn run grunt run:checkTsProjects +checks-reporter-with-killswitch "Check TypeScript Projects" \ + node scripts/check_ts_projects diff --git a/.ci/teamcity/checks/type_check.sh b/.ci/teamcity/checks/type_check.sh index da8ae3373d976..d465e8f4c52b4 100755 --- a/.ci/teamcity/checks/type_check.sh +++ b/.ci/teamcity/checks/type_check.sh @@ -4,4 +4,5 @@ set -euo pipefail source "$(dirname "${0}")/../util.sh" -yarn run grunt run:typeCheck +checks-reporter-with-killswitch "Check Types" \ + node scripts/type_check diff --git a/.ci/teamcity/checks/verify_notice.sh b/.ci/teamcity/checks/verify_notice.sh index 8571e0bbceb13..636dc35555f67 100755 --- a/.ci/teamcity/checks/verify_notice.sh +++ b/.ci/teamcity/checks/verify_notice.sh @@ -4,4 +4,5 @@ set -euo pipefail source "$(dirname "${0}")/../util.sh" -yarn run grunt run:verifyNotice +checks-reporter-with-killswitch "Verify NOTICE" \ + node scripts/notice --validate diff --git a/.ci/teamcity/default/jest.sh b/.ci/teamcity/default/jest.sh new file mode 100755 index 0000000000000..93ca7f76f3a21 --- /dev/null +++ b/.ci/teamcity/default/jest.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +set -euo pipefail + +source "$(dirname "${0}")/../util.sh" + +export JOB=kibana-default-jest + +cd "$XPACK_DIR" + +checks-reporter-with-killswitch "Jest Unit Tests" \ + node scripts/jest --bail --debug diff --git a/.ci/teamcity/oss/api_integration.sh b/.ci/teamcity/oss/api_integration.sh new file mode 100755 index 0000000000000..37241bdbdc075 --- /dev/null +++ b/.ci/teamcity/oss/api_integration.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +set -euo pipefail + +source "$(dirname "${0}")/../util.sh" + +export JOB=kibana-oss-api-integration + +checks-reporter-with-killswitch "API Integration Tests" \ + node scripts/functional_tests --config test/api_integration/config.js --bail --debug diff --git a/.ci/teamcity/oss/jest.sh b/.ci/teamcity/oss/jest.sh new file mode 100755 index 0000000000000..3ba9ab0c31c57 --- /dev/null +++ b/.ci/teamcity/oss/jest.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +set -euo pipefail + +source "$(dirname "${0}")/../util.sh" + +export JOB=kibana-oss-jest + +checks-reporter-with-killswitch "OSS Jest Unit Tests" \ + node scripts/jest --ci --verbose diff --git a/.ci/teamcity/oss/jest_integration.sh b/.ci/teamcity/oss/jest_integration.sh new file mode 100755 index 0000000000000..1a23c46c8a2c2 --- /dev/null +++ b/.ci/teamcity/oss/jest_integration.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +set -euo pipefail + +source "$(dirname "${0}")/../util.sh" + +export JOB=kibana-oss-jest-integration + +checks-reporter-with-killswitch "OSS Jest Integration Tests" \ + node scripts/jest_integration --verbose diff --git a/.ci/teamcity/oss/plugin_functional.sh b/.ci/teamcity/oss/plugin_functional.sh index 41ff549945c0b..5d1ecbcbd48ee 100755 --- a/.ci/teamcity/oss/plugin_functional.sh +++ b/.ci/teamcity/oss/plugin_functional.sh @@ -13,6 +13,6 @@ if [[ ! -d "target" ]]; then fi cd - -yarn run grunt run:pluginFunctionalTestsRelease --from=source -yarn run grunt run:exampleFunctionalTestsRelease --from=source -yarn run grunt run:interpreterFunctionalTestsRelease +./test/scripts/test/plugin_functional.sh +./test/scripts/test/example_functional.sh +./test/scripts/test/interpreter_functional.sh diff --git a/.ci/teamcity/oss/server_integration.sh b/.ci/teamcity/oss/server_integration.sh new file mode 100755 index 0000000000000..ddeef77907c49 --- /dev/null +++ b/.ci/teamcity/oss/server_integration.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +set -euo pipefail + +source "$(dirname "${0}")/../util.sh" + +export JOB=kibana-oss-server-integration +export KIBANA_INSTALL_DIR="$PARENT_DIR/build/kibana-build-oss" + +checks-reporter-with-killswitch "Server integration tests" \ + node scripts/functional_tests \ + --config test/server_integration/http/ssl/config.js \ + --config test/server_integration/http/ssl_redirect/config.js \ + --config test/server_integration/http/platform/config.ts \ + --config test/server_integration/http/ssl_with_p12/config.js \ + --config test/server_integration/http/ssl_with_p12_intermediate/config.js \ + --bail \ + --debug \ + --kibana-install-dir $KIBANA_INSTALL_DIR diff --git a/.ci/teamcity/tests/mocha.sh b/.ci/teamcity/tests/mocha.sh index ea6c43c39e397..acb088220fa78 100755 --- a/.ci/teamcity/tests/mocha.sh +++ b/.ci/teamcity/tests/mocha.sh @@ -4,4 +4,5 @@ set -euo pipefail source "$(dirname "${0}")/../util.sh" -yarn run grunt run:mocha +checks-reporter-with-killswitch "Mocha Tests" \ + node scripts/mocha diff --git a/.ci/teamcity/tests/test_hardening.sh b/.ci/teamcity/tests/test_hardening.sh deleted file mode 100755 index 21ee68e5ade70..0000000000000 --- a/.ci/teamcity/tests/test_hardening.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -source "$(dirname "${0}")/../util.sh" - -yarn run grunt run:test_hardening diff --git a/.ci/teamcity/tests/test_projects.sh b/.ci/teamcity/tests/test_projects.sh index 3feaa821424e1..2553650930392 100755 --- a/.ci/teamcity/tests/test_projects.sh +++ b/.ci/teamcity/tests/test_projects.sh @@ -4,4 +4,5 @@ set -euo pipefail source "$(dirname "${0}")/../util.sh" -yarn run grunt run:test_projects +checks-reporter-with-killswitch "Test Projects" \ + yarn kbn run test --exclude kibana --oss --skip-kibana-plugins diff --git a/.teamcity/src/builds/Lint.kt b/.teamcity/src/builds/Lint.kt index 0b3b3b013b5ec..d02f1c9038aca 100644 --- a/.teamcity/src/builds/Lint.kt +++ b/.teamcity/src/builds/Lint.kt @@ -17,7 +17,7 @@ object Lint : BuildType({ scriptContent = """ #!/bin/bash - yarn run grunt run:sasslint + ./.ci/teamcity/checks/sasslint.sh """.trimIndent() } @@ -26,7 +26,7 @@ object Lint : BuildType({ scriptContent = """ #!/bin/bash - yarn run grunt run:eslint + ./.ci/teamcity/checks/eslint.sh """.trimIndent() } } diff --git a/.teamcity/src/builds/test/ApiServerIntegration.kt b/.teamcity/src/builds/test/ApiServerIntegration.kt index d595840c879e6..ca58b628cbd22 100644 --- a/.teamcity/src/builds/test/ApiServerIntegration.kt +++ b/.teamcity/src/builds/test/ApiServerIntegration.kt @@ -9,8 +9,8 @@ object ApiServerIntegration : BuildType({ description = "Executes API and Server Integration Tests" steps { - runbld("API Integration", "yarn run grunt run:apiIntegrationTests") - runbld("Server Integration", "yarn run grunt run:serverIntegrationTests") + runbld("API Integration", "./.ci/teamcity/oss/api_integration.sh") + runbld("Server Integration", "./.ci/teamcity/oss/server_integration.sh") } addTestSettings() diff --git a/.teamcity/src/builds/test/Jest.kt b/.teamcity/src/builds/test/Jest.kt index 04217a4e99b1c..c33c9c2678ca4 100644 --- a/.teamcity/src/builds/test/Jest.kt +++ b/.teamcity/src/builds/test/Jest.kt @@ -12,7 +12,7 @@ object Jest : BuildType({ kibanaAgent(8) steps { - runbld("Jest Unit", "yarn run grunt run:test_jest") + runbld("Jest Unit", "./.ci/teamcity/oss/jest.sh") } addTestSettings() diff --git a/.teamcity/src/builds/test/JestIntegration.kt b/.teamcity/src/builds/test/JestIntegration.kt index 9ec1360dcb1d7..7d44e41493b2b 100644 --- a/.teamcity/src/builds/test/JestIntegration.kt +++ b/.teamcity/src/builds/test/JestIntegration.kt @@ -9,7 +9,7 @@ object JestIntegration : BuildType({ description = "Executes Jest Integration Tests" steps { - runbld("Jest Integration", "yarn run grunt run:test_jest_integration") + runbld("Jest Integration", "./.ci/teamcity/oss/jest_integration.sh") } addTestSettings() diff --git a/.teamcity/src/builds/test/QuickTests.kt b/.teamcity/src/builds/test/QuickTests.kt index cca10cc3f2aa2..5b1d2541480ad 100644 --- a/.teamcity/src/builds/test/QuickTests.kt +++ b/.teamcity/src/builds/test/QuickTests.kt @@ -12,7 +12,7 @@ object QuickTests : BuildType({ kibanaAgent(2) val testScripts = mapOf( - "Test Hardening" to ".ci/teamcity/tests/test_hardening.sh", + "Test Hardening" to ".ci/teamcity/checkes/test_hardening.sh", "Test Projects" to ".ci/teamcity/tests/test_projects.sh", "Mocha Tests" to ".ci/teamcity/tests/mocha.sh" ) diff --git a/.teamcity/src/builds/test/XPackJest.kt b/.teamcity/src/builds/test/XPackJest.kt index 1958d39183bae..8246b60823ff9 100644 --- a/.teamcity/src/builds/test/XPackJest.kt +++ b/.teamcity/src/builds/test/XPackJest.kt @@ -12,10 +12,7 @@ object XPackJest : BuildType({ kibanaAgent(16) steps { - runbld("X-Pack Jest Unit", """ - cd x-pack - node --max-old-space-size=6144 scripts/jest --ci --verbose --maxWorkers=6 - """.trimIndent()) + runbld("X-Pack Jest Unit", "./.ci/teamcity/default/jest.sh") } addTestSettings() diff --git a/docs/development/core/public/kibana-plugin-core-public.httpsetup.externalurl.md b/docs/development/core/public/kibana-plugin-core-public.httpsetup.externalurl.md new file mode 100644 index 0000000000000..b26c9d371e496 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.httpsetup.externalurl.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [HttpSetup](./kibana-plugin-core-public.httpsetup.md) > [externalUrl](./kibana-plugin-core-public.httpsetup.externalurl.md) + +## HttpSetup.externalUrl property + +Signature: + +```typescript +externalUrl: IExternalUrl; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.httpsetup.md b/docs/development/core/public/kibana-plugin-core-public.httpsetup.md index bb43e9f588a72..b8a99cbb62353 100644 --- a/docs/development/core/public/kibana-plugin-core-public.httpsetup.md +++ b/docs/development/core/public/kibana-plugin-core-public.httpsetup.md @@ -18,6 +18,7 @@ export interface HttpSetup | [anonymousPaths](./kibana-plugin-core-public.httpsetup.anonymouspaths.md) | IAnonymousPaths | APIs for denoting certain paths for not requiring authentication | | [basePath](./kibana-plugin-core-public.httpsetup.basepath.md) | IBasePath | APIs for manipulating the basePath on URL segments. See [IBasePath](./kibana-plugin-core-public.ibasepath.md) | | [delete](./kibana-plugin-core-public.httpsetup.delete.md) | HttpHandler | Makes an HTTP request with the DELETE method. See [HttpHandler](./kibana-plugin-core-public.httphandler.md) for options. | +| [externalUrl](./kibana-plugin-core-public.httpsetup.externalurl.md) | IExternalUrl | | | [fetch](./kibana-plugin-core-public.httpsetup.fetch.md) | HttpHandler | Makes an HTTP request. Defaults to a GET request unless overriden. See [HttpHandler](./kibana-plugin-core-public.httphandler.md) for options. | | [get](./kibana-plugin-core-public.httpsetup.get.md) | HttpHandler | Makes an HTTP request with the GET method. See [HttpHandler](./kibana-plugin-core-public.httphandler.md) for options. | | [head](./kibana-plugin-core-public.httpsetup.head.md) | HttpHandler | Makes an HTTP request with the HEAD method. See [HttpHandler](./kibana-plugin-core-public.httphandler.md) for options. | diff --git a/docs/development/core/public/kibana-plugin-core-public.iexternalurl.md b/docs/development/core/public/kibana-plugin-core-public.iexternalurl.md new file mode 100644 index 0000000000000..5a598281c7be7 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.iexternalurl.md @@ -0,0 +1,20 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [IExternalUrl](./kibana-plugin-core-public.iexternalurl.md) + +## IExternalUrl interface + +APIs for working with external URLs. + +Signature: + +```typescript +export interface IExternalUrl +``` + +## Methods + +| Method | Description | +| --- | --- | +| [validateUrl(relativeOrAbsoluteUrl)](./kibana-plugin-core-public.iexternalurl.validateurl.md) | Determines if the provided URL is a valid location to send users. Validation is based on the configured allow list in kibana.yml.If the URL is valid, then a URL will be returned. Otherwise, this will return null. | + diff --git a/docs/development/core/public/kibana-plugin-core-public.iexternalurl.validateurl.md b/docs/development/core/public/kibana-plugin-core-public.iexternalurl.validateurl.md new file mode 100644 index 0000000000000..466d7cfebf547 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.iexternalurl.validateurl.md @@ -0,0 +1,26 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [IExternalUrl](./kibana-plugin-core-public.iexternalurl.md) > [validateUrl](./kibana-plugin-core-public.iexternalurl.validateurl.md) + +## IExternalUrl.validateUrl() method + +Determines if the provided URL is a valid location to send users. Validation is based on the configured allow list in kibana.yml. + +If the URL is valid, then a URL will be returned. Otherwise, this will return null. + +Signature: + +```typescript +validateUrl(relativeOrAbsoluteUrl: string): URL | null; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| relativeOrAbsoluteUrl | string | | + +Returns: + +`URL | null` + diff --git a/docs/development/core/public/kibana-plugin-core-public.iexternalurlpolicy.allow.md b/docs/development/core/public/kibana-plugin-core-public.iexternalurlpolicy.allow.md new file mode 100644 index 0000000000000..ec7129a43b99a --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.iexternalurlpolicy.allow.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [IExternalUrlPolicy](./kibana-plugin-core-public.iexternalurlpolicy.md) > [allow](./kibana-plugin-core-public.iexternalurlpolicy.allow.md) + +## IExternalUrlPolicy.allow property + +Indicates if this policy allows or denies access to the described destination. + +Signature: + +```typescript +allow: boolean; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.iexternalurlpolicy.host.md b/docs/development/core/public/kibana-plugin-core-public.iexternalurlpolicy.host.md new file mode 100644 index 0000000000000..5551d52cc1226 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.iexternalurlpolicy.host.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [IExternalUrlPolicy](./kibana-plugin-core-public.iexternalurlpolicy.md) > [host](./kibana-plugin-core-public.iexternalurlpolicy.host.md) + +## IExternalUrlPolicy.host property + +Optional host describing the external destination. May be combined with `protocol`. Required if `protocol` is not defined. + +Signature: + +```typescript +host?: string; +``` + +## Example + + +```ts +// allows access to all of google.com, using any protocol. +allow: true, +host: 'google.com' + +``` + diff --git a/docs/development/core/public/kibana-plugin-core-public.iexternalurlpolicy.md b/docs/development/core/public/kibana-plugin-core-public.iexternalurlpolicy.md new file mode 100644 index 0000000000000..a87dc69d79e23 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.iexternalurlpolicy.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [IExternalUrlPolicy](./kibana-plugin-core-public.iexternalurlpolicy.md) + +## IExternalUrlPolicy interface + +A policy describing whether access to an external destination is allowed. + +Signature: + +```typescript +export interface IExternalUrlPolicy +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [allow](./kibana-plugin-core-public.iexternalurlpolicy.allow.md) | boolean | Indicates if this policy allows or denies access to the described destination. | +| [host](./kibana-plugin-core-public.iexternalurlpolicy.host.md) | string | Optional host describing the external destination. May be combined with protocol. Required if protocol is not defined. | +| [protocol](./kibana-plugin-core-public.iexternalurlpolicy.protocol.md) | string | Optional protocol describing the external destination. May be combined with host. Required if host is not defined. | + diff --git a/docs/development/core/public/kibana-plugin-core-public.iexternalurlpolicy.protocol.md b/docs/development/core/public/kibana-plugin-core-public.iexternalurlpolicy.protocol.md new file mode 100644 index 0000000000000..67b9b439a54f6 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.iexternalurlpolicy.protocol.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [IExternalUrlPolicy](./kibana-plugin-core-public.iexternalurlpolicy.md) > [protocol](./kibana-plugin-core-public.iexternalurlpolicy.protocol.md) + +## IExternalUrlPolicy.protocol property + +Optional protocol describing the external destination. May be combined with `host`. Required if `host` is not defined. + +Signature: + +```typescript +protocol?: string; +``` + +## Example + + +```ts +// allows access to all destinations over the `https` protocol. +allow: true, +protocol: 'https' + +``` + diff --git a/docs/development/core/public/kibana-plugin-core-public.md b/docs/development/core/public/kibana-plugin-core-public.md index 5f656b9ca510d..a3df5d30137df 100644 --- a/docs/development/core/public/kibana-plugin-core-public.md +++ b/docs/development/core/public/kibana-plugin-core-public.md @@ -73,6 +73,8 @@ The plugin integrates with the core system via lifecycle events: `setup` | [IAnonymousPaths](./kibana-plugin-core-public.ianonymouspaths.md) | APIs for denoting paths as not requiring authentication | | [IBasePath](./kibana-plugin-core-public.ibasepath.md) | APIs for manipulating the basePath on URL segments. | | [IContextContainer](./kibana-plugin-core-public.icontextcontainer.md) | An object that handles registration of context providers and configuring handlers with context. | +| [IExternalUrl](./kibana-plugin-core-public.iexternalurl.md) | APIs for working with external URLs. | +| [IExternalUrlPolicy](./kibana-plugin-core-public.iexternalurlpolicy.md) | A policy describing whether access to an external destination is allowed. | | [IHttpFetchError](./kibana-plugin-core-public.ihttpfetcherror.md) | | | [IHttpInterceptController](./kibana-plugin-core-public.ihttpinterceptcontroller.md) | Used to halt a request Promise chain in a [HttpInterceptor](./kibana-plugin-core-public.httpinterceptor.md). | | [IHttpResponseInterceptorOverrides](./kibana-plugin-core-public.ihttpresponseinterceptoroverrides.md) | Properties that can be returned by HttpInterceptor.request to override the response. | diff --git a/docs/development/core/server/kibana-plugin-core-server.iexternalurlconfig.md b/docs/development/core/server/kibana-plugin-core-server.iexternalurlconfig.md new file mode 100644 index 0000000000000..8df4db4aa9b5e --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.iexternalurlconfig.md @@ -0,0 +1,20 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [IExternalUrlConfig](./kibana-plugin-core-server.iexternalurlconfig.md) + +## IExternalUrlConfig interface + +External Url configuration for use in Kibana. + +Signature: + +```typescript +export interface IExternalUrlConfig +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [policy](./kibana-plugin-core-server.iexternalurlconfig.policy.md) | IExternalUrlPolicy[] | A set of policies describing which external urls are allowed. | + diff --git a/docs/development/core/server/kibana-plugin-core-server.iexternalurlconfig.policy.md b/docs/development/core/server/kibana-plugin-core-server.iexternalurlconfig.policy.md new file mode 100644 index 0000000000000..b5b6f07038076 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.iexternalurlconfig.policy.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [IExternalUrlConfig](./kibana-plugin-core-server.iexternalurlconfig.md) > [policy](./kibana-plugin-core-server.iexternalurlconfig.policy.md) + +## IExternalUrlConfig.policy property + +A set of policies describing which external urls are allowed. + +Signature: + +```typescript +readonly policy: IExternalUrlPolicy[]; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.iexternalurlpolicy.allow.md b/docs/development/core/server/kibana-plugin-core-server.iexternalurlpolicy.allow.md new file mode 100644 index 0000000000000..e0c140409dcf0 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.iexternalurlpolicy.allow.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [IExternalUrlPolicy](./kibana-plugin-core-server.iexternalurlpolicy.md) > [allow](./kibana-plugin-core-server.iexternalurlpolicy.allow.md) + +## IExternalUrlPolicy.allow property + +Indicates of this policy allows or denies access to the described destination. + +Signature: + +```typescript +allow: boolean; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.iexternalurlpolicy.host.md b/docs/development/core/server/kibana-plugin-core-server.iexternalurlpolicy.host.md new file mode 100644 index 0000000000000..e65de074f1578 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.iexternalurlpolicy.host.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [IExternalUrlPolicy](./kibana-plugin-core-server.iexternalurlpolicy.md) > [host](./kibana-plugin-core-server.iexternalurlpolicy.host.md) + +## IExternalUrlPolicy.host property + +Optional host describing the external destination. May be combined with `protocol`. Required if `protocol` is not defined. + +Signature: + +```typescript +host?: string; +``` + +## Example + + +```ts +// allows access to all of google.com, using any protocol. +allow: true, +host: 'google.com' + +``` + diff --git a/docs/development/core/server/kibana-plugin-core-server.iexternalurlpolicy.md b/docs/development/core/server/kibana-plugin-core-server.iexternalurlpolicy.md new file mode 100644 index 0000000000000..8e3658a10ed81 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.iexternalurlpolicy.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [IExternalUrlPolicy](./kibana-plugin-core-server.iexternalurlpolicy.md) + +## IExternalUrlPolicy interface + +A policy describing whether access to an external destination is allowed. + +Signature: + +```typescript +export interface IExternalUrlPolicy +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [allow](./kibana-plugin-core-server.iexternalurlpolicy.allow.md) | boolean | Indicates of this policy allows or denies access to the described destination. | +| [host](./kibana-plugin-core-server.iexternalurlpolicy.host.md) | string | Optional host describing the external destination. May be combined with protocol. Required if protocol is not defined. | +| [protocol](./kibana-plugin-core-server.iexternalurlpolicy.protocol.md) | string | Optional protocol describing the external destination. May be combined with host. Required if host is not defined. | + diff --git a/docs/development/core/server/kibana-plugin-core-server.iexternalurlpolicy.protocol.md b/docs/development/core/server/kibana-plugin-core-server.iexternalurlpolicy.protocol.md new file mode 100644 index 0000000000000..00c5d05eb0cc4 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.iexternalurlpolicy.protocol.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [IExternalUrlPolicy](./kibana-plugin-core-server.iexternalurlpolicy.md) > [protocol](./kibana-plugin-core-server.iexternalurlpolicy.protocol.md) + +## IExternalUrlPolicy.protocol property + +Optional protocol describing the external destination. May be combined with `host`. Required if `host` is not defined. + +Signature: + +```typescript +protocol?: string; +``` + +## Example + + +```ts +// allows access to all destinations over the `https` protocol. +allow: true, +protocol: 'https' + +``` + diff --git a/docs/development/core/server/kibana-plugin-core-server.md b/docs/development/core/server/kibana-plugin-core-server.md index 1a4209ff87c5b..269db90c4db9b 100644 --- a/docs/development/core/server/kibana-plugin-core-server.md +++ b/docs/development/core/server/kibana-plugin-core-server.md @@ -94,6 +94,8 @@ The plugin integrates with the core system via lifecycle events: `setup` | [IContextContainer](./kibana-plugin-core-server.icontextcontainer.md) | An object that handles registration of context providers and configuring handlers with context. | | [ICspConfig](./kibana-plugin-core-server.icspconfig.md) | CSP configuration for use in Kibana. | | [ICustomClusterClient](./kibana-plugin-core-server.icustomclusterclient.md) | See [IClusterClient](./kibana-plugin-core-server.iclusterclient.md) | +| [IExternalUrlConfig](./kibana-plugin-core-server.iexternalurlconfig.md) | External Url configuration for use in Kibana. | +| [IExternalUrlPolicy](./kibana-plugin-core-server.iexternalurlpolicy.md) | A policy describing whether access to an external destination is allowed. | | [IKibanaResponse](./kibana-plugin-core-server.ikibanaresponse.md) | A response data object, expected to returned as a result of [RequestHandler](./kibana-plugin-core-server.requesthandler.md) execution | | [IKibanaSocket](./kibana-plugin-core-server.ikibanasocket.md) | A tiny abstraction for TCP socket. | | [ImageValidation](./kibana-plugin-core-server.imagevalidation.md) | | diff --git a/package.json b/package.json index 513d9b907c96c..1295217b4bcbe 100644 --- a/package.json +++ b/package.json @@ -47,7 +47,6 @@ "test:jest": "node scripts/jest", "test:jest_integration": "node scripts/jest_integration", "test:mocha": "node scripts/mocha", - "test:mocha:coverage": "grunt test:mochaCoverage", "test:ftr": "node scripts/functional_tests", "test:ftr:server": "node scripts/functional_tests_server", "test:ftr:runner": "node scripts/functional_test_runner", @@ -85,6 +84,7 @@ "**/@types/hapi__hapi": "^18.2.6", "**/@types/hapi__mimos": "4.1.0", "**/@types/node": "14.14.7", + "**/chokidar": "^3.4.3", "**/cross-fetch/node-fetch": "^2.6.1", "**/deepmerge": "^4.2.2", "**/fast-deep-equal": "^3.1.1", @@ -175,7 +175,7 @@ "chalk": "^4.1.0", "check-disk-space": "^2.1.0", "cheerio": "0.22.0", - "chokidar": "^3.4.2", + "chokidar": "^3.4.3", "chroma-js": "^1.4.1", "classnames": "2.2.6", "color": "1.0.3", @@ -354,7 +354,7 @@ "@cypress/webpack-preprocessor": "^5.4.11", "@elastic/apm-rum": "^5.6.1", "@elastic/apm-rum-react": "^1.2.5", - "@elastic/charts": "24.3.0", + "@elastic/charts": "24.4.0", "@elastic/eslint-config-kibana": "link:packages/elastic-eslint-config-kibana", "@elastic/eslint-plugin-eui": "0.0.2", "@elastic/github-checks-reporter": "0.0.20b3", @@ -674,7 +674,6 @@ "grunt-contrib-copy": "^1.0.0", "grunt-contrib-watch": "^1.1.0", "grunt-peg": "^2.0.1", - "grunt-run": "0.8.1", "gulp": "4.0.2", "gulp-babel": "^8.0.0", "gulp-sourcemaps": "2.6.5", diff --git a/packages/kbn-pm/dist/index.js b/packages/kbn-pm/dist/index.js index eb9b7a4a35dc7..922159ab555c8 100644 --- a/packages/kbn-pm/dist/index.js +++ b/packages/kbn-pm/dist/index.js @@ -59762,11 +59762,11 @@ const os = __webpack_require__(121); const pMap = __webpack_require__(514); const arrify = __webpack_require__(509); const globby = __webpack_require__(515); -const hasGlob = __webpack_require__(711); -const cpFile = __webpack_require__(713); -const junk = __webpack_require__(723); -const pFilter = __webpack_require__(724); -const CpyError = __webpack_require__(726); +const hasGlob = __webpack_require__(715); +const cpFile = __webpack_require__(717); +const junk = __webpack_require__(727); +const pFilter = __webpack_require__(728); +const CpyError = __webpack_require__(730); const defaultOptions = { ignoreJunk: true @@ -60014,8 +60014,8 @@ const fs = __webpack_require__(134); const arrayUnion = __webpack_require__(516); const glob = __webpack_require__(147); const fastGlob = __webpack_require__(518); -const dirGlob = __webpack_require__(704); -const gitignore = __webpack_require__(707); +const dirGlob = __webpack_require__(708); +const gitignore = __webpack_require__(711); const DEFAULT_FILTER = () => false; @@ -60266,11 +60266,11 @@ module.exports.generateTasks = pkg.generateTasks; Object.defineProperty(exports, "__esModule", { value: true }); var optionsManager = __webpack_require__(520); var taskManager = __webpack_require__(521); -var reader_async_1 = __webpack_require__(675); -var reader_stream_1 = __webpack_require__(699); -var reader_sync_1 = __webpack_require__(700); -var arrayUtils = __webpack_require__(702); -var streamUtils = __webpack_require__(703); +var reader_async_1 = __webpack_require__(679); +var reader_stream_1 = __webpack_require__(703); +var reader_sync_1 = __webpack_require__(704); +var arrayUtils = __webpack_require__(706); +var streamUtils = __webpack_require__(707); /** * Synchronous API. */ @@ -60851,16 +60851,16 @@ module.exports.win32 = win32; var util = __webpack_require__(112); var braces = __webpack_require__(527); var toRegex = __webpack_require__(528); -var extend = __webpack_require__(641); +var extend = __webpack_require__(645); /** * Local dependencies */ -var compilers = __webpack_require__(643); -var parsers = __webpack_require__(670); -var cache = __webpack_require__(671); -var utils = __webpack_require__(672); +var compilers = __webpack_require__(647); +var parsers = __webpack_require__(674); +var cache = __webpack_require__(675); +var utils = __webpack_require__(676); var MAX_LENGTH = 1024 * 64; /** @@ -61741,8 +61741,8 @@ var extend = __webpack_require__(551); */ var compilers = __webpack_require__(553); -var parsers = __webpack_require__(566); -var Braces = __webpack_require__(570); +var parsers = __webpack_require__(568); +var Braces = __webpack_require__(572); var utils = __webpack_require__(554); var MAX_LENGTH = 1024 * 64; var cache = {}; @@ -64182,7 +64182,7 @@ utils.extend = __webpack_require__(551); utils.flatten = __webpack_require__(558); utils.isObject = __webpack_require__(536); utils.fillRange = __webpack_require__(559); -utils.repeat = __webpack_require__(565); +utils.repeat = __webpack_require__(567); utils.unique = __webpack_require__(550); utils.define = function(obj, key, val) { @@ -64825,9 +64825,9 @@ function flat(arr, res) { var util = __webpack_require__(112); var isNumber = __webpack_require__(560); -var extend = __webpack_require__(551); -var repeat = __webpack_require__(563); -var toRegex = __webpack_require__(564); +var extend = __webpack_require__(563); +var repeat = __webpack_require__(565); +var toRegex = __webpack_require__(566); /** * Return a range of numbers or letters. @@ -65206,6 +65206,66 @@ function isSlowBuffer (obj) { /* 563 */ /***/ (function(module, exports, __webpack_require__) { +"use strict"; + + +var isObject = __webpack_require__(564); + +module.exports = function extend(o/*, objects*/) { + if (!isObject(o)) { o = {}; } + + var len = arguments.length; + for (var i = 1; i < len; i++) { + var obj = arguments[i]; + + if (isObject(obj)) { + assign(o, obj); + } + } + return o; +}; + +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +/** + * Returns true if the given `key` is an own property of `obj`. + */ + +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + + +/***/ }), +/* 564 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +module.exports = function isExtendable(val) { + return typeof val !== 'undefined' && val !== null + && (typeof val === 'object' || typeof val === 'function'); +}; + + +/***/ }), +/* 565 */ +/***/ (function(module, exports, __webpack_require__) { + "use strict"; /*! * repeat-string @@ -65280,7 +65340,7 @@ function repeat(str, num) { /***/ }), -/* 564 */ +/* 566 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -65293,7 +65353,7 @@ function repeat(str, num) { -var repeat = __webpack_require__(563); +var repeat = __webpack_require__(565); var isNumber = __webpack_require__(560); var cache = {}; @@ -65581,7 +65641,7 @@ module.exports = toRegexRange; /***/ }), -/* 565 */ +/* 567 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -65606,13 +65666,13 @@ module.exports = function repeat(ele, num) { /***/ }), -/* 566 */ +/* 568 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var Node = __webpack_require__(567); +var Node = __webpack_require__(569); var utils = __webpack_require__(554); /** @@ -65973,15 +66033,15 @@ function concatNodes(pos, node, parent, options) { /***/ }), -/* 567 */ +/* 569 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isObject = __webpack_require__(536); -var define = __webpack_require__(568); -var utils = __webpack_require__(569); +var define = __webpack_require__(570); +var utils = __webpack_require__(571); var ownNames; /** @@ -66472,7 +66532,7 @@ exports = module.exports = Node; /***/ }), -/* 568 */ +/* 570 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -66510,7 +66570,7 @@ module.exports = function defineProperty(obj, prop, val) { /***/ }), -/* 569 */ +/* 571 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -67536,16 +67596,16 @@ function assert(val, message) { /***/ }), -/* 570 */ +/* 572 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var extend = __webpack_require__(551); -var Snapdragon = __webpack_require__(571); +var Snapdragon = __webpack_require__(573); var compilers = __webpack_require__(553); -var parsers = __webpack_require__(566); +var parsers = __webpack_require__(568); var utils = __webpack_require__(554); /** @@ -67647,17 +67707,17 @@ module.exports = Braces; /***/ }), -/* 571 */ +/* 573 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var Base = __webpack_require__(572); -var define = __webpack_require__(599); -var Compiler = __webpack_require__(609); -var Parser = __webpack_require__(638); -var utils = __webpack_require__(618); +var Base = __webpack_require__(574); +var define = __webpack_require__(603); +var Compiler = __webpack_require__(613); +var Parser = __webpack_require__(642); +var utils = __webpack_require__(622); var regexCache = {}; var cache = {}; @@ -67828,20 +67888,20 @@ module.exports.Parser = Parser; /***/ }), -/* 572 */ +/* 574 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var util = __webpack_require__(112); -var define = __webpack_require__(573); -var CacheBase = __webpack_require__(574); -var Emitter = __webpack_require__(575); +var define = __webpack_require__(575); +var CacheBase = __webpack_require__(576); +var Emitter = __webpack_require__(577); var isObject = __webpack_require__(536); -var merge = __webpack_require__(593); -var pascal = __webpack_require__(596); -var cu = __webpack_require__(597); +var merge = __webpack_require__(597); +var pascal = __webpack_require__(600); +var cu = __webpack_require__(601); /** * Optionally define a custom `cache` namespace to use. @@ -68270,7 +68330,7 @@ module.exports.namespace = namespace; /***/ }), -/* 573 */ +/* 575 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -68308,21 +68368,21 @@ module.exports = function defineProperty(obj, prop, val) { /***/ }), -/* 574 */ +/* 576 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isObject = __webpack_require__(536); -var Emitter = __webpack_require__(575); -var visit = __webpack_require__(576); -var toPath = __webpack_require__(579); -var union = __webpack_require__(580); -var del = __webpack_require__(584); -var get = __webpack_require__(582); -var has = __webpack_require__(589); -var set = __webpack_require__(592); +var Emitter = __webpack_require__(577); +var visit = __webpack_require__(578); +var toPath = __webpack_require__(581); +var union = __webpack_require__(582); +var del = __webpack_require__(588); +var get = __webpack_require__(585); +var has = __webpack_require__(593); +var set = __webpack_require__(596); /** * Create a `Cache` constructor that when instantiated will @@ -68576,7 +68636,7 @@ module.exports.namespace = namespace; /***/ }), -/* 575 */ +/* 577 */ /***/ (function(module, exports, __webpack_require__) { @@ -68745,7 +68805,7 @@ Emitter.prototype.hasListeners = function(event){ /***/ }), -/* 576 */ +/* 578 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -68758,8 +68818,8 @@ Emitter.prototype.hasListeners = function(event){ -var visit = __webpack_require__(577); -var mapVisit = __webpack_require__(578); +var visit = __webpack_require__(579); +var mapVisit = __webpack_require__(580); module.exports = function(collection, method, val) { var result; @@ -68782,7 +68842,7 @@ module.exports = function(collection, method, val) { /***/ }), -/* 577 */ +/* 579 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -68822,14 +68882,14 @@ module.exports = function visit(thisArg, method, target, val) { /***/ }), -/* 578 */ +/* 580 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var util = __webpack_require__(112); -var visit = __webpack_require__(577); +var visit = __webpack_require__(579); /** * Map `visit` over an array of objects. @@ -68866,7 +68926,7 @@ function isObject(val) { /***/ }), -/* 579 */ +/* 581 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -68906,16 +68966,16 @@ function filter(arr) { /***/ }), -/* 580 */ +/* 582 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isObject = __webpack_require__(552); -var union = __webpack_require__(581); -var get = __webpack_require__(582); -var set = __webpack_require__(583); +var isObject = __webpack_require__(583); +var union = __webpack_require__(584); +var get = __webpack_require__(585); +var set = __webpack_require__(586); module.exports = function unionValue(obj, prop, value) { if (!isObject(obj)) { @@ -68943,7 +69003,27 @@ function arrayify(val) { /***/ }), -/* 581 */ +/* 583 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +module.exports = function isExtendable(val) { + return typeof val !== 'undefined' && val !== null + && (typeof val === 'object' || typeof val === 'function'); +}; + + +/***/ }), +/* 584 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -68979,7 +69059,7 @@ module.exports = function union(init) { /***/ }), -/* 582 */ +/* 585 */ /***/ (function(module, exports) { /*! @@ -69035,7 +69115,7 @@ function toString(val) { /***/ }), -/* 583 */ +/* 586 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -69049,9 +69129,9 @@ function toString(val) { var split = __webpack_require__(555); -var extend = __webpack_require__(551); +var extend = __webpack_require__(587); var isPlainObject = __webpack_require__(545); -var isObject = __webpack_require__(552); +var isObject = __webpack_require__(583); module.exports = function(obj, prop, val) { if (!isObject(obj)) { @@ -69097,7 +69177,47 @@ function isValidKey(key) { /***/ }), -/* 584 */ +/* 587 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isObject = __webpack_require__(583); + +module.exports = function extend(o/*, objects*/) { + if (!isObject(o)) { o = {}; } + + var len = arguments.length; + for (var i = 1; i < len; i++) { + var obj = arguments[i]; + + if (isObject(obj)) { + assign(o, obj); + } + } + return o; +}; + +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +/** + * Returns true if the given `key` is an own property of `obj`. + */ + +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + + +/***/ }), +/* 588 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -69111,7 +69231,7 @@ function isValidKey(key) { var isObject = __webpack_require__(536); -var has = __webpack_require__(585); +var has = __webpack_require__(589); module.exports = function unset(obj, prop) { if (!isObject(obj)) { @@ -69136,7 +69256,7 @@ module.exports = function unset(obj, prop) { /***/ }), -/* 585 */ +/* 589 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -69149,9 +69269,9 @@ module.exports = function unset(obj, prop) { -var isObject = __webpack_require__(586); -var hasValues = __webpack_require__(588); -var get = __webpack_require__(582); +var isObject = __webpack_require__(590); +var hasValues = __webpack_require__(592); +var get = __webpack_require__(585); module.exports = function(obj, prop, noZero) { if (isObject(obj)) { @@ -69162,7 +69282,7 @@ module.exports = function(obj, prop, noZero) { /***/ }), -/* 586 */ +/* 590 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -69175,7 +69295,7 @@ module.exports = function(obj, prop, noZero) { -var isArray = __webpack_require__(587); +var isArray = __webpack_require__(591); module.exports = function isObject(val) { return val != null && typeof val === 'object' && isArray(val) === false; @@ -69183,7 +69303,7 @@ module.exports = function isObject(val) { /***/ }), -/* 587 */ +/* 591 */ /***/ (function(module, exports) { var toString = {}.toString; @@ -69194,7 +69314,7 @@ module.exports = Array.isArray || function (arr) { /***/ }), -/* 588 */ +/* 592 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -69237,7 +69357,7 @@ module.exports = function hasValue(o, noZero) { /***/ }), -/* 589 */ +/* 593 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -69251,8 +69371,8 @@ module.exports = function hasValue(o, noZero) { var isObject = __webpack_require__(536); -var hasValues = __webpack_require__(590); -var get = __webpack_require__(582); +var hasValues = __webpack_require__(594); +var get = __webpack_require__(585); module.exports = function(val, prop) { return hasValues(isObject(val) && prop ? get(val, prop) : val); @@ -69260,7 +69380,7 @@ module.exports = function(val, prop) { /***/ }), -/* 590 */ +/* 594 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -69273,7 +69393,7 @@ module.exports = function(val, prop) { -var typeOf = __webpack_require__(591); +var typeOf = __webpack_require__(595); var isNumber = __webpack_require__(560); module.exports = function hasValue(val) { @@ -69327,7 +69447,7 @@ module.exports = function hasValue(val) { /***/ }), -/* 591 */ +/* 595 */ /***/ (function(module, exports, __webpack_require__) { var isBuffer = __webpack_require__(562); @@ -69452,7 +69572,7 @@ module.exports = function kindOf(val) { /***/ }), -/* 592 */ +/* 596 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -69466,9 +69586,9 @@ module.exports = function kindOf(val) { var split = __webpack_require__(555); -var extend = __webpack_require__(551); +var extend = __webpack_require__(587); var isPlainObject = __webpack_require__(545); -var isObject = __webpack_require__(552); +var isObject = __webpack_require__(583); module.exports = function(obj, prop, val) { if (!isObject(obj)) { @@ -69514,14 +69634,14 @@ function isValidKey(key) { /***/ }), -/* 593 */ +/* 597 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isExtendable = __webpack_require__(594); -var forIn = __webpack_require__(595); +var isExtendable = __webpack_require__(598); +var forIn = __webpack_require__(599); function mixinDeep(target, objects) { var len = arguments.length, i = 0; @@ -69585,7 +69705,7 @@ module.exports = mixinDeep; /***/ }), -/* 594 */ +/* 598 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -69606,7 +69726,7 @@ module.exports = function isExtendable(val) { /***/ }), -/* 595 */ +/* 599 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -69629,7 +69749,7 @@ module.exports = function forIn(obj, fn, thisArg) { /***/ }), -/* 596 */ +/* 600 */ /***/ (function(module, exports) { /*! @@ -69656,14 +69776,14 @@ module.exports = pascalcase; /***/ }), -/* 597 */ +/* 601 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var util = __webpack_require__(112); -var utils = __webpack_require__(598); +var utils = __webpack_require__(602); /** * Expose class utils @@ -70028,7 +70148,7 @@ cu.bubble = function(Parent, events) { /***/ }), -/* 598 */ +/* 602 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -70042,10 +70162,10 @@ var utils = {}; * Lazily required module dependencies */ -utils.union = __webpack_require__(581); -utils.define = __webpack_require__(599); +utils.union = __webpack_require__(584); +utils.define = __webpack_require__(603); utils.isObj = __webpack_require__(536); -utils.staticExtend = __webpack_require__(606); +utils.staticExtend = __webpack_require__(610); /** @@ -70056,7 +70176,7 @@ module.exports = utils; /***/ }), -/* 599 */ +/* 603 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -70069,7 +70189,7 @@ module.exports = utils; -var isDescriptor = __webpack_require__(600); +var isDescriptor = __webpack_require__(604); module.exports = function defineProperty(obj, prop, val) { if (typeof obj !== 'object' && typeof obj !== 'function') { @@ -70094,7 +70214,7 @@ module.exports = function defineProperty(obj, prop, val) { /***/ }), -/* 600 */ +/* 604 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -70107,9 +70227,9 @@ module.exports = function defineProperty(obj, prop, val) { -var typeOf = __webpack_require__(601); -var isAccessor = __webpack_require__(602); -var isData = __webpack_require__(604); +var typeOf = __webpack_require__(605); +var isAccessor = __webpack_require__(606); +var isData = __webpack_require__(608); module.exports = function isDescriptor(obj, key) { if (typeOf(obj) !== 'object') { @@ -70123,7 +70243,7 @@ module.exports = function isDescriptor(obj, key) { /***/ }), -/* 601 */ +/* 605 */ /***/ (function(module, exports) { var toString = Object.prototype.toString; @@ -70276,7 +70396,7 @@ function isBuffer(val) { /***/ }), -/* 602 */ +/* 606 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -70289,7 +70409,7 @@ function isBuffer(val) { -var typeOf = __webpack_require__(603); +var typeOf = __webpack_require__(607); // accessor descriptor properties var accessor = { @@ -70352,7 +70472,7 @@ module.exports = isAccessorDescriptor; /***/ }), -/* 603 */ +/* 607 */ /***/ (function(module, exports, __webpack_require__) { var isBuffer = __webpack_require__(562); @@ -70474,7 +70594,7 @@ module.exports = function kindOf(val) { /***/ }), -/* 604 */ +/* 608 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -70487,7 +70607,7 @@ module.exports = function kindOf(val) { -var typeOf = __webpack_require__(605); +var typeOf = __webpack_require__(609); // data descriptor properties var data = { @@ -70536,7 +70656,7 @@ module.exports = isDataDescriptor; /***/ }), -/* 605 */ +/* 609 */ /***/ (function(module, exports, __webpack_require__) { var isBuffer = __webpack_require__(562); @@ -70658,7 +70778,7 @@ module.exports = function kindOf(val) { /***/ }), -/* 606 */ +/* 610 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -70671,8 +70791,8 @@ module.exports = function kindOf(val) { -var copy = __webpack_require__(607); -var define = __webpack_require__(599); +var copy = __webpack_require__(611); +var define = __webpack_require__(603); var util = __webpack_require__(112); /** @@ -70755,15 +70875,15 @@ module.exports = extend; /***/ }), -/* 607 */ +/* 611 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var typeOf = __webpack_require__(561); -var copyDescriptor = __webpack_require__(608); -var define = __webpack_require__(599); +var copyDescriptor = __webpack_require__(612); +var define = __webpack_require__(603); /** * Copy static properties, prototype properties, and descriptors from one object to another. @@ -70936,7 +71056,7 @@ module.exports.has = has; /***/ }), -/* 608 */ +/* 612 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -71024,16 +71144,16 @@ function isObject(val) { /***/ }), -/* 609 */ +/* 613 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var use = __webpack_require__(610); -var define = __webpack_require__(599); -var debug = __webpack_require__(612)('snapdragon:compiler'); -var utils = __webpack_require__(618); +var use = __webpack_require__(614); +var define = __webpack_require__(603); +var debug = __webpack_require__(616)('snapdragon:compiler'); +var utils = __webpack_require__(622); /** * Create a new `Compiler` with the given `options`. @@ -71187,7 +71307,7 @@ Compiler.prototype = { // source map support if (opts.sourcemap) { - var sourcemaps = __webpack_require__(637); + var sourcemaps = __webpack_require__(641); sourcemaps(this); this.mapVisit(this.ast.nodes); this.applySourceMaps(); @@ -71208,7 +71328,7 @@ module.exports = Compiler; /***/ }), -/* 610 */ +/* 614 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -71221,7 +71341,7 @@ module.exports = Compiler; -var utils = __webpack_require__(611); +var utils = __webpack_require__(615); module.exports = function base(app, opts) { if (!utils.isObject(app) && typeof app !== 'function') { @@ -71336,7 +71456,7 @@ module.exports = function base(app, opts) { /***/ }), -/* 611 */ +/* 615 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -71350,7 +71470,7 @@ var utils = {}; * Lazily required module dependencies */ -utils.define = __webpack_require__(599); +utils.define = __webpack_require__(603); utils.isObject = __webpack_require__(536); @@ -71366,7 +71486,7 @@ module.exports = utils; /***/ }), -/* 612 */ +/* 616 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -71375,14 +71495,14 @@ module.exports = utils; */ if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __webpack_require__(613); + module.exports = __webpack_require__(617); } else { - module.exports = __webpack_require__(616); + module.exports = __webpack_require__(620); } /***/ }), -/* 613 */ +/* 617 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -71391,7 +71511,7 @@ if (typeof process !== 'undefined' && process.type === 'renderer') { * Expose `debug()` as the module. */ -exports = module.exports = __webpack_require__(614); +exports = module.exports = __webpack_require__(618); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; @@ -71573,7 +71693,7 @@ function localstorage() { /***/ }), -/* 614 */ +/* 618 */ /***/ (function(module, exports, __webpack_require__) { @@ -71589,7 +71709,7 @@ exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; -exports.humanize = __webpack_require__(615); +exports.humanize = __webpack_require__(619); /** * The currently active debug mode names, and names to skip. @@ -71781,7 +71901,7 @@ function coerce(val) { /***/ }), -/* 615 */ +/* 619 */ /***/ (function(module, exports) { /** @@ -71939,7 +72059,7 @@ function plural(ms, n, name) { /***/ }), -/* 616 */ +/* 620 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -71955,7 +72075,7 @@ var util = __webpack_require__(112); * Expose `debug()` as the module. */ -exports = module.exports = __webpack_require__(614); +exports = module.exports = __webpack_require__(618); exports.init = init; exports.log = log; exports.formatArgs = formatArgs; @@ -72134,7 +72254,7 @@ function createWritableStdioStream (fd) { case 'PIPE': case 'TCP': - var net = __webpack_require__(617); + var net = __webpack_require__(621); stream = new net.Socket({ fd: fd, readable: false, @@ -72193,13 +72313,13 @@ exports.enable(load()); /***/ }), -/* 617 */ +/* 621 */ /***/ (function(module, exports) { module.exports = require("net"); /***/ }), -/* 618 */ +/* 622 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -72209,9 +72329,9 @@ module.exports = require("net"); * Module dependencies */ -exports.extend = __webpack_require__(551); -exports.SourceMap = __webpack_require__(619); -exports.sourceMapResolve = __webpack_require__(630); +exports.extend = __webpack_require__(587); +exports.SourceMap = __webpack_require__(623); +exports.sourceMapResolve = __webpack_require__(634); /** * Convert backslash in the given string to forward slashes @@ -72254,7 +72374,7 @@ exports.last = function(arr, n) { /***/ }), -/* 619 */ +/* 623 */ /***/ (function(module, exports, __webpack_require__) { /* @@ -72262,13 +72382,13 @@ exports.last = function(arr, n) { * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ -exports.SourceMapGenerator = __webpack_require__(620).SourceMapGenerator; -exports.SourceMapConsumer = __webpack_require__(626).SourceMapConsumer; -exports.SourceNode = __webpack_require__(629).SourceNode; +exports.SourceMapGenerator = __webpack_require__(624).SourceMapGenerator; +exports.SourceMapConsumer = __webpack_require__(630).SourceMapConsumer; +exports.SourceNode = __webpack_require__(633).SourceNode; /***/ }), -/* 620 */ +/* 624 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -72278,10 +72398,10 @@ exports.SourceNode = __webpack_require__(629).SourceNode; * http://opensource.org/licenses/BSD-3-Clause */ -var base64VLQ = __webpack_require__(621); -var util = __webpack_require__(623); -var ArraySet = __webpack_require__(624).ArraySet; -var MappingList = __webpack_require__(625).MappingList; +var base64VLQ = __webpack_require__(625); +var util = __webpack_require__(627); +var ArraySet = __webpack_require__(628).ArraySet; +var MappingList = __webpack_require__(629).MappingList; /** * An instance of the SourceMapGenerator represents a source map which is @@ -72690,7 +72810,7 @@ exports.SourceMapGenerator = SourceMapGenerator; /***/ }), -/* 621 */ +/* 625 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -72730,7 +72850,7 @@ exports.SourceMapGenerator = SourceMapGenerator; * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -var base64 = __webpack_require__(622); +var base64 = __webpack_require__(626); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, @@ -72836,7 +72956,7 @@ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { /***/ }), -/* 622 */ +/* 626 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -72909,7 +73029,7 @@ exports.decode = function (charCode) { /***/ }), -/* 623 */ +/* 627 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -73332,7 +73452,7 @@ exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflate /***/ }), -/* 624 */ +/* 628 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -73342,7 +73462,7 @@ exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflate * http://opensource.org/licenses/BSD-3-Clause */ -var util = __webpack_require__(623); +var util = __webpack_require__(627); var has = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; @@ -73459,7 +73579,7 @@ exports.ArraySet = ArraySet; /***/ }), -/* 625 */ +/* 629 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -73469,7 +73589,7 @@ exports.ArraySet = ArraySet; * http://opensource.org/licenses/BSD-3-Clause */ -var util = __webpack_require__(623); +var util = __webpack_require__(627); /** * Determine whether mappingB is after mappingA with respect to generated @@ -73544,7 +73664,7 @@ exports.MappingList = MappingList; /***/ }), -/* 626 */ +/* 630 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -73554,11 +73674,11 @@ exports.MappingList = MappingList; * http://opensource.org/licenses/BSD-3-Clause */ -var util = __webpack_require__(623); -var binarySearch = __webpack_require__(627); -var ArraySet = __webpack_require__(624).ArraySet; -var base64VLQ = __webpack_require__(621); -var quickSort = __webpack_require__(628).quickSort; +var util = __webpack_require__(627); +var binarySearch = __webpack_require__(631); +var ArraySet = __webpack_require__(628).ArraySet; +var base64VLQ = __webpack_require__(625); +var quickSort = __webpack_require__(632).quickSort; function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; @@ -74632,7 +74752,7 @@ exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; /***/ }), -/* 627 */ +/* 631 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -74749,7 +74869,7 @@ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { /***/ }), -/* 628 */ +/* 632 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -74869,7 +74989,7 @@ exports.quickSort = function (ary, comparator) { /***/ }), -/* 629 */ +/* 633 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -74879,8 +74999,8 @@ exports.quickSort = function (ary, comparator) { * http://opensource.org/licenses/BSD-3-Clause */ -var SourceMapGenerator = __webpack_require__(620).SourceMapGenerator; -var util = __webpack_require__(623); +var SourceMapGenerator = __webpack_require__(624).SourceMapGenerator; +var util = __webpack_require__(627); // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other // operating systems these days (capturing the result). @@ -75288,17 +75408,17 @@ exports.SourceNode = SourceNode; /***/ }), -/* 630 */ +/* 634 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2014, 2015, 2016, 2017 Simon Lydell // X11 (“MIT”) Licensed. (See LICENSE.) -var sourceMappingURL = __webpack_require__(631) -var resolveUrl = __webpack_require__(632) -var decodeUriComponent = __webpack_require__(633) -var urix = __webpack_require__(635) -var atob = __webpack_require__(636) +var sourceMappingURL = __webpack_require__(635) +var resolveUrl = __webpack_require__(636) +var decodeUriComponent = __webpack_require__(637) +var urix = __webpack_require__(639) +var atob = __webpack_require__(640) @@ -75596,7 +75716,7 @@ module.exports = { /***/ }), -/* 631 */ +/* 635 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright 2014 Simon Lydell @@ -75659,7 +75779,7 @@ void (function(root, factory) { /***/ }), -/* 632 */ +/* 636 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2014 Simon Lydell @@ -75677,13 +75797,13 @@ module.exports = resolveUrl /***/ }), -/* 633 */ +/* 637 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2017 Simon Lydell // X11 (“MIT”) Licensed. (See LICENSE.) -var decodeUriComponent = __webpack_require__(634) +var decodeUriComponent = __webpack_require__(638) function customDecodeUriComponent(string) { // `decodeUriComponent` turns `+` into ` `, but that's not wanted. @@ -75694,7 +75814,7 @@ module.exports = customDecodeUriComponent /***/ }), -/* 634 */ +/* 638 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -75795,7 +75915,7 @@ module.exports = function (encodedURI) { /***/ }), -/* 635 */ +/* 639 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2014 Simon Lydell @@ -75818,7 +75938,7 @@ module.exports = urix /***/ }), -/* 636 */ +/* 640 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -75832,7 +75952,7 @@ module.exports = atob.atob = atob; /***/ }), -/* 637 */ +/* 641 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -75840,8 +75960,8 @@ module.exports = atob.atob = atob; var fs = __webpack_require__(134); var path = __webpack_require__(4); -var define = __webpack_require__(599); -var utils = __webpack_require__(618); +var define = __webpack_require__(603); +var utils = __webpack_require__(622); /** * Expose `mixin()`. @@ -75984,19 +76104,19 @@ exports.comment = function(node) { /***/ }), -/* 638 */ +/* 642 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var use = __webpack_require__(610); +var use = __webpack_require__(614); var util = __webpack_require__(112); -var Cache = __webpack_require__(639); -var define = __webpack_require__(599); -var debug = __webpack_require__(612)('snapdragon:parser'); -var Position = __webpack_require__(640); -var utils = __webpack_require__(618); +var Cache = __webpack_require__(643); +var define = __webpack_require__(603); +var debug = __webpack_require__(616)('snapdragon:parser'); +var Position = __webpack_require__(644); +var utils = __webpack_require__(622); /** * Create a new `Parser` with the given `input` and `options`. @@ -76524,7 +76644,7 @@ module.exports = Parser; /***/ }), -/* 639 */ +/* 643 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -76631,13 +76751,13 @@ MapCache.prototype.del = function mapDelete(key) { /***/ }), -/* 640 */ +/* 644 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var define = __webpack_require__(599); +var define = __webpack_require__(603); /** * Store position for a node @@ -76652,13 +76772,13 @@ module.exports = function Position(start, parser) { /***/ }), -/* 641 */ +/* 645 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isExtendable = __webpack_require__(642); +var isExtendable = __webpack_require__(646); var assignSymbols = __webpack_require__(546); module.exports = Object.assign || function(obj/*, objects*/) { @@ -76719,7 +76839,7 @@ function isEnum(obj, key) { /***/ }), -/* 642 */ +/* 646 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -76740,14 +76860,14 @@ module.exports = function isExtendable(val) { /***/ }), -/* 643 */ +/* 647 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var nanomatch = __webpack_require__(644); -var extglob = __webpack_require__(659); +var nanomatch = __webpack_require__(648); +var extglob = __webpack_require__(663); module.exports = function(snapdragon) { var compilers = snapdragon.compiler.compilers; @@ -76824,7 +76944,7 @@ function escapeExtglobs(compiler) { /***/ }), -/* 644 */ +/* 648 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -76836,16 +76956,16 @@ function escapeExtglobs(compiler) { var util = __webpack_require__(112); var toRegex = __webpack_require__(528); -var extend = __webpack_require__(645); +var extend = __webpack_require__(649); /** * Local dependencies */ -var compilers = __webpack_require__(647); -var parsers = __webpack_require__(648); -var cache = __webpack_require__(651); -var utils = __webpack_require__(653); +var compilers = __webpack_require__(651); +var parsers = __webpack_require__(652); +var cache = __webpack_require__(655); +var utils = __webpack_require__(657); var MAX_LENGTH = 1024 * 64; /** @@ -77669,13 +77789,13 @@ module.exports = nanomatch; /***/ }), -/* 645 */ +/* 649 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isExtendable = __webpack_require__(646); +var isExtendable = __webpack_require__(650); var assignSymbols = __webpack_require__(546); module.exports = Object.assign || function(obj/*, objects*/) { @@ -77736,7 +77856,7 @@ function isEnum(obj, key) { /***/ }), -/* 646 */ +/* 650 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -77757,7 +77877,7 @@ module.exports = function isExtendable(val) { /***/ }), -/* 647 */ +/* 651 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -78103,7 +78223,7 @@ module.exports = function(nanomatch, options) { /***/ }), -/* 648 */ +/* 652 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -78111,7 +78231,7 @@ module.exports = function(nanomatch, options) { var regexNot = __webpack_require__(547); var toRegex = __webpack_require__(528); -var isOdd = __webpack_require__(649); +var isOdd = __webpack_require__(653); /** * Characters to use in negation regex (we want to "not" match @@ -78497,7 +78617,7 @@ module.exports.not = NOT_REGEX; /***/ }), -/* 649 */ +/* 653 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -78510,7 +78630,7 @@ module.exports.not = NOT_REGEX; -var isNumber = __webpack_require__(650); +var isNumber = __webpack_require__(654); module.exports = function isOdd(i) { if (!isNumber(i)) { @@ -78524,7 +78644,7 @@ module.exports = function isOdd(i) { /***/ }), -/* 650 */ +/* 654 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -78552,14 +78672,14 @@ module.exports = function isNumber(num) { /***/ }), -/* 651 */ +/* 655 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = new (__webpack_require__(652))(); +module.exports = new (__webpack_require__(656))(); /***/ }), -/* 652 */ +/* 656 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -78572,7 +78692,7 @@ module.exports = new (__webpack_require__(652))(); -var MapCache = __webpack_require__(639); +var MapCache = __webpack_require__(643); /** * Create a new `FragmentCache` with an optional object to use for `caches`. @@ -78694,7 +78814,7 @@ exports = module.exports = FragmentCache; /***/ }), -/* 653 */ +/* 657 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -78707,13 +78827,13 @@ var path = __webpack_require__(4); * Module dependencies */ -var isWindows = __webpack_require__(654)(); -var Snapdragon = __webpack_require__(571); -utils.define = __webpack_require__(655); -utils.diff = __webpack_require__(656); -utils.extend = __webpack_require__(645); -utils.pick = __webpack_require__(657); -utils.typeOf = __webpack_require__(658); +var isWindows = __webpack_require__(658)(); +var Snapdragon = __webpack_require__(573); +utils.define = __webpack_require__(659); +utils.diff = __webpack_require__(660); +utils.extend = __webpack_require__(649); +utils.pick = __webpack_require__(661); +utils.typeOf = __webpack_require__(662); utils.unique = __webpack_require__(550); /** @@ -79080,7 +79200,7 @@ utils.unixify = function(options) { /***/ }), -/* 654 */ +/* 658 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! @@ -79108,7 +79228,7 @@ var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_ /***/ }), -/* 655 */ +/* 659 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79153,7 +79273,7 @@ module.exports = function defineProperty(obj, key, val) { /***/ }), -/* 656 */ +/* 660 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79207,7 +79327,7 @@ function diffArray(one, two) { /***/ }), -/* 657 */ +/* 661 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79249,7 +79369,7 @@ module.exports = function pick(obj, keys) { /***/ }), -/* 658 */ +/* 662 */ /***/ (function(module, exports) { var toString = Object.prototype.toString; @@ -79384,7 +79504,7 @@ function isBuffer(val) { /***/ }), -/* 659 */ +/* 663 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79394,7 +79514,7 @@ function isBuffer(val) { * Module dependencies */ -var extend = __webpack_require__(551); +var extend = __webpack_require__(587); var unique = __webpack_require__(550); var toRegex = __webpack_require__(528); @@ -79402,10 +79522,10 @@ var toRegex = __webpack_require__(528); * Local dependencies */ -var compilers = __webpack_require__(660); -var parsers = __webpack_require__(666); -var Extglob = __webpack_require__(669); -var utils = __webpack_require__(668); +var compilers = __webpack_require__(664); +var parsers = __webpack_require__(670); +var Extglob = __webpack_require__(673); +var utils = __webpack_require__(672); var MAX_LENGTH = 1024 * 64; /** @@ -79722,13 +79842,13 @@ module.exports = extglob; /***/ }), -/* 660 */ +/* 664 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var brackets = __webpack_require__(661); +var brackets = __webpack_require__(665); /** * Extglob compilers @@ -79898,7 +80018,7 @@ module.exports = function(extglob) { /***/ }), -/* 661 */ +/* 665 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79908,16 +80028,16 @@ module.exports = function(extglob) { * Local dependencies */ -var compilers = __webpack_require__(662); -var parsers = __webpack_require__(664); +var compilers = __webpack_require__(666); +var parsers = __webpack_require__(668); /** * Module dependencies */ -var debug = __webpack_require__(612)('expand-brackets'); -var extend = __webpack_require__(551); -var Snapdragon = __webpack_require__(571); +var debug = __webpack_require__(616)('expand-brackets'); +var extend = __webpack_require__(587); +var Snapdragon = __webpack_require__(573); var toRegex = __webpack_require__(528); /** @@ -80116,13 +80236,13 @@ module.exports = brackets; /***/ }), -/* 662 */ +/* 666 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var posix = __webpack_require__(663); +var posix = __webpack_require__(667); module.exports = function(brackets) { brackets.compiler @@ -80210,7 +80330,7 @@ module.exports = function(brackets) { /***/ }), -/* 663 */ +/* 667 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -80239,14 +80359,14 @@ module.exports = { /***/ }), -/* 664 */ +/* 668 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var utils = __webpack_require__(665); -var define = __webpack_require__(599); +var utils = __webpack_require__(669); +var define = __webpack_require__(603); /** * Text regex @@ -80465,7 +80585,7 @@ module.exports.TEXT_REGEX = TEXT_REGEX; /***/ }), -/* 665 */ +/* 669 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -80506,15 +80626,15 @@ exports.createRegex = function(pattern, include) { /***/ }), -/* 666 */ +/* 670 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var brackets = __webpack_require__(661); -var define = __webpack_require__(667); -var utils = __webpack_require__(668); +var brackets = __webpack_require__(665); +var define = __webpack_require__(671); +var utils = __webpack_require__(672); /** * Characters to use in text regex (we want to "not" match @@ -80669,7 +80789,7 @@ module.exports = parsers; /***/ }), -/* 667 */ +/* 671 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -80707,14 +80827,14 @@ module.exports = function defineProperty(obj, prop, val) { /***/ }), -/* 668 */ +/* 672 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var regex = __webpack_require__(547); -var Cache = __webpack_require__(652); +var Cache = __webpack_require__(656); /** * Utils @@ -80783,7 +80903,7 @@ utils.createRegex = function(str) { /***/ }), -/* 669 */ +/* 673 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -80793,16 +80913,16 @@ utils.createRegex = function(str) { * Module dependencies */ -var Snapdragon = __webpack_require__(571); -var define = __webpack_require__(667); -var extend = __webpack_require__(551); +var Snapdragon = __webpack_require__(573); +var define = __webpack_require__(671); +var extend = __webpack_require__(587); /** * Local dependencies */ -var compilers = __webpack_require__(660); -var parsers = __webpack_require__(666); +var compilers = __webpack_require__(664); +var parsers = __webpack_require__(670); /** * Customize Snapdragon parser and renderer @@ -80868,14 +80988,14 @@ module.exports = Extglob; /***/ }), -/* 670 */ +/* 674 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var extglob = __webpack_require__(659); -var nanomatch = __webpack_require__(644); +var extglob = __webpack_require__(663); +var nanomatch = __webpack_require__(648); var regexNot = __webpack_require__(547); var toRegex = __webpack_require__(528); var not; @@ -80958,14 +81078,14 @@ function textRegex(pattern) { /***/ }), -/* 671 */ +/* 675 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = new (__webpack_require__(652))(); +module.exports = new (__webpack_require__(656))(); /***/ }), -/* 672 */ +/* 676 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -80978,12 +81098,12 @@ var path = __webpack_require__(4); * Module dependencies */ -var Snapdragon = __webpack_require__(571); -utils.define = __webpack_require__(673); -utils.diff = __webpack_require__(656); -utils.extend = __webpack_require__(641); -utils.pick = __webpack_require__(657); -utils.typeOf = __webpack_require__(674); +var Snapdragon = __webpack_require__(573); +utils.define = __webpack_require__(677); +utils.diff = __webpack_require__(660); +utils.extend = __webpack_require__(645); +utils.pick = __webpack_require__(661); +utils.typeOf = __webpack_require__(678); utils.unique = __webpack_require__(550); /** @@ -81281,7 +81401,7 @@ utils.unixify = function(options) { /***/ }), -/* 673 */ +/* 677 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -81326,7 +81446,7 @@ module.exports = function defineProperty(obj, key, val) { /***/ }), -/* 674 */ +/* 678 */ /***/ (function(module, exports) { var toString = Object.prototype.toString; @@ -81461,7 +81581,7 @@ function isBuffer(val) { /***/ }), -/* 675 */ +/* 679 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -81480,9 +81600,9 @@ var __extends = (this && this.__extends) || (function () { }; })(); Object.defineProperty(exports, "__esModule", { value: true }); -var readdir = __webpack_require__(676); -var reader_1 = __webpack_require__(689); -var fs_stream_1 = __webpack_require__(693); +var readdir = __webpack_require__(680); +var reader_1 = __webpack_require__(693); +var fs_stream_1 = __webpack_require__(697); var ReaderAsync = /** @class */ (function (_super) { __extends(ReaderAsync, _super); function ReaderAsync() { @@ -81543,15 +81663,15 @@ exports.default = ReaderAsync; /***/ }), -/* 676 */ +/* 680 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const readdirSync = __webpack_require__(677); -const readdirAsync = __webpack_require__(685); -const readdirStream = __webpack_require__(688); +const readdirSync = __webpack_require__(681); +const readdirAsync = __webpack_require__(689); +const readdirStream = __webpack_require__(692); module.exports = exports = readdirAsyncPath; exports.readdir = exports.readdirAsync = exports.async = readdirAsyncPath; @@ -81635,7 +81755,7 @@ function readdirStreamStat (dir, options) { /***/ }), -/* 677 */ +/* 681 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -81643,11 +81763,11 @@ function readdirStreamStat (dir, options) { module.exports = readdirSync; -const DirectoryReader = __webpack_require__(678); +const DirectoryReader = __webpack_require__(682); let syncFacade = { - fs: __webpack_require__(683), - forEach: __webpack_require__(684), + fs: __webpack_require__(687), + forEach: __webpack_require__(688), sync: true }; @@ -81676,7 +81796,7 @@ function readdirSync (dir, options, internalOptions) { /***/ }), -/* 678 */ +/* 682 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -81685,9 +81805,9 @@ function readdirSync (dir, options, internalOptions) { const Readable = __webpack_require__(138).Readable; const EventEmitter = __webpack_require__(156).EventEmitter; const path = __webpack_require__(4); -const normalizeOptions = __webpack_require__(679); -const stat = __webpack_require__(681); -const call = __webpack_require__(682); +const normalizeOptions = __webpack_require__(683); +const stat = __webpack_require__(685); +const call = __webpack_require__(686); /** * Asynchronously reads the contents of a directory and streams the results @@ -82063,14 +82183,14 @@ module.exports = DirectoryReader; /***/ }), -/* 679 */ +/* 683 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; const path = __webpack_require__(4); -const globToRegExp = __webpack_require__(680); +const globToRegExp = __webpack_require__(684); module.exports = normalizeOptions; @@ -82247,7 +82367,7 @@ function normalizeOptions (options, internalOptions) { /***/ }), -/* 680 */ +/* 684 */ /***/ (function(module, exports) { module.exports = function (glob, opts) { @@ -82384,13 +82504,13 @@ module.exports = function (glob, opts) { /***/ }), -/* 681 */ +/* 685 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const call = __webpack_require__(682); +const call = __webpack_require__(686); module.exports = stat; @@ -82465,7 +82585,7 @@ function symlinkStat (fs, path, lstats, callback) { /***/ }), -/* 682 */ +/* 686 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -82526,14 +82646,14 @@ function callOnce (fn) { /***/ }), -/* 683 */ +/* 687 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; const fs = __webpack_require__(134); -const call = __webpack_require__(682); +const call = __webpack_require__(686); /** * A facade around {@link fs.readdirSync} that allows it to be called @@ -82597,7 +82717,7 @@ exports.lstat = function (path, callback) { /***/ }), -/* 684 */ +/* 688 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -82626,7 +82746,7 @@ function syncForEach (array, iterator, done) { /***/ }), -/* 685 */ +/* 689 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -82634,12 +82754,12 @@ function syncForEach (array, iterator, done) { module.exports = readdirAsync; -const maybe = __webpack_require__(686); -const DirectoryReader = __webpack_require__(678); +const maybe = __webpack_require__(690); +const DirectoryReader = __webpack_require__(682); let asyncFacade = { fs: __webpack_require__(134), - forEach: __webpack_require__(687), + forEach: __webpack_require__(691), async: true }; @@ -82681,7 +82801,7 @@ function readdirAsync (dir, options, callback, internalOptions) { /***/ }), -/* 686 */ +/* 690 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -82708,7 +82828,7 @@ module.exports = function maybe (cb, promise) { /***/ }), -/* 687 */ +/* 691 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -82744,7 +82864,7 @@ function asyncForEach (array, iterator, done) { /***/ }), -/* 688 */ +/* 692 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -82752,11 +82872,11 @@ function asyncForEach (array, iterator, done) { module.exports = readdirStream; -const DirectoryReader = __webpack_require__(678); +const DirectoryReader = __webpack_require__(682); let streamFacade = { fs: __webpack_require__(134), - forEach: __webpack_require__(687), + forEach: __webpack_require__(691), async: true }; @@ -82776,16 +82896,16 @@ function readdirStream (dir, options, internalOptions) { /***/ }), -/* 689 */ +/* 693 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var path = __webpack_require__(4); -var deep_1 = __webpack_require__(690); -var entry_1 = __webpack_require__(692); -var pathUtil = __webpack_require__(691); +var deep_1 = __webpack_require__(694); +var entry_1 = __webpack_require__(696); +var pathUtil = __webpack_require__(695); var Reader = /** @class */ (function () { function Reader(options) { this.options = options; @@ -82851,13 +82971,13 @@ exports.default = Reader; /***/ }), -/* 690 */ +/* 694 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var pathUtils = __webpack_require__(691); +var pathUtils = __webpack_require__(695); var patternUtils = __webpack_require__(522); var DeepFilter = /** @class */ (function () { function DeepFilter(options, micromatchOptions) { @@ -82941,7 +83061,7 @@ exports.default = DeepFilter; /***/ }), -/* 691 */ +/* 695 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -82972,13 +83092,13 @@ exports.makeAbsolute = makeAbsolute; /***/ }), -/* 692 */ +/* 696 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var pathUtils = __webpack_require__(691); +var pathUtils = __webpack_require__(695); var patternUtils = __webpack_require__(522); var EntryFilter = /** @class */ (function () { function EntryFilter(options, micromatchOptions) { @@ -83064,7 +83184,7 @@ exports.default = EntryFilter; /***/ }), -/* 693 */ +/* 697 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83084,8 +83204,8 @@ var __extends = (this && this.__extends) || (function () { })(); Object.defineProperty(exports, "__esModule", { value: true }); var stream = __webpack_require__(138); -var fsStat = __webpack_require__(694); -var fs_1 = __webpack_require__(698); +var fsStat = __webpack_require__(698); +var fs_1 = __webpack_require__(702); var FileSystemStream = /** @class */ (function (_super) { __extends(FileSystemStream, _super); function FileSystemStream() { @@ -83135,14 +83255,14 @@ exports.default = FileSystemStream; /***/ }), -/* 694 */ +/* 698 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const optionsManager = __webpack_require__(695); -const statProvider = __webpack_require__(697); +const optionsManager = __webpack_require__(699); +const statProvider = __webpack_require__(701); /** * Asynchronous API. */ @@ -83173,13 +83293,13 @@ exports.statSync = statSync; /***/ }), -/* 695 */ +/* 699 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const fsAdapter = __webpack_require__(696); +const fsAdapter = __webpack_require__(700); function prepare(opts) { const options = Object.assign({ fs: fsAdapter.getFileSystemAdapter(opts ? opts.fs : undefined), @@ -83192,7 +83312,7 @@ exports.prepare = prepare; /***/ }), -/* 696 */ +/* 700 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83215,7 +83335,7 @@ exports.getFileSystemAdapter = getFileSystemAdapter; /***/ }), -/* 697 */ +/* 701 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83267,7 +83387,7 @@ exports.isFollowedSymlink = isFollowedSymlink; /***/ }), -/* 698 */ +/* 702 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83298,7 +83418,7 @@ exports.default = FileSystem; /***/ }), -/* 699 */ +/* 703 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83318,9 +83438,9 @@ var __extends = (this && this.__extends) || (function () { })(); Object.defineProperty(exports, "__esModule", { value: true }); var stream = __webpack_require__(138); -var readdir = __webpack_require__(676); -var reader_1 = __webpack_require__(689); -var fs_stream_1 = __webpack_require__(693); +var readdir = __webpack_require__(680); +var reader_1 = __webpack_require__(693); +var fs_stream_1 = __webpack_require__(697); var TransformStream = /** @class */ (function (_super) { __extends(TransformStream, _super); function TransformStream(reader) { @@ -83388,7 +83508,7 @@ exports.default = ReaderStream; /***/ }), -/* 700 */ +/* 704 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83407,9 +83527,9 @@ var __extends = (this && this.__extends) || (function () { }; })(); Object.defineProperty(exports, "__esModule", { value: true }); -var readdir = __webpack_require__(676); -var reader_1 = __webpack_require__(689); -var fs_sync_1 = __webpack_require__(701); +var readdir = __webpack_require__(680); +var reader_1 = __webpack_require__(693); +var fs_sync_1 = __webpack_require__(705); var ReaderSync = /** @class */ (function (_super) { __extends(ReaderSync, _super); function ReaderSync() { @@ -83469,7 +83589,7 @@ exports.default = ReaderSync; /***/ }), -/* 701 */ +/* 705 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83488,8 +83608,8 @@ var __extends = (this && this.__extends) || (function () { }; })(); Object.defineProperty(exports, "__esModule", { value: true }); -var fsStat = __webpack_require__(694); -var fs_1 = __webpack_require__(698); +var fsStat = __webpack_require__(698); +var fs_1 = __webpack_require__(702); var FileSystemSync = /** @class */ (function (_super) { __extends(FileSystemSync, _super); function FileSystemSync() { @@ -83535,7 +83655,7 @@ exports.default = FileSystemSync; /***/ }), -/* 702 */ +/* 706 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83551,7 +83671,7 @@ exports.flatten = flatten; /***/ }), -/* 703 */ +/* 707 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83572,13 +83692,13 @@ exports.merge = merge; /***/ }), -/* 704 */ +/* 708 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; const path = __webpack_require__(4); -const pathType = __webpack_require__(705); +const pathType = __webpack_require__(709); const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; @@ -83644,13 +83764,13 @@ module.exports.sync = (input, opts) => { /***/ }), -/* 705 */ +/* 709 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; const fs = __webpack_require__(134); -const pify = __webpack_require__(706); +const pify = __webpack_require__(710); function type(fn, fn2, fp) { if (typeof fp !== 'string') { @@ -83693,7 +83813,7 @@ exports.symlinkSync = typeSync.bind(null, 'lstatSync', 'isSymbolicLink'); /***/ }), -/* 706 */ +/* 710 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83784,7 +83904,7 @@ module.exports = (obj, opts) => { /***/ }), -/* 707 */ +/* 711 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83792,9 +83912,9 @@ module.exports = (obj, opts) => { const fs = __webpack_require__(134); const path = __webpack_require__(4); const fastGlob = __webpack_require__(518); -const gitIgnore = __webpack_require__(708); -const pify = __webpack_require__(709); -const slash = __webpack_require__(710); +const gitIgnore = __webpack_require__(712); +const pify = __webpack_require__(713); +const slash = __webpack_require__(714); const DEFAULT_IGNORE = [ '**/node_modules/**', @@ -83892,7 +84012,7 @@ module.exports.sync = options => { /***/ }), -/* 708 */ +/* 712 */ /***/ (function(module, exports) { // A simple implementation of make-array @@ -84361,7 +84481,7 @@ module.exports = options => new IgnoreBase(options) /***/ }), -/* 709 */ +/* 713 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -84436,7 +84556,7 @@ module.exports = (input, options) => { /***/ }), -/* 710 */ +/* 714 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -84454,7 +84574,7 @@ module.exports = input => { /***/ }), -/* 711 */ +/* 715 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -84467,7 +84587,7 @@ module.exports = input => { -var isGlob = __webpack_require__(712); +var isGlob = __webpack_require__(716); module.exports = function hasGlob(val) { if (val == null) return false; @@ -84487,7 +84607,7 @@ module.exports = function hasGlob(val) { /***/ }), -/* 712 */ +/* 716 */ /***/ (function(module, exports, __webpack_require__) { /*! @@ -84518,17 +84638,17 @@ module.exports = function isGlob(str) { /***/ }), -/* 713 */ +/* 717 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; const path = __webpack_require__(4); const {constants: fsConstants} = __webpack_require__(134); -const pEvent = __webpack_require__(714); -const CpFileError = __webpack_require__(717); -const fs = __webpack_require__(719); -const ProgressEmitter = __webpack_require__(722); +const pEvent = __webpack_require__(718); +const CpFileError = __webpack_require__(721); +const fs = __webpack_require__(723); +const ProgressEmitter = __webpack_require__(726); const cpFileAsync = async (source, destination, options, progressEmitter) => { let readError; @@ -84642,12 +84762,12 @@ module.exports.sync = (source, destination, options) => { /***/ }), -/* 714 */ +/* 718 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const pTimeout = __webpack_require__(715); +const pTimeout = __webpack_require__(719); const symbolAsyncIterator = Symbol.asyncIterator || '@@asyncIterator'; @@ -84938,12 +85058,12 @@ module.exports.iterator = (emitter, event, options) => { /***/ }), -/* 715 */ +/* 719 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const pFinally = __webpack_require__(716); +const pFinally = __webpack_require__(720); class TimeoutError extends Error { constructor(message) { @@ -84989,7 +85109,7 @@ module.exports.TimeoutError = TimeoutError; /***/ }), -/* 716 */ +/* 720 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -85011,12 +85131,12 @@ module.exports = (promise, onFinally) => { /***/ }), -/* 717 */ +/* 721 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const NestedError = __webpack_require__(718); +const NestedError = __webpack_require__(722); class CpFileError extends NestedError { constructor(message, nested) { @@ -85030,7 +85150,7 @@ module.exports = CpFileError; /***/ }), -/* 718 */ +/* 722 */ /***/ (function(module, exports, __webpack_require__) { var inherits = __webpack_require__(112).inherits; @@ -85086,16 +85206,16 @@ module.exports = NestedError; /***/ }), -/* 719 */ +/* 723 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; const {promisify} = __webpack_require__(112); const fs = __webpack_require__(133); -const makeDir = __webpack_require__(720); -const pEvent = __webpack_require__(714); -const CpFileError = __webpack_require__(717); +const makeDir = __webpack_require__(724); +const pEvent = __webpack_require__(718); +const CpFileError = __webpack_require__(721); const stat = promisify(fs.stat); const lstat = promisify(fs.lstat); @@ -85192,7 +85312,7 @@ exports.copyFileSync = (source, destination, flags) => { /***/ }), -/* 720 */ +/* 724 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -85200,7 +85320,7 @@ exports.copyFileSync = (source, destination, flags) => { const fs = __webpack_require__(134); const path = __webpack_require__(4); const {promisify} = __webpack_require__(112); -const semver = __webpack_require__(721); +const semver = __webpack_require__(725); const useNativeRecursiveOption = semver.satisfies(process.version, '>=10.12.0'); @@ -85355,7 +85475,7 @@ module.exports.sync = (input, options) => { /***/ }), -/* 721 */ +/* 725 */ /***/ (function(module, exports) { exports = module.exports = SemVer @@ -86957,7 +87077,7 @@ function coerce (version, options) { /***/ }), -/* 722 */ +/* 726 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -86998,7 +87118,7 @@ module.exports = ProgressEmitter; /***/ }), -/* 723 */ +/* 727 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -87044,12 +87164,12 @@ exports.default = module.exports; /***/ }), -/* 724 */ +/* 728 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const pMap = __webpack_require__(725); +const pMap = __webpack_require__(729); const pFilter = async (iterable, filterer, options) => { const values = await pMap( @@ -87066,7 +87186,7 @@ module.exports.default = pFilter; /***/ }), -/* 725 */ +/* 729 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -87145,12 +87265,12 @@ module.exports.default = pMap; /***/ }), -/* 726 */ +/* 730 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const NestedError = __webpack_require__(718); +const NestedError = __webpack_require__(722); class CpyError extends NestedError { constructor(message, nested) { diff --git a/packages/kbn-spec-to-console/package.json b/packages/kbn-spec-to-console/package.json index f1eefab0f1fd0..b8947d1b3b6d0 100644 --- a/packages/kbn-spec-to-console/package.json +++ b/packages/kbn-spec-to-console/package.json @@ -7,7 +7,6 @@ "lib": "lib" }, "scripts": { - "test": "../../node_modules/.bin/jest", "format": "../../node_modules/.bin/prettier **/*.js --write" }, "author": "", diff --git a/packages/kbn-test/src/functional_test_runner/lib/docker_servers/docker_servers_service.ts b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/docker_servers_service.ts index 606902228e1b7..e5bad88e5e7bf 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/docker_servers/docker_servers_service.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/docker_servers_service.ts @@ -124,7 +124,11 @@ export class DockerServersService { lifecycle.cleanup.add(() => { try { execa.sync('docker', ['kill', containerId]); - execa.sync('docker', ['rm', containerId]); + // we don't remove the containers on CI because removing them causes the + // network list to be updated and aborts all in-flight requests in Chrome + if (!process.env.CI) { + execa.sync('docker', ['rm', containerId]); + } } catch (error) { if ( error.message.includes(`Container ${containerId} is not running`) || diff --git a/src/core/public/http/external_url_service.test.ts b/src/core/public/http/external_url_service.test.ts new file mode 100644 index 0000000000000..af34dba5e6216 --- /dev/null +++ b/src/core/public/http/external_url_service.test.ts @@ -0,0 +1,494 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { ExternalUrlConfig } from 'src/core/server/types'; + +import { injectedMetadataServiceMock } from '../mocks'; +import { Sha256 } from '../utils'; + +import { ExternalUrlService } from './external_url_service'; + +const setupService = ({ + location, + serverBasePath, + policy, +}: { + location: URL; + serverBasePath: string; + policy: ExternalUrlConfig['policy']; +}) => { + const hashedPolicies = policy.map((entry) => { + // If the host contains a `[`, then it's likely an IPv6 address. Otherwise, append a `.` if it doesn't already contain one + const hostToHash = + entry.host && !entry.host.includes('[') && !entry.host.endsWith('.') + ? `${entry.host}.` + : entry.host; + return { + ...entry, + host: hostToHash ? new Sha256().update(hostToHash, 'utf8').digest('hex') : undefined, + }; + }); + const injectedMetadata = injectedMetadataServiceMock.createSetupContract(); + injectedMetadata.getExternalUrlConfig.mockReturnValue({ policy: hashedPolicies }); + injectedMetadata.getServerBasePath.mockReturnValue(serverBasePath); + + const service = new ExternalUrlService(); + return { + setup: service.setup({ + injectedMetadata, + location, + }), + }; +}; + +const internalRequestScenarios = [ + { + description: 'without any policies', + allowExternal: false, + policy: [], + }, + { + description: 'with an unrestricted policy', + allowExternal: true, + policy: [ + { + allow: true, + }, + ], + }, + { + description: 'with a fully restricted policy', + allowExternal: false, + policy: [ + { + allow: false, + }, + ], + }, +]; + +describe('External Url Service', () => { + describe('#validateUrl', () => { + describe('internal requests with a server base path', () => { + const serverBasePath = '/base-path'; + const serverRoot = `https://my-kibana.example.com:5601`; + const kibanaRoot = `${serverRoot}${serverBasePath}`; + const location = new URL(`${kibanaRoot}/app/management?q=1&bar=false#some-hash`); + + internalRequestScenarios.forEach(({ description, policy, allowExternal }) => { + describe(description, () => { + it('allows relative URLs that start with the server base path', () => { + const { setup } = setupService({ location, serverBasePath, policy }); + const urlCandidate = `/some/path?foo=bar`; + const result = setup.validateUrl(`${serverBasePath}${urlCandidate}`); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(`${kibanaRoot}${urlCandidate}`); + }); + + it('allows absolute URLs to Kibana that start with the server base path', () => { + const { setup } = setupService({ location, serverBasePath, policy }); + const urlCandidate = `${kibanaRoot}/some/path?foo=bar`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(`${kibanaRoot}/some/path?foo=bar`); + }); + + if (allowExternal) { + it('allows absolute URLs to Kibana that do not start with the server base path', () => { + const { setup } = setupService({ location, serverBasePath, policy }); + const urlCandidate = `${serverRoot}/some/path?foo=bar`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(`${serverRoot}/some/path?foo=bar`); + }); + + it('allows relative URLs that attempt to bypass the server base path', () => { + const { setup } = setupService({ location, serverBasePath, policy }); + const urlCandidate = `/some/../../path?foo=bar`; + const result = setup.validateUrl(`${serverBasePath}${urlCandidate}`); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(`${serverRoot}/path?foo=bar`); + }); + + it('allows relative URLs that do not start with the server base path', () => { + const { setup } = setupService({ location, serverBasePath, policy }); + const urlCandidate = `/some/path?foo=bar`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(`${serverRoot}/some/path?foo=bar`); + }); + } else { + it('disallows absolute URLs to Kibana that do not start with the server base path', () => { + const { setup } = setupService({ location, serverBasePath, policy }); + const urlCandidate = `${serverRoot}/some/path?foo=bar`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeNull(); + }); + + it('disallows relative URLs that attempt to bypass the server base path', () => { + const { setup } = setupService({ location, serverBasePath, policy }); + const urlCandidate = `/some/../../path?foo=bar`; + const result = setup.validateUrl(`${serverBasePath}${urlCandidate}`); + + expect(result).toBeNull(); + }); + + it('disallows relative URLs that do not start with the server base path', () => { + const { setup } = setupService({ location, serverBasePath, policy }); + const urlCandidate = `/some/path?foo=bar`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeNull(); + }); + } + }); + }); + + describe('handles protocol resolution bypass', () => { + it('does not allow relative URLs that include a host', () => { + const { setup } = setupService({ location, serverBasePath, policy: [] }); + const urlCandidate = `/some/path?foo=bar`; + const result = setup.validateUrl(`//www.google.com${serverBasePath}${urlCandidate}`); + + expect(result).toBeNull(); + }); + + it('does allow relative URLs that include a host if allowed by policy', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + host: 'www.google.com', + }, + ], + }); + const urlCandidate = `/some/path?foo=bar`; + const result = setup.validateUrl(`//www.google.com${serverBasePath}${urlCandidate}`); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual( + `https://www.google.com${serverBasePath}${urlCandidate}` + ); + }); + }); + }); + + describe('internal requests without a server base path', () => { + const serverBasePath = ''; + const serverRoot = `https://my-kibana.example.com:5601`; + const kibanaRoot = `${serverRoot}${serverBasePath}`; + const location = new URL(`${kibanaRoot}/app/management?q=1&bar=false#some-hash`); + + internalRequestScenarios.forEach(({ description, policy }) => { + describe(description, () => { + it('allows relative URLs', () => { + const { setup } = setupService({ location, serverBasePath, policy }); + const urlCandidate = `/some/path?foo=bar`; + const result = setup.validateUrl(`${serverBasePath}${urlCandidate}`); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(`${kibanaRoot}${urlCandidate}`); + }); + + it('allows absolute URLs to Kibana', () => { + const { setup } = setupService({ location, serverBasePath, policy }); + const urlCandidate = `${kibanaRoot}/some/path?foo=bar`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(`${kibanaRoot}/some/path?foo=bar`); + }); + }); + }); + + describe('handles protocol resolution bypass', () => { + it('does not allow relative URLs that include a host', () => { + const { setup } = setupService({ location, serverBasePath, policy: [] }); + const urlCandidate = `/some/path?foo=bar`; + const result = setup.validateUrl(`//www.google.com${urlCandidate}`); + + expect(result).toBeNull(); + }); + + it('allows relative URLs that include a host in the allow list', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + host: 'www.google.com', + }, + ], + }); + const urlCandidate = `/some/path?foo=bar`; + const result = setup.validateUrl(`//www.google.com${urlCandidate}`); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(`https://www.google.com${urlCandidate}`); + }); + }); + }); + + describe('external requests', () => { + const serverBasePath = '/base-path'; + const serverRoot = `https://my-kibana.example.com:5601`; + const kibanaRoot = `${serverRoot}${serverBasePath}`; + const location = new URL(`${kibanaRoot}/app/management?q=1&bar=false#some-hash`); + + it('does not allow external urls by default', () => { + const { setup } = setupService({ location, serverBasePath, policy: [] }); + const urlCandidate = `http://www.google.com`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeNull(); + }); + + it('does not allow external urls with a fully restricted policy', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: false, + }, + ], + }); + const urlCandidate = `https://www.google.com/foo?bar=baz`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeNull(); + }); + + it('allows external urls with an unrestricted policy', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + }, + ], + }); + const urlCandidate = `https://www.google.com/foo?bar=baz`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(urlCandidate); + }); + + it('allows external urls with a matching host and protocol in the allow list', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + host: 'www.google.com', + protocol: 'https', + }, + ], + }); + const urlCandidate = `https://www.google.com/foo?bar=baz`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(urlCandidate); + }); + + it('allows external urls with a partially matching host and protocol in the allow list', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + host: 'google.com', + protocol: 'https', + }, + ], + }); + const urlCandidate = `https://www.google.com/foo?bar=baz`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(urlCandidate); + }); + + it('allows external urls with a partially matching host and protocol in the allow list when the URL includes the root domain', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + host: 'google.com', + protocol: 'https', + }, + ], + }); + const urlCandidate = `https://www.google.com./foo?bar=baz`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(urlCandidate); + }); + + it('allows external urls with an IPv4 address', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + host: '192.168.10.12', + protocol: 'https', + }, + ], + }); + const urlCandidate = `https://192.168.10.12/foo?bar=baz`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(urlCandidate); + }); + + it('allows external urls with an IPv6 address', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + host: '[2001:db8:85a3:8d3:1319:8a2e:370:7348]', + protocol: 'https', + }, + ], + }); + const urlCandidate = `https://[2001:db8:85a3:8d3:1319:8a2e:370:7348]/foo?bar=baz`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(urlCandidate); + }); + + it('allows external urls that specify a locally addressable host', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + host: 'some-host-name', + protocol: 'https', + }, + ], + }); + const urlCandidate = `https://some-host-name/foo?bar=baz`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(urlCandidate); + }); + + it('disallows external urls with a matching host and unmatched protocol', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + host: 'www.google.com', + protocol: 'https', + }, + ], + }); + const urlCandidate = `http://www.google.com/foo?bar=baz`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeNull(); + }); + + it('allows external urls with a matching host and any protocol', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + host: 'www.google.com', + }, + ], + }); + const urlCandidate = `ftp://www.google.com/foo?bar=baz`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(urlCandidate); + }); + + it('allows external urls with any host and matching protocol', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + protocol: 'https', + }, + ], + }); + const urlCandidate = `https://www.google.com/foo?bar=baz`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeInstanceOf(URL); + expect(result?.toString()).toEqual(urlCandidate); + }); + + it('disallows external urls that match multiple rules, one of which denies the request', () => { + const { setup } = setupService({ + location, + serverBasePath, + policy: [ + { + allow: true, + protocol: 'https', + }, + { + allow: false, + host: 'www.google.com', + }, + ], + }); + const urlCandidate = `https://www.google.com/foo?bar=baz`; + const result = setup.validateUrl(urlCandidate); + + expect(result).toBeNull(); + }); + }); + }); +}); diff --git a/src/core/public/http/external_url_service.ts b/src/core/public/http/external_url_service.ts new file mode 100644 index 0000000000000..e975451a7fdaa --- /dev/null +++ b/src/core/public/http/external_url_service.ts @@ -0,0 +1,111 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { IExternalUrlPolicy } from 'src/core/server/types'; + +import { CoreService } from 'src/core/types'; +import { IExternalUrl } from './types'; +import { InjectedMetadataSetup } from '../injected_metadata'; +import { Sha256 } from '../utils'; + +interface SetupDeps { + location: Pick; + injectedMetadata: InjectedMetadataSetup; +} + +function* getHostHashes(actualHost: string) { + yield new Sha256().update(actualHost, 'utf8').digest('hex'); + let host = actualHost.substr(actualHost.indexOf('.') + 1); + while (host) { + yield new Sha256().update(host, 'utf8').digest('hex'); + if (host.indexOf('.') === -1) { + break; + } + host = host.substr(host.indexOf('.') + 1); + } +} + +const isHostMatch = (actualHost: string, ruleHostHash: string) => { + // If the host contains a `[`, then it's likely an IPv6 address. Otherwise, append a `.` if it doesn't already contain one + const hostToHash = + !actualHost.includes('[') && !actualHost.endsWith('.') ? `${actualHost}.` : actualHost; + for (const hash of getHostHashes(hostToHash)) { + if (hash === ruleHostHash) { + return true; + } + } + return false; +}; + +const isProtocolMatch = (actualProtocol: string, ruleProtocol: string) => { + return normalizeProtocol(actualProtocol) === normalizeProtocol(ruleProtocol); +}; + +function normalizeProtocol(protocol: string) { + return protocol.endsWith(':') ? protocol.slice(0, -1).toLowerCase() : protocol.toLowerCase(); +} + +const createExternalUrlValidation = ( + rules: IExternalUrlPolicy[], + location: Pick, + serverBasePath: string +) => { + const base = new URL(location.origin + serverBasePath); + return function validateExternalUrl(next: string) { + const url = new URL(next, base); + + const isInternalURL = + url.origin === base.origin && + (!serverBasePath || url.pathname.startsWith(`${serverBasePath}/`)); + + if (isInternalURL) { + return url; + } + + let allowed: null | boolean = null; + rules.forEach((rule) => { + const hostMatch = rule.host ? isHostMatch(url.hostname || '', rule.host) : true; + + const protocolMatch = rule.protocol ? isProtocolMatch(url.protocol, rule.protocol) : true; + + const isRuleMatch = hostMatch && protocolMatch; + + if (isRuleMatch && allowed !== false) { + allowed = rule.allow; + } + }); + + return allowed === true ? url : null; + }; +}; + +export class ExternalUrlService implements CoreService { + setup({ injectedMetadata, location }: SetupDeps): IExternalUrl { + const serverBasePath = injectedMetadata.getServerBasePath(); + const { policy } = injectedMetadata.getExternalUrlConfig(); + + return { + validateUrl: createExternalUrlValidation(policy, location, serverBasePath), + }; + } + + start() {} + + stop() {} +} diff --git a/src/core/public/http/http_service.mock.ts b/src/core/public/http/http_service.mock.ts index 68533159765fb..025336487c855 100644 --- a/src/core/public/http/http_service.mock.ts +++ b/src/core/public/http/http_service.mock.ts @@ -41,6 +41,9 @@ const createServiceMock = ({ basePath = '' } = {}): HttpSetupMock => ({ register: jest.fn(), isAnonymous: jest.fn(), }, + externalUrl: { + validateUrl: jest.fn(), + }, addLoadingCountSource: jest.fn(), getLoadingCount$: jest.fn().mockReturnValue(new BehaviorSubject(0)), intercept: jest.fn(), diff --git a/src/core/public/http/http_service.ts b/src/core/public/http/http_service.ts index 2eaaefe285755..a65eb5f76e1ac 100644 --- a/src/core/public/http/http_service.ts +++ b/src/core/public/http/http_service.ts @@ -25,6 +25,7 @@ import { AnonymousPathsService } from './anonymous_paths_service'; import { LoadingCountService } from './loading_count_service'; import { Fetch } from './fetch'; import { CoreService } from '../../types'; +import { ExternalUrlService } from './external_url_service'; interface HttpDeps { injectedMetadata: InjectedMetadataSetup; @@ -51,6 +52,7 @@ export class HttpService implements CoreService { this.service = { basePath, anonymousPaths: this.anonymousPaths.setup({ basePath }), + externalUrl: new ExternalUrlService().setup({ injectedMetadata, location: window.location }), intercept: fetchService.intercept.bind(fetchService), fetch: fetchService.fetch.bind(fetchService), delete: fetchService.delete.bind(fetchService), diff --git a/src/core/public/http/types.ts b/src/core/public/http/types.ts index 7285d1a4288dc..5910aa0fc3238 100644 --- a/src/core/public/http/types.ts +++ b/src/core/public/http/types.ts @@ -33,6 +33,8 @@ export interface HttpSetup { */ anonymousPaths: IAnonymousPaths; + externalUrl: IExternalUrl; + /** * Adds a new {@link HttpInterceptor} to the global HTTP client. * @param interceptor a {@link HttpInterceptor} @@ -112,6 +114,23 @@ export interface IBasePath { */ readonly publicBaseUrl?: string; } +/** + * APIs for working with external URLs. + * + * @public + */ +export interface IExternalUrl { + /** + * Determines if the provided URL is a valid location to send users. + * Validation is based on the configured allow list in kibana.yml. + * + * If the URL is valid, then a URL will be returned. + * Otherwise, this will return null. + * + * @param relativeOrAbsoluteUrl + */ + validateUrl(relativeOrAbsoluteUrl: string): URL | null; +} /** * APIs for denoting paths as not requiring authentication diff --git a/src/core/public/index.ts b/src/core/public/index.ts index 557529fc94dc4..8e240bfe91d48 100644 --- a/src/core/public/index.ts +++ b/src/core/public/index.ts @@ -77,7 +77,7 @@ import { HandlerParameters, } from './context'; -export { PackageInfo, EnvironmentMode } from '../server/types'; +export { PackageInfo, EnvironmentMode, IExternalUrlPolicy } from '../server/types'; export { CoreContext, CoreSystem } from './core_system'; export { DEFAULT_APP_CATEGORIES } from '../utils'; export { @@ -164,6 +164,7 @@ export { HttpHandler, IBasePath, IAnonymousPaths, + IExternalUrl, IHttpInterceptController, IHttpFetchError, IHttpResponseInterceptorOverrides, diff --git a/src/core/public/injected_metadata/injected_metadata_service.mock.ts b/src/core/public/injected_metadata/injected_metadata_service.mock.ts index 96282caa62c0a..ec05edcbbf25c 100644 --- a/src/core/public/injected_metadata/injected_metadata_service.mock.ts +++ b/src/core/public/injected_metadata/injected_metadata_service.mock.ts @@ -27,6 +27,7 @@ const createSetupContractMock = () => { getKibanaVersion: jest.fn(), getKibanaBranch: jest.fn(), getCspConfig: jest.fn(), + getExternalUrlConfig: jest.fn(), getAnonymousStatusPage: jest.fn(), getLegacyMetadata: jest.fn(), getPlugins: jest.fn(), @@ -35,6 +36,7 @@ const createSetupContractMock = () => { getKibanaBuildNumber: jest.fn(), }; setupContract.getCspConfig.mockReturnValue({ warnLegacyBrowsers: true }); + setupContract.getExternalUrlConfig.mockReturnValue({ policy: [] }); setupContract.getKibanaVersion.mockReturnValue('kibanaVersion'); setupContract.getAnonymousStatusPage.mockReturnValue(false); setupContract.getLegacyMetadata.mockReturnValue({ diff --git a/src/core/public/injected_metadata/injected_metadata_service.ts b/src/core/public/injected_metadata/injected_metadata_service.ts index 283710980e3ce..51025e24140da 100644 --- a/src/core/public/injected_metadata/injected_metadata_service.ts +++ b/src/core/public/injected_metadata/injected_metadata_service.ts @@ -22,6 +22,7 @@ import { deepFreeze } from '@kbn/std'; import { DiscoveredPlugin, PluginName } from '../../server'; import { EnvironmentMode, + IExternalUrlPolicy, PackageInfo, UiSettingsParams, UserProvidedValues, @@ -49,6 +50,9 @@ export interface InjectedMetadataParams { csp: { warnLegacyBrowsers: boolean; }; + externalUrl: { + policy: IExternalUrlPolicy[]; + }; vars: { [key: string]: unknown; }; @@ -112,6 +116,10 @@ export class InjectedMetadataService { return this.state.csp; }, + getExternalUrlConfig: () => { + return this.state.externalUrl; + }, + getPlugins: () => { return this.state.uiPlugins; }, @@ -154,6 +162,9 @@ export interface InjectedMetadataSetup { getCspConfig: () => { warnLegacyBrowsers: boolean; }; + getExternalUrlConfig: () => { + policy: IExternalUrlPolicy[]; + }; /** * An array of frontend plugins in topological order. */ diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md index 0b1d3f8263a23..65912e0954261 100644 --- a/src/core/public/public.api.md +++ b/src/core/public/public.api.md @@ -727,6 +727,8 @@ export interface HttpSetup { anonymousPaths: IAnonymousPaths; basePath: IBasePath; delete: HttpHandler; + // (undocumented) + externalUrl: IExternalUrl; fetch: HttpHandler; get: HttpHandler; getLoadingCount$(): Observable; @@ -777,6 +779,18 @@ export interface IContextContainer> { // @public export type IContextProvider, TContextName extends keyof HandlerContextType> = (context: PartialExceptFor, 'core'>, ...rest: HandlerParameters) => Promise[TContextName]> | HandlerContextType[TContextName]; +// @public +export interface IExternalUrl { + validateUrl(relativeOrAbsoluteUrl: string): URL | null; +} + +// @public +export interface IExternalUrlPolicy { + allow: boolean; + host?: string; + protocol?: string; +} + // @public (undocumented) export interface IHttpFetchError extends Error { // (undocumented) diff --git a/src/core/server/external_url/config.test.ts b/src/core/server/external_url/config.test.ts new file mode 100644 index 0000000000000..eeaf3751904d4 --- /dev/null +++ b/src/core/server/external_url/config.test.ts @@ -0,0 +1,160 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { config } from './config'; + +describe('externalUrl config', () => { + it('provides a default policy allowing all external urls', () => { + expect(config.schema.validate({})).toMatchInlineSnapshot(` + Object { + "policy": Array [ + Object { + "allow": true, + }, + ], + } + `); + }); + + it('allows an empty policy', () => { + expect(config.schema.validate({ policy: [] })).toMatchInlineSnapshot(` + Object { + "policy": Array [], + } + `); + }); + + it('allows a policy with just a protocol', () => { + expect( + config.schema.validate({ + policy: [ + { + allow: true, + protocol: 'http', + }, + ], + }) + ).toMatchInlineSnapshot(` + Object { + "policy": Array [ + Object { + "allow": true, + "protocol": "http", + }, + ], + } + `); + }); + + it('allows a policy with just a host', () => { + expect( + config.schema.validate({ + policy: [ + { + allow: true, + host: 'www.google.com', + }, + ], + }) + ).toMatchInlineSnapshot(` + Object { + "policy": Array [ + Object { + "allow": true, + "host": "www.google.com", + }, + ], + } + `); + }); + + it('allows a policy with both host and protocol', () => { + expect( + config.schema.validate({ + policy: [ + { + allow: true, + protocol: 'http', + host: 'www.google.com', + }, + ], + }) + ).toMatchInlineSnapshot(` + Object { + "policy": Array [ + Object { + "allow": true, + "host": "www.google.com", + "protocol": "http", + }, + ], + } + `); + }); + + it('allows a policy without a host or protocol', () => { + expect( + config.schema.validate({ + policy: [ + { + allow: true, + }, + ], + }) + ).toMatchInlineSnapshot(` + Object { + "policy": Array [ + Object { + "allow": true, + }, + ], + } + `); + }); + + describe('protocols', () => { + ['http', 'https', 'ftp', 'ftps', 'custom-protocol+123.bar'].forEach((protocol) => { + it(`allows a protocol of "${protocol}"`, () => { + config.schema.validate({ + policy: [ + { + allow: true, + protocol, + }, + ], + }); + }); + }); + + ['1http', '', 'custom-protocol()', 'https://'].forEach((protocol) => { + it(`disallows a protocol of "${protocol}"`, () => { + expect(() => + config.schema.validate({ + policy: [ + { + allow: true, + protocol, + }, + ], + }) + ).toThrowError(); + }); + }); + }); +}); diff --git a/src/core/server/external_url/config.ts b/src/core/server/external_url/config.ts new file mode 100644 index 0000000000000..4a26365a0c93d --- /dev/null +++ b/src/core/server/external_url/config.ts @@ -0,0 +1,61 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { TypeOf, schema } from '@kbn/config-schema'; +import { IExternalUrlPolicy } from '.'; + +/** + * @internal + */ +export type ExternalUrlConfigType = TypeOf; + +const allowSchema = schema.boolean(); + +const hostSchema = schema.string(); + +const protocolSchema = schema.string({ + validate: (value) => { + // tools.ietf.org/html/rfc3986#section-3.1 + // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + const schemaRegex = /^[a-zA-Z][a-zA-Z0-9\+\-\.]*$/; + if (!schemaRegex.test(value)) + throw new Error( + 'Protocol must begin with a letter, and can only contain letters, numbers, and the following characters: `+ - .`' + ); + }, +}); + +const policySchema = schema.object({ + allow: allowSchema, + protocol: schema.maybe(protocolSchema), + host: schema.maybe(hostSchema), +}); + +export const config = { + path: 'externalUrl', + schema: schema.object({ + policy: schema.arrayOf(policySchema, { + defaultValue: [ + { + allow: true, + }, + ], + }), + }), +}; diff --git a/src/core/server/external_url/external_url_config.ts b/src/core/server/external_url/external_url_config.ts new file mode 100644 index 0000000000000..065a9cd1d2609 --- /dev/null +++ b/src/core/server/external_url/external_url_config.ts @@ -0,0 +1,101 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { createSHA256Hash } from '../utils'; +import { config } from './config'; + +const DEFAULT_CONFIG = Object.freeze(config.schema.validate({})); + +/** + * External Url configuration for use in Kibana. + * @public + */ +export interface IExternalUrlConfig { + /** + * A set of policies describing which external urls are allowed. + */ + readonly policy: IExternalUrlPolicy[]; +} + +/** + * A policy describing whether access to an external destination is allowed. + * @public + */ +export interface IExternalUrlPolicy { + /** + * Indicates if this policy allows or denies access to the described destination. + */ + allow: boolean; + + /** + * Optional host describing the external destination. + * May be combined with `protocol`. + * + * @example + * ```ts + * // allows access to all of google.com, using any protocol. + * allow: true, + * host: 'google.com' + * ``` + */ + host?: string; + + /** + * Optional protocol describing the external destination. + * May be combined with `host`. + * + * @example + * ```ts + * // allows access to all destinations over the `https` protocol. + * allow: true, + * protocol: 'https' + * ``` + */ + protocol?: string; +} + +/** + * External Url configuration for use in Kibana. + * @public + */ +export class ExternalUrlConfig implements IExternalUrlConfig { + static readonly DEFAULT = new ExternalUrlConfig(DEFAULT_CONFIG); + + public readonly policy: IExternalUrlPolicy[]; + /** + * Returns the default External Url configuration when passed with no config + * @internal + */ + constructor(rawConfig: IExternalUrlConfig) { + this.policy = rawConfig.policy.map((entry) => { + if (entry.host) { + // If the host contains a `[`, then it's likely an IPv6 address. Otherwise, append a `.` if it doesn't already contain one + const hostToHash = + entry.host && !entry.host.includes('[') && !entry.host.endsWith('.') + ? `${entry.host}.` + : entry.host; + return { + ...entry, + host: createSHA256Hash(hostToHash), + }; + } + return entry; + }); + } +} diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/services/index.js b/src/core/server/external_url/index.ts similarity index 83% rename from src/plugins/es_ui_shared/public/components/cron_editor/services/index.js rename to src/core/server/external_url/index.ts index cb4af15bf1945..dfc8e753fa644 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/services/index.js +++ b/src/core/server/external_url/index.ts @@ -17,5 +17,5 @@ * under the License. */ -export * from './cron'; -export * from './humanized_numbers'; +export { ExternalUrlConfig, IExternalUrlConfig, IExternalUrlPolicy } from './external_url_config'; +export { ExternalUrlConfigType, config } from './config'; diff --git a/src/core/server/http/cookie_session_storage.test.ts b/src/core/server/http/cookie_session_storage.test.ts index 7ac7e4b9712d0..0e7b55b7d35ab 100644 --- a/src/core/server/http/cookie_session_storage.test.ts +++ b/src/core/server/http/cookie_session_storage.test.ts @@ -46,29 +46,40 @@ const setupDeps = { context: contextSetup, }; -configService.atPath.mockReturnValue( - new BehaviorSubject({ - hosts: ['http://1.2.3.4'], - maxPayload: new ByteSizeValue(1024), - autoListen: true, - healthCheck: { - delay: 2000, - }, - ssl: { - verificationMode: 'none', - }, - compression: { enabled: true }, - xsrf: { - disableProtection: true, - allowlist: [], - }, - customResponseHeaders: {}, - requestId: { - allowFromAnyIp: true, - ipAllowlist: [], - }, - } as any) -); +configService.atPath.mockImplementation((path) => { + if (path === 'server') { + return new BehaviorSubject({ + hosts: ['http://1.2.3.4'], + maxPayload: new ByteSizeValue(1024), + autoListen: true, + healthCheck: { + delay: 2000, + }, + ssl: { + verificationMode: 'none', + }, + compression: { enabled: true }, + xsrf: { + disableProtection: true, + allowlist: [], + }, + customResponseHeaders: {}, + requestId: { + allowFromAnyIp: true, + ipAllowlist: [], + }, + } as any); + } + if (path === 'externalUrl') { + return new BehaviorSubject({ + policy: [], + } as any); + } + if (path === 'csp') { + return new BehaviorSubject({} as any); + } + throw new Error(`Unexpected config path: ${path}`); +}); beforeEach(() => { logger = loggingSystemMock.create(); diff --git a/src/core/server/http/http_config.test.ts b/src/core/server/http/http_config.test.ts index 6538c1ae973b7..c82e7c3796e4b 100644 --- a/src/core/server/http/http_config.test.ts +++ b/src/core/server/http/http_config.test.ts @@ -20,6 +20,7 @@ import uuid from 'uuid'; import { config, HttpConfig } from './http_config'; import { CspConfig } from '../csp'; +import { ExternalUrlConfig } from '../external_url'; const validHostnames = ['www.example.com', '8.8.8.8', '::1', 'localhost']; const invalidHostname = 'asdf$%^'; @@ -344,7 +345,7 @@ describe('HttpConfig', () => { }, }, }); - const httpConfig = new HttpConfig(rawConfig, CspConfig.DEFAULT); + const httpConfig = new HttpConfig(rawConfig, CspConfig.DEFAULT, ExternalUrlConfig.DEFAULT); expect(httpConfig.customResponseHeaders).toEqual({ string: 'string', diff --git a/src/core/server/http/http_config.ts b/src/core/server/http/http_config.ts index 9a425fa645503..d26f077723ce3 100644 --- a/src/core/server/http/http_config.ts +++ b/src/core/server/http/http_config.ts @@ -22,6 +22,7 @@ import { hostname } from 'os'; import url from 'url'; import { CspConfigType, CspConfig, ICspConfig } from '../csp'; +import { ExternalUrlConfig, IExternalUrlConfig } from '../external_url'; import { SslConfig, sslSchema } from './ssl_config'; const validBasePathRegex = /^\/.*[^\/]$/; @@ -156,13 +157,18 @@ export class HttpConfig { public ssl: SslConfig; public compression: { enabled: boolean; referrerWhitelist?: string[] }; public csp: ICspConfig; + public externalUrl: IExternalUrlConfig; public xsrf: { disableProtection: boolean; allowlist: string[] }; public requestId: { allowFromAnyIp: boolean; ipAllowlist: string[] }; /** * @internal */ - constructor(rawHttpConfig: HttpConfigType, rawCspConfig: CspConfigType) { + constructor( + rawHttpConfig: HttpConfigType, + rawCspConfig: CspConfigType, + rawExternalUrlConfig: ExternalUrlConfig + ) { this.autoListen = rawHttpConfig.autoListen; this.host = rawHttpConfig.host; this.port = rawHttpConfig.port; @@ -186,6 +192,7 @@ export class HttpConfig { this.ssl = new SslConfig(rawHttpConfig.ssl || {}); this.compression = rawHttpConfig.compression; this.csp = new CspConfig(rawCspConfig); + this.externalUrl = rawExternalUrlConfig; this.xsrf = rawHttpConfig.xsrf; this.requestId = rawHttpConfig.requestId; } diff --git a/src/core/server/http/http_service.mock.ts b/src/core/server/http/http_service.mock.ts index 552f41d912417..d19bee27dd4cf 100644 --- a/src/core/server/http/http_service.mock.ts +++ b/src/core/server/http/http_service.mock.ts @@ -37,6 +37,7 @@ import { OnPostAuthToolkit } from './lifecycle/on_post_auth'; import { OnPreAuthToolkit } from './lifecycle/on_pre_auth'; import { OnPreResponseToolkit } from './lifecycle/on_pre_response'; import { configMock } from '../config/mocks'; +import { ExternalUrlConfig } from '../external_url'; type BasePathMocked = jest.Mocked; type AuthMocked = jest.Mocked; @@ -105,6 +106,7 @@ const createInternalSetupContractMock = () => { registerStaticDir: jest.fn(), basePath: createBasePathMock(), csp: CspConfig.DEFAULT, + externalUrl: ExternalUrlConfig.DEFAULT, auth: createAuthMock(), getAuthHeaders: jest.fn(), getServerInfo: jest.fn(), diff --git a/src/core/server/http/http_service.test.ts b/src/core/server/http/http_service.test.ts index 3d55322461288..9075cb293667a 100644 --- a/src/core/server/http/http_service.test.ts +++ b/src/core/server/http/http_service.test.ts @@ -30,6 +30,7 @@ import { ConfigService, Env } from '../config'; import { loggingSystemMock } from '../logging/logging_system.mock'; import { contextServiceMock } from '../context/context_service.mock'; import { config as cspConfig } from '../csp'; +import { config as externalUrlConfig } from '../external_url'; const logger = loggingSystemMock.create(); const env = Env.createDefault(REPO_ROOT, getEnvOptions()); @@ -48,6 +49,7 @@ const createConfigService = (value: Partial = {}) => { ); configService.setSchema(config.path, config.schema); configService.setSchema(cspConfig.path, cspConfig.schema); + configService.setSchema(externalUrlConfig.path, externalUrlConfig.schema); return configService; }; const contextSetup = contextServiceMock.createSetupContract(); diff --git a/src/core/server/http/http_service.ts b/src/core/server/http/http_service.ts index 171a20160d26d..ae2e82d8b2241 100644 --- a/src/core/server/http/http_service.ts +++ b/src/core/server/http/http_service.ts @@ -44,6 +44,11 @@ import { import { RequestHandlerContext } from '../../server'; import { registerCoreHandlers } from './lifecycle_handlers'; +import { + ExternalUrlConfigType, + config as externalUrlConfig, + ExternalUrlConfig, +} from '../external_url'; interface SetupDeps { context: ContextSetup; @@ -73,7 +78,8 @@ export class HttpService this.config$ = combineLatest([ configService.atPath(httpConfig.path), configService.atPath(cspConfig.path), - ]).pipe(map(([http, csp]) => new HttpConfig(http, csp))); + configService.atPath(externalUrlConfig.path), + ]).pipe(map(([http, csp, externalUrl]) => new HttpConfig(http, csp, externalUrl))); this.httpServer = new HttpServer(logger, 'Kibana'); this.httpsRedirectServer = new HttpsRedirectServer(logger.get('http', 'redirect', 'server')); } @@ -103,6 +109,8 @@ export class HttpService this.internalSetup = { ...serverContract, + externalUrl: new ExternalUrlConfig(config.externalUrl), + createRouter: (path: string, pluginId: PluginOpaqueId = this.coreContext.coreId) => { const enhanceHandler = this.requestHandlerContext!.createHandler.bind(null, pluginId); const router = new Router(path, this.log, enhanceHandler); diff --git a/src/core/server/http/http_tools.test.ts b/src/core/server/http/http_tools.test.ts index 1423e27b914a3..a409a7485a0ef 100644 --- a/src/core/server/http/http_tools.test.ts +++ b/src/core/server/http/http_tools.test.ts @@ -136,6 +136,7 @@ describe('getServerOptions', () => { certificate: 'some-certificate-path', }, }), + {} as any, {} as any ); @@ -165,6 +166,7 @@ describe('getServerOptions', () => { clientAuthentication: 'required', }, }), + {} as any, {} as any ); diff --git a/src/core/server/http/integration_tests/lifecycle_handlers.test.ts b/src/core/server/http/integration_tests/lifecycle_handlers.test.ts index 7df35b04c66cf..ba7f55caeba22 100644 --- a/src/core/server/http/integration_tests/lifecycle_handlers.test.ts +++ b/src/core/server/http/integration_tests/lifecycle_handlers.test.ts @@ -50,26 +50,37 @@ describe('core lifecycle handlers', () => { beforeEach(async () => { const configService = configServiceMock.create(); - configService.atPath.mockReturnValue( - new BehaviorSubject({ - hosts: ['localhost'], - maxPayload: new ByteSizeValue(1024), - autoListen: true, - ssl: { - enabled: false, - }, - compression: { enabled: true }, - name: kibanaName, - customResponseHeaders: { - 'some-header': 'some-value', - }, - xsrf: { disableProtection: false, allowlist: [allowlistedTestPath] }, - requestId: { - allowFromAnyIp: true, - ipAllowlist: [], - }, - } as any) - ); + configService.atPath.mockImplementation((path) => { + if (path === 'server') { + return new BehaviorSubject({ + hosts: ['localhost'], + maxPayload: new ByteSizeValue(1024), + autoListen: true, + ssl: { + enabled: false, + }, + compression: { enabled: true }, + name: kibanaName, + customResponseHeaders: { + 'some-header': 'some-value', + }, + xsrf: { disableProtection: false, allowlist: [allowlistedTestPath] }, + requestId: { + allowFromAnyIp: true, + ipAllowlist: [], + }, + } as any); + } + if (path === 'externalUrl') { + return new BehaviorSubject({ + policy: [], + } as any); + } + if (path === 'csp') { + return new BehaviorSubject({} as any); + } + throw new Error(`Unexpected config path: ${path}`); + }); server = createHttpServer({ configService }); const serverSetup = await server.setup(setupDeps); diff --git a/src/core/server/http/test_utils.ts b/src/core/server/http/test_utils.ts index cdcbe513e1224..0a5cee5505ef1 100644 --- a/src/core/server/http/test_utils.ts +++ b/src/core/server/http/test_utils.ts @@ -32,28 +32,39 @@ const env = Env.createDefault(REPO_ROOT, getEnvOptions()); const logger = loggingSystemMock.create(); const configService = configServiceMock.create(); -configService.atPath.mockReturnValue( - new BehaviorSubject({ - hosts: ['localhost'], - maxPayload: new ByteSizeValue(1024), - autoListen: true, - ssl: { - enabled: false, - }, - compression: { enabled: true }, - xsrf: { - disableProtection: true, - allowlist: [], - }, - customResponseHeaders: {}, - requestId: { - allowFromAnyIp: true, - ipAllowlist: [], - }, - keepaliveTimeout: 120_000, - socketTimeout: 120_000, - } as any) -); +configService.atPath.mockImplementation((path) => { + if (path === 'server') { + return new BehaviorSubject({ + hosts: ['localhost'], + maxPayload: new ByteSizeValue(1024), + autoListen: true, + ssl: { + enabled: false, + }, + compression: { enabled: true }, + xsrf: { + disableProtection: true, + allowlist: [], + }, + customResponseHeaders: {}, + requestId: { + allowFromAnyIp: true, + ipAllowlist: [], + }, + keepaliveTimeout: 120_000, + socketTimeout: 120_000, + } as any); + } + if (path === 'externalUrl') { + return new BehaviorSubject({ + policy: [], + } as any); + } + if (path === 'csp') { + return new BehaviorSubject({} as any); + } + throw new Error(`Unexpected config path: ${path}`); +}); const defaultContext: CoreContext = { coreId, diff --git a/src/core/server/http/types.ts b/src/core/server/http/types.ts index afd7b0174d158..558fa20e0fd6b 100644 --- a/src/core/server/http/types.ts +++ b/src/core/server/http/types.ts @@ -30,6 +30,7 @@ import { OnPreAuthHandler } from './lifecycle/on_pre_auth'; import { OnPostAuthHandler } from './lifecycle/on_post_auth'; import { OnPreResponseHandler } from './lifecycle/on_pre_response'; import { IBasePath } from './base_path_service'; +import { ExternalUrlConfig } from '../external_url'; import { PluginOpaqueId, RequestHandlerContext } from '..'; /** @@ -280,6 +281,7 @@ export interface InternalHttpServiceSetup extends Omit { auth: HttpServerSetup['auth']; server: HttpServerSetup['server']; + externalUrl: ExternalUrlConfig; createRouter: (path: string, plugin?: PluginOpaqueId) => IRouter; registerStaticDir: (path: string, dirPath: string) => void; getAuthHeaders: GetAuthHeaders; diff --git a/src/core/server/index.ts b/src/core/server/index.ts index 6abe067f24c8c..0f2761b67437d 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -136,6 +136,7 @@ export { DeleteDocumentResponse, } from './elasticsearch'; export * from './elasticsearch/legacy/api_types'; +export { IExternalUrlConfig, IExternalUrlPolicy } from './external_url'; export { AuthenticationHandler, AuthHeaders, diff --git a/src/core/server/legacy/legacy_service.ts b/src/core/server/legacy/legacy_service.ts index 6da5d54869801..669286ccb2318 100644 --- a/src/core/server/legacy/legacy_service.ts +++ b/src/core/server/legacy/legacy_service.ts @@ -32,6 +32,7 @@ import { DevConfig, DevConfigType, config as devConfig } from '../dev'; import { BasePathProxyServer, HttpConfig, HttpConfigType, config as httpConfig } from '../http'; import { Logger } from '../logging'; import { LegacyServiceSetupDeps, LegacyServiceStartDeps, LegacyConfig, LegacyVars } from './types'; +import { ExternalUrlConfigType, config as externalUrlConfig } from '../external_url'; import { CoreSetup, CoreStart } from '..'; interface LegacyKbnServer { @@ -84,8 +85,9 @@ export class LegacyService implements CoreService { .pipe(map((rawConfig) => new DevConfig(rawConfig))); this.httpConfig$ = combineLatest( configService.atPath(httpConfig.path), - configService.atPath(cspConfig.path) - ).pipe(map(([http, csp]) => new HttpConfig(http, csp))); + configService.atPath(cspConfig.path), + configService.atPath(externalUrlConfig.path) + ).pipe(map(([http, csp, externalUrl]) => new HttpConfig(http, csp, externalUrl))); } public async setupLegacyConfig() { diff --git a/src/core/server/rendering/__snapshots__/rendering_service.test.ts.snap b/src/core/server/rendering/__snapshots__/rendering_service.test.ts.snap index a3f6b27f135be..f6b39ea24262b 100644 --- a/src/core/server/rendering/__snapshots__/rendering_service.test.ts.snap +++ b/src/core/server/rendering/__snapshots__/rendering_service.test.ts.snap @@ -23,6 +23,13 @@ Object { "version": Any, }, }, + "externalUrl": Object { + "policy": Array [ + Object { + "allow": true, + }, + ], + }, "i18n": Object { "translationsUrl": "/mock-server-basepath/translations/en.json", }, @@ -67,6 +74,13 @@ Object { "version": Any, }, }, + "externalUrl": Object { + "policy": Array [ + Object { + "allow": true, + }, + ], + }, "i18n": Object { "translationsUrl": "/mock-server-basepath/translations/en.json", }, @@ -111,6 +125,13 @@ Object { "version": Any, }, }, + "externalUrl": Object { + "policy": Array [ + Object { + "allow": true, + }, + ], + }, "i18n": Object { "translationsUrl": "/mock-server-basepath/translations/en.json", }, @@ -159,6 +180,13 @@ Object { "version": Any, }, }, + "externalUrl": Object { + "policy": Array [ + Object { + "allow": true, + }, + ], + }, "i18n": Object { "translationsUrl": "/translations/en.json", }, @@ -203,6 +231,13 @@ Object { "version": Any, }, }, + "externalUrl": Object { + "policy": Array [ + Object { + "allow": true, + }, + ], + }, "i18n": Object { "translationsUrl": "/mock-server-basepath/translations/en.json", }, diff --git a/src/core/server/rendering/rendering_service.tsx b/src/core/server/rendering/rendering_service.tsx index 4bbb2bd4811cb..b7c57f1c31e40 100644 --- a/src/core/server/rendering/rendering_service.tsx +++ b/src/core/server/rendering/rendering_service.tsx @@ -79,6 +79,7 @@ export class RenderingService { translationsUrl: `${basePath}/translations/${i18n.getLocale()}.json`, }, csp: { warnLegacyBrowsers: http.csp.warnLegacyBrowsers }, + externalUrl: http.externalUrl, vars: vars ?? {}, uiPlugins: await Promise.all( [...uiPlugins.public].map(async ([id, plugin]) => ({ diff --git a/src/core/server/rendering/types.ts b/src/core/server/rendering/types.ts index 1954fc1c79e55..1b73b2be46835 100644 --- a/src/core/server/rendering/types.ts +++ b/src/core/server/rendering/types.ts @@ -25,6 +25,7 @@ import { InternalHttpServiceSetup, KibanaRequest, LegacyRequest } from '../http' import { UiPlugins, DiscoveredPlugin } from '../plugins'; import { IUiSettingsClient, UserProvidedValues } from '../ui_settings'; import type { InternalStatusServiceSetup } from '../status'; +import { IExternalUrlPolicy } from '../external_url'; /** @internal */ export interface RenderingMetadata { @@ -50,6 +51,7 @@ export interface RenderingMetadata { translationsUrl: string; }; csp: Pick; + externalUrl: { policy: IExternalUrlPolicy[] }; vars: Record; uiPlugins: Array<{ id: string; diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index 703a73a50ebf2..a39bbecd16ff5 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -937,6 +937,18 @@ export interface ICustomClusterClient extends IClusterClient { close: () => Promise; } +// @public +export interface IExternalUrlConfig { + readonly policy: IExternalUrlPolicy[]; +} + +// @public +export interface IExternalUrlPolicy { + allow: boolean; + host?: string; + protocol?: string; +} + // @public export interface IKibanaResponse { // (undocumented) diff --git a/src/core/server/server.ts b/src/core/server/server.ts index 0b3249ad58750..75530e557de04 100644 --- a/src/core/server/server.ts +++ b/src/core/server/server.ts @@ -53,6 +53,7 @@ import { RequestHandlerContext } from '.'; import { InternalCoreSetup, InternalCoreStart, ServiceConfigDescriptor } from './internal_types'; import { CoreUsageDataService } from './core_usage_data'; import { CoreRouteHandlerContext } from './core_route_handler_context'; +import { config as externalUrlConfig } from './external_url'; const coreId = Symbol('core'); const rootConfigPath = ''; @@ -314,6 +315,7 @@ export class Server { pathConfig, cspConfig, elasticsearchConfig, + externalUrlConfig, loggingConfig, httpConfig, pluginsConfig, diff --git a/src/core/server/types.ts b/src/core/server/types.ts index f8d2f635671fa..48b3a9058605c 100644 --- a/src/core/server/types.ts +++ b/src/core/server/types.ts @@ -23,3 +23,4 @@ export * from './saved_objects/types'; export * from './ui_settings/types'; export * from './legacy/types'; export type { EnvironmentMode, PackageInfo } from '@kbn/config'; +export type { ExternalUrlConfig, IExternalUrlPolicy } from './external_url'; diff --git a/src/core/server/ui_settings/create_or_upgrade_saved_config/create_or_upgrade_saved_config.test.ts b/src/core/server/ui_settings/create_or_upgrade_saved_config/create_or_upgrade_saved_config.test.ts index 10a30db038174..3f61db4292604 100644 --- a/src/core/server/ui_settings/create_or_upgrade_saved_config/create_or_upgrade_saved_config.test.ts +++ b/src/core/server/ui_settings/create_or_upgrade_saved_config/create_or_upgrade_saved_config.test.ts @@ -19,10 +19,10 @@ import Chance from 'chance'; +import { getUpgradeableConfigMock } from './get_upgradeable_config.test.mock'; import { SavedObjectsErrorHelpers } from '../../saved_objects'; import { savedObjectsClientMock } from '../../saved_objects/service/saved_objects_client.mock'; import { loggingSystemMock } from '../../logging/logging_system.mock'; -import { getUpgradeableConfigMock } from './get_upgradeable_config.test.mock'; import { createOrUpgradeSavedConfig } from './create_or_upgrade_saved_config'; diff --git a/src/core/server/utils/crypto/index.ts b/src/core/server/utils/crypto/index.ts index 9a36682cc4ecb..aa9728e0462d6 100644 --- a/src/core/server/utils/crypto/index.ts +++ b/src/core/server/utils/crypto/index.ts @@ -18,3 +18,4 @@ */ export { Pkcs12ReadResult, readPkcs12Keystore, readPkcs12Truststore } from './pkcs12'; +export { createSHA256Hash } from './sha256'; diff --git a/tasks/jenkins.js b/src/core/server/utils/crypto/sha256.test.ts similarity index 55% rename from tasks/jenkins.js rename to src/core/server/utils/crypto/sha256.test.ts index 890fef3442079..ddb8ffee36da6 100644 --- a/tasks/jenkins.js +++ b/src/core/server/utils/crypto/sha256.test.ts @@ -17,25 +17,23 @@ * under the License. */ -module.exports = function (grunt) { - grunt.registerTask('jenkins:docs', ['docker:docs']); +import { createSHA256Hash } from './sha256'; - grunt.registerTask('jenkins:unit', [ - 'run:eslint', - 'run:sasslint', - 'run:checkTsProjects', - 'run:checkDocApiChanges', - 'run:typeCheck', - 'run:i18nCheck', - 'run:telemetryCheck', - 'run:checkFileCasing', - 'run:licenses', - 'run:verifyNotice', - 'run:mocha', - 'run:test_jest', - 'run:test_jest_integration', - 'run:test_projects', - 'run:test_hardening', - 'run:apiIntegrationTests', - ]); -}; +describe('createSHA256Hash', () => { + it('creates a hex-encoded hash by default', () => { + expect(createSHA256Hash('foo')).toMatchInlineSnapshot( + `"2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"` + ); + }); + + it('allows the output encoding to be changed', () => { + expect(createSHA256Hash('foo', 'base64')).toMatchInlineSnapshot( + `"LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564="` + ); + }); + + it('accepts a buffer as input', () => { + const data = Buffer.from('foo', 'utf8'); + expect(createSHA256Hash(data)).toEqual(createSHA256Hash('foo')); + }); +}); diff --git a/src/core/server/utils/crypto/sha256.ts b/src/core/server/utils/crypto/sha256.ts new file mode 100644 index 0000000000000..de9eee2efad5a --- /dev/null +++ b/src/core/server/utils/crypto/sha256.ts @@ -0,0 +1,33 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import crypto, { HexBase64Latin1Encoding } from 'crypto'; + +export const createSHA256Hash = ( + input: string | Buffer, + outputEncoding: HexBase64Latin1Encoding = 'hex' +) => { + let data: Buffer; + if (typeof input === 'string') { + data = Buffer.from(input, 'utf8'); + } else { + data = input; + } + return crypto.createHash('sha256').update(data).digest(outputEncoding); +}; diff --git a/src/dev/build/lib/integration_tests/fs.test.ts b/src/dev/build/lib/integration_tests/fs.test.ts index e9ce09554159b..34d5a15261b6d 100644 --- a/src/dev/build/lib/integration_tests/fs.test.ts +++ b/src/dev/build/lib/integration_tests/fs.test.ts @@ -177,6 +177,16 @@ describe('copyAll()', () => { }); it('copies files and directories from source to dest, creating dest if necessary, respecting mode', async () => { + const path777 = resolve(FIXTURES, 'bin/world_executable'); + const path644 = resolve(FIXTURES, 'foo_dir/bar.txt'); + + // we're seeing flaky failures because the resulting files sometimes have + // 755 permissions. Unless there's a bug in vinyl-fs I can't figure out + // where the issue might be, so trying to validate the mode first to narrow + // down where the issue might be + expect(getCommonMode(path777)).toBe(isWindows ? '666' : '777'); + expect(getCommonMode(path644)).toBe(isWindows ? '666' : '644'); + const destination = resolve(TMP, 'a/b/c'); await copyAll(FIXTURES, destination); @@ -185,10 +195,8 @@ describe('copyAll()', () => { resolve(destination, 'foo_dir/foo'), ]); - expect(getCommonMode(resolve(destination, 'bin/world_executable'))).toBe( - isWindows ? '666' : '777' - ); - expect(getCommonMode(resolve(destination, 'foo_dir/bar.txt'))).toBe(isWindows ? '666' : '644'); + expect(getCommonMode(path777)).toBe(isWindows ? '666' : '777'); + expect(getCommonMode(path644)).toBe(isWindows ? '666' : '644'); }); it('applies select globs if specified, ignores dot files', async () => { diff --git a/src/dev/code_coverage/shell_scripts/extract_archives.sh b/src/dev/code_coverage/shell_scripts/extract_archives.sh index 376467f9f2e55..32b4ccd6abccb 100644 --- a/src/dev/code_coverage/shell_scripts/extract_archives.sh +++ b/src/dev/code_coverage/shell_scripts/extract_archives.sh @@ -6,7 +6,7 @@ EXTRACT_DIR=/tmp/extracted_coverage mkdir -p $EXTRACT_DIR echo "### Extracting downloaded artifacts" -for x in kibana-intake x-pack-intake kibana-oss-tests kibana-xpack-tests; do +for x in kibana-intake kibana-oss-tests kibana-xpack-tests; do #x-pack-intake skipping due to failures tar -xzf $DOWNLOAD_DIR/coverage/${x}/kibana-coverage.tar.gz -C $EXTRACT_DIR || echo "### Error 'tarring': ${x}" done diff --git a/src/dev/code_coverage/shell_scripts/generate_team_assignments_and_ingest_coverage.sh b/src/dev/code_coverage/shell_scripts/generate_team_assignments_and_ingest_coverage.sh index 62b81929ae79b..5d983828394bf 100644 --- a/src/dev/code_coverage/shell_scripts/generate_team_assignments_and_ingest_coverage.sh +++ b/src/dev/code_coverage/shell_scripts/generate_team_assignments_and_ingest_coverage.sh @@ -32,7 +32,7 @@ TEAM_ASSIGN_PATH=$5 # Build team assignments dat file node scripts/generate_team_assignments.js --verbose --src .github/CODEOWNERS --dest $TEAM_ASSIGN_PATH -for x in jest functional; do +for x in functional; do #jest skip due to failures echo "### Ingesting coverage for ${x}" COVERAGE_SUMMARY_FILE=target/kibana-coverage/${x}-combined/coverage-summary.json diff --git a/src/dev/code_coverage/shell_scripts/merge_jest_and_functional.sh b/src/dev/code_coverage/shell_scripts/merge_jest_and_functional.sh index 707c6de3f88a0..a8952f987b419 100644 --- a/src/dev/code_coverage/shell_scripts/merge_jest_and_functional.sh +++ b/src/dev/code_coverage/shell_scripts/merge_jest_and_functional.sh @@ -4,6 +4,6 @@ COVERAGE_TEMP_DIR=/tmp/extracted_coverage/target/kibana-coverage/ export COVERAGE_TEMP_DIR echo "### Merge coverage reports" -for x in jest functional; do +for x in functional; do # jest skip due to failures yarn nyc report --nycrc-path src/dev/code_coverage/nyc_config/nyc.${x}.config.js done diff --git a/src/plugins/dashboard/public/application/__snapshots__/dashboard_empty_screen.test.tsx.snap b/src/plugins/dashboard/public/application/__snapshots__/dashboard_empty_screen.test.tsx.snap index b64b485f65615..68d8a6a42eb5d 100644 --- a/src/plugins/dashboard/public/application/__snapshots__/dashboard_empty_screen.test.tsx.snap +++ b/src/plugins/dashboard/public/application/__snapshots__/dashboard_empty_screen.test.tsx.snap @@ -18,6 +18,9 @@ exports[`DashboardEmptyScreen renders correctly with readonly mode 1`] = ` "serverBasePath": "", }, "delete": [MockFunction], + "externalUrl": Object { + "validateUrl": [MockFunction], + }, "fetch": [MockFunction], "get": [MockFunction], "getLoadingCount$": [MockFunction], @@ -382,6 +385,9 @@ exports[`DashboardEmptyScreen renders correctly with visualize paragraph 1`] = ` "serverBasePath": "", }, "delete": [MockFunction], + "externalUrl": Object { + "validateUrl": [MockFunction], + }, "fetch": [MockFunction], "get": [MockFunction], "getLoadingCount$": [MockFunction], @@ -754,6 +760,9 @@ exports[`DashboardEmptyScreen renders correctly without visualize paragraph 1`] "serverBasePath": "", }, "delete": [MockFunction], + "externalUrl": Object { + "validateUrl": [MockFunction], + }, "fetch": [MockFunction], "get": [MockFunction], "getLoadingCount$": [MockFunction], diff --git a/src/plugins/dashboard/public/application/listing/__snapshots__/dashboard_listing.test.js.snap b/src/plugins/dashboard/public/application/listing/__snapshots__/dashboard_listing.test.js.snap index d68011d2f7fde..e817e898cca67 100644 --- a/src/plugins/dashboard/public/application/listing/__snapshots__/dashboard_listing.test.js.snap +++ b/src/plugins/dashboard/public/application/listing/__snapshots__/dashboard_listing.test.js.snap @@ -492,6 +492,7 @@ exports[`renders empty page in before initial fetch to avoid flickering 1`] = ` findItems={[Function]} headingId="dashboardListingHeading" initialFilter="" + initialPageSize={10} listingLimit={1000} noItemsFragment={
diff --git a/src/plugins/dashboard/public/application/listing/dashboard_listing.test.js b/src/plugins/dashboard/public/application/listing/dashboard_listing.test.js index 99b1ebf047d74..cc2c0a2e828ca 100644 --- a/src/plugins/dashboard/public/application/listing/dashboard_listing.test.js +++ b/src/plugins/dashboard/public/application/listing/dashboard_listing.test.js @@ -62,6 +62,7 @@ test('renders empty page in before initial fetch to avoid flickering', () => { getViewUrl={() => {}} listingLimit={1000} hideWriteControls={false} + initialPageSize={10} core={{ notifications: { toasts: {} }, uiSettings: { get: jest.fn(() => 10) } }} /> ); diff --git a/src/plugins/data/common/search/search_source/search_source.test.ts b/src/plugins/data/common/search/search_source/search_source.test.ts index d0c6f0456a8f1..ec5174df50f13 100644 --- a/src/plugins/data/common/search/search_source/search_source.test.ts +++ b/src/plugins/data/common/search/search_source/search_source.test.ts @@ -341,6 +341,21 @@ describe('SearchSource', () => { const request = await searchSource.getSearchRequestBody(); expect(request.script_fields).toEqual({ hello: {} }); }); + + test('returns all scripted fields when one fields entry is *', async () => { + searchSource.setField('index', ({ + ...indexPattern, + getComputedFields: () => ({ + storedFields: [], + scriptFields: { hello: {}, world: {} }, + docvalueFields: [], + }), + } as unknown) as IndexPattern); + searchSource.setField('fields', ['timestamp', '*']); + + const request = await searchSource.getSearchRequestBody(); + expect(request.script_fields).toEqual({ hello: {}, world: {} }); + }); }); describe('handling for when specific fields are provided', () => { diff --git a/src/plugins/data/common/search/search_source/search_source.ts b/src/plugins/data/common/search/search_source/search_source.ts index 2206d6d2816e2..fce0b737b962b 100644 --- a/src/plugins/data/common/search/search_source/search_source.ts +++ b/src/plugins/data/common/search/search_source/search_source.ts @@ -408,7 +408,12 @@ export class SearchSource { case 'query': return addToRoot(key, (data[key] || []).concat(val)); case 'fields': - // uses new Fields API + // This will pass the passed in parameters to the new fields API. + // Also if will only return scripted fields that are part of the specified + // array of fields. If you specify the wildcard `*` as an array element + // the fields API will return all fields, and all scripted fields will be returned. + // NOTE: While the fields API supports wildcards within names, e.g. `user.*` + // scripted fields won't be considered for this. return addToBody('fields', val); case 'fieldsFromSource': // preserves legacy behavior @@ -518,11 +523,13 @@ export class SearchSource { ); const uniqFieldNames = [...new Set([...bodyFieldNames, ...fieldsFromSource])]; - // filter down script_fields to only include items specified - body.script_fields = pick( - body.script_fields, - Object.keys(body.script_fields).filter((f) => uniqFieldNames.includes(f)) - ); + if (!uniqFieldNames.includes('*')) { + // filter down script_fields to only include items specified + body.script_fields = pick( + body.script_fields, + Object.keys(body.script_fields).filter((f) => uniqFieldNames.includes(f)) + ); + } // request the remaining fields from stored_fields just in case, since the // fields API does not handle stored fields diff --git a/src/plugins/data/server/search/search_service.ts b/src/plugins/data/server/search/search_service.ts index 2d4a548f55c11..9d9ffbb41c16f 100644 --- a/src/plugins/data/server/search/search_service.ts +++ b/src/plugins/data/server/search/search_service.ts @@ -106,13 +106,15 @@ export class SearchService implements Plugin { private readonly searchSourceService = new SearchSourceService(); private defaultSearchStrategyName: string = ES_SEARCH_STRATEGY; private searchStrategies: StrategyMap = {}; + private sessionService: ISessionService; private coreStart?: CoreStart; - private sessionService: ISessionService = new SessionService(); constructor( private initializerContext: PluginInitializerContext, private readonly logger: Logger - ) {} + ) { + this.sessionService = new SessionService(); + } public setup( core: CoreSetup<{}, DataPluginStart>, diff --git a/src/plugins/embeddable/public/lib/embeddables/embeddable_renderer.test.tsx b/src/plugins/embeddable/public/lib/embeddables/embeddable_renderer.test.tsx index f9be9d5bfade7..bcd9d31dade26 100644 --- a/src/plugins/embeddable/public/lib/embeddables/embeddable_renderer.test.tsx +++ b/src/plugins/embeddable/public/lib/embeddables/embeddable_renderer.test.tsx @@ -18,7 +18,7 @@ */ import React from 'react'; -import { wait } from '@testing-library/dom'; +import { waitFor } from '@testing-library/dom'; import { render } from '@testing-library/react'; import { HelloWorldEmbeddable, @@ -47,7 +47,7 @@ describe('', () => { ); expect(getByTestId('embedSpinner')).toBeInTheDocument(); - await wait(() => !queryByTestId('embedSpinner')); // wait until spinner disappears + await waitFor(() => !queryByTestId('embedSpinner')); // wait until spinner disappears expect(getByTestId('helloWorldEmbeddable')).toBeInTheDocument(); }); }); diff --git a/src/plugins/embeddable/public/lib/embeddables/error_embeddable.test.tsx b/src/plugins/embeddable/public/lib/embeddables/error_embeddable.test.tsx index cb14d7ed11dc9..743db62ced989 100644 --- a/src/plugins/embeddable/public/lib/embeddables/error_embeddable.test.tsx +++ b/src/plugins/embeddable/public/lib/embeddables/error_embeddable.test.tsx @@ -17,7 +17,7 @@ * under the License. */ import React from 'react'; -import { wait, render } from '@testing-library/react'; +import { waitFor, render } from '@testing-library/react'; import { ErrorEmbeddable } from './error_embeddable'; import { EmbeddableRoot } from './embeddable_root'; @@ -26,7 +26,7 @@ test('ErrorEmbeddable renders an embeddable', async () => { const { getByTestId, getByText } = render(); expect(getByTestId('embeddableStackError')).toBeVisible(); - await wait(() => getByTestId('errorMessageMarkdown')); // wait for lazy markdown component + await waitFor(() => getByTestId('errorMessageMarkdown')); // wait for lazy markdown component expect(getByText(/some error occurred/i)).toBeVisible(); }); @@ -36,7 +36,7 @@ test('ErrorEmbeddable renders an embeddable with markdown message', async () => const { getByTestId, getByText } = render(); expect(getByTestId('embeddableStackError')).toBeVisible(); - await wait(() => getByTestId('errorMessageMarkdown')); // wait for lazy markdown component + await waitFor(() => getByTestId('errorMessageMarkdown')); // wait for lazy markdown component expect(getByText(/some link/i)).toMatchInlineSnapshot(` + + } + labelType="label" + > +
+
+ + + +
+
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+ + + } + labelType="label" + > +
+
+ + + +
+
+ +
+ +
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+ +
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +`; + +exports[`CronEditor is rendered with a HOUR frequency 1`] = ` + + + } + labelType="label" + > +
+
+ + + +
+
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+ + + } + labelType="label" + > +
+
+ + + +
+
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+
+
+`; + +exports[`CronEditor is rendered with a MINUTE frequency 1`] = ` + + + } + labelType="label" + > +
+
+ + + +
+
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+
+`; + +exports[`CronEditor is rendered with a MONTH frequency 1`] = ` + + + } + labelType="label" + > +
+
+ + + +
+
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+ + + } + labelType="label" + > +
+
+ + + +
+
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+ + } + labelType="label" + > +
+
+ + + +
+
+ +
+ +
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+ +
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+`; + +exports[`CronEditor is rendered with a WEEK frequency 1`] = ` + + + } + labelType="label" + > +
+
+ + + +
+
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+ + + } + labelType="label" + > +
+
+ + + +
+
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+ + } + labelType="label" + > +
+
+ + + +
+
+ +
+ +
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+ +
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+`; + +exports[`CronEditor is rendered with a YEAR frequency 1`] = ` + + + } + labelType="label" + > +
+
+ + + +
+
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+ + + } + labelType="label" + > +
+
+ + + +
+
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+ + } + labelType="label" + > +
+
+ + + +
+
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+ + } + labelType="label" + > +
+
+ + + +
+
+ +
+ +
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+ +
+ + +
+ + + +
+ + + + +
+ + + + + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+`; diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/constants.ts b/src/plugins/es_ui_shared/public/components/cron_editor/constants.ts new file mode 100644 index 0000000000000..786e89070d9fb --- /dev/null +++ b/src/plugins/es_ui_shared/public/components/cron_editor/constants.ts @@ -0,0 +1,166 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { padStart } from 'lodash'; +import { EuiSelectOption } from '@elastic/eui'; + +import { DayOrdinal, MonthOrdinal, getOrdinalValue, getDayName, getMonthName } from './services'; +import { Frequency, Field, FieldToValueMap } from './types'; + +type FieldFlags = { + [key in Field]?: boolean; +}; + +function makeSequence(min: number, max: number): number[] { + const values = []; + for (let i = min; i <= max; i++) { + values.push(i); + } + return values; +} + +export const MINUTE_OPTIONS = makeSequence(0, 59).map((value) => ({ + value: value.toString(), + text: padStart(value.toString(), 2, '0'), +})); + +export const HOUR_OPTIONS = makeSequence(0, 23).map((value) => ({ + value: value.toString(), + text: padStart(value.toString(), 2, '0'), +})); + +export const DAY_OPTIONS = makeSequence(1, 7).map((value) => ({ + value: value.toString(), + text: getDayName((value - 1) as DayOrdinal), +})); + +export const DATE_OPTIONS = makeSequence(1, 31).map((value) => ({ + value: value.toString(), + text: getOrdinalValue(value), +})); + +export const MONTH_OPTIONS = makeSequence(1, 12).map((value) => ({ + value: value.toString(), + text: getMonthName((value - 1) as MonthOrdinal), +})); + +export const UNITS: EuiSelectOption[] = [ + { + value: 'MINUTE', + text: 'minute', + }, + { + value: 'HOUR', + text: 'hour', + }, + { + value: 'DAY', + text: 'day', + }, + { + value: 'WEEK', + text: 'week', + }, + { + value: 'MONTH', + text: 'month', + }, + { + value: 'YEAR', + text: 'year', + }, +]; + +export const frequencyToFieldsMap: Record = { + MINUTE: {}, + HOUR: { + minute: true, + }, + DAY: { + hour: true, + minute: true, + }, + WEEK: { + day: true, + hour: true, + minute: true, + }, + MONTH: { + date: true, + hour: true, + minute: true, + }, + YEAR: { + month: true, + date: true, + hour: true, + minute: true, + }, +}; + +export const frequencyToBaselineFieldsMap: Record = { + MINUTE: { + second: '0', + minute: '*', + hour: '*', + date: '*', + month: '*', + day: '?', + }, + HOUR: { + second: '0', + minute: '0', + hour: '*', + date: '*', + month: '*', + day: '?', + }, + DAY: { + second: '0', + minute: '0', + hour: '0', + date: '*', + month: '*', + day: '?', + }, + WEEK: { + second: '0', + minute: '0', + hour: '0', + date: '?', + month: '*', + day: '7', + }, + MONTH: { + second: '0', + minute: '0', + hour: '0', + date: '1', + month: '*', + day: '?', + }, + YEAR: { + second: '0', + minute: '0', + hour: '0', + date: '1', + month: '1', + day: '?', + }, +}; diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.tsx similarity index 83% rename from src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.js rename to src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.tsx index f038766766fe0..42fce194945b9 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.tsx @@ -18,13 +18,25 @@ */ import React, { Fragment } from 'react'; -import PropTypes from 'prop-types'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; +import { EuiFlexGroup, EuiFlexItem, EuiFormRow, EuiSelect, EuiSelectOption } from '@elastic/eui'; -import { EuiFlexGroup, EuiFlexItem, EuiFormRow, EuiSelect } from '@elastic/eui'; +interface Props { + minute?: string; + minuteOptions: EuiSelectOption[]; + hour?: string; + hourOptions: EuiSelectOption[]; + onChange: ({ minute, hour }: { minute?: string; hour?: string }) => void; +} -export const CronDaily = ({ minute, minuteOptions, hour, hourOptions, onChange }) => ( +export const CronDaily: React.FunctionComponent = ({ + minute, + minuteOptions, + hour, + hourOptions, + onChange, +}) => ( ); - -CronDaily.propTypes = { - minute: PropTypes.string.isRequired, - minuteOptions: PropTypes.array.isRequired, - hour: PropTypes.string.isRequired, - hourOptions: PropTypes.array.isRequired, - onChange: PropTypes.func.isRequired, -}; diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.test.tsx b/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.test.tsx new file mode 100644 index 0000000000000..8d0d497e8b5d4 --- /dev/null +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.test.tsx @@ -0,0 +1,137 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import React from 'react'; +import sinon from 'sinon'; +import { findTestSubject } from '@elastic/eui/lib/test'; +import { mountWithI18nProvider } from '@kbn/test/jest'; + +import { Frequency } from './types'; +import { CronEditor } from './cron_editor'; + +jest.mock('@elastic/eui/lib/services/accessibility/html_id_generator', () => { + return { + htmlIdGenerator: () => () => `generated-id`, + }; +}); + +describe('CronEditor', () => { + ['MINUTE', 'HOUR', 'DAY', 'WEEK', 'MONTH', 'YEAR'].forEach((unit) => { + test(`is rendered with a ${unit} frequency`, () => { + const component = mountWithI18nProvider( + {}} + /> + ); + + expect(component).toMatchSnapshot(); + }); + }); + + describe('props', () => { + describe('frequencyBlockList', () => { + it('excludes the blocked frequencies from the frequency list', () => { + const component = mountWithI18nProvider( + {}} + /> + ); + + const frequencySelect = findTestSubject(component, 'cronFrequencySelect'); + expect(frequencySelect.text()).toBe('minutedaymonth'); + }); + }); + + describe('cronExpression', () => { + it('sets the values of the fields', () => { + const component = mountWithI18nProvider( + {}} + /> + ); + + const monthSelect = findTestSubject(component, 'cronFrequencyYearlyMonthSelect'); + expect(monthSelect.props().value).toBe('2'); + + const dateSelect = findTestSubject(component, 'cronFrequencyYearlyDateSelect'); + expect(dateSelect.props().value).toBe('5'); + + const hourSelect = findTestSubject(component, 'cronFrequencyYearlyHourSelect'); + expect(hourSelect.props().value).toBe('10'); + + const minuteSelect = findTestSubject(component, 'cronFrequencyYearlyMinuteSelect'); + expect(minuteSelect.props().value).toBe('20'); + }); + }); + + describe('onChange', () => { + it('is called when the frequency changes', () => { + const onChangeSpy = sinon.spy(); + const component = mountWithI18nProvider( + + ); + + const frequencySelect = findTestSubject(component, 'cronFrequencySelect'); + frequencySelect.simulate('change', { target: { value: 'MONTH' } }); + + sinon.assert.calledWith(onChangeSpy, { + cronExpression: '0 0 0 1 * ?', + fieldToPreferredValueMap: {}, + frequency: 'MONTH', + }); + }); + + it(`is called when a field's value changes`, () => { + const onChangeSpy = sinon.spy(); + const component = mountWithI18nProvider( + + ); + + const minuteSelect = findTestSubject(component, 'cronFrequencyYearlyMinuteSelect'); + minuteSelect.simulate('change', { target: { value: '40' } }); + + sinon.assert.calledWith(onChangeSpy, { + cronExpression: '0 40 * * * ?', + fieldToPreferredValueMap: { minute: '40' }, + frequency: 'YEAR', + }); + }); + }); + }); +}); diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.tsx similarity index 58% rename from src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.js rename to src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.tsx index cde2a253d7630..72e2f51c37e4c 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.tsx @@ -18,207 +18,86 @@ */ import React, { Component, Fragment } from 'react'; -import PropTypes from 'prop-types'; -import { padStart } from 'lodash'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; +import { EuiSelect, EuiFormRow, EuiSelectOption } from '@elastic/eui'; -import { EuiSelect, EuiFormRow } from '@elastic/eui'; +import { Frequency, Field, FieldToValueMap } from './types'; import { - getOrdinalValue, - getDayName, - getMonthName, - cronExpressionToParts, - cronPartsToExpression, - MINUTE, - HOUR, - DAY, - WEEK, - MONTH, - YEAR, -} from './services'; - + MINUTE_OPTIONS, + HOUR_OPTIONS, + DAY_OPTIONS, + DATE_OPTIONS, + MONTH_OPTIONS, + UNITS, + frequencyToFieldsMap, + frequencyToBaselineFieldsMap, +} from './constants'; + +import { cronExpressionToParts, cronPartsToExpression } from './services'; import { CronHourly } from './cron_hourly'; import { CronDaily } from './cron_daily'; import { CronWeekly } from './cron_weekly'; import { CronMonthly } from './cron_monthly'; import { CronYearly } from './cron_yearly'; -function makeSequence(min, max) { - const values = []; - for (let i = min; i <= max; i++) { - values.push(i); +const excludeBlockListedFrequencies = ( + units: EuiSelectOption[], + blockListedUnits: string[] = [] +): EuiSelectOption[] => { + if (blockListedUnits.length === 0) { + return units; } - return values; -} -const MINUTE_OPTIONS = makeSequence(0, 59).map((value) => ({ - value: value.toString(), - text: padStart(value, 2, '0'), -})); - -const HOUR_OPTIONS = makeSequence(0, 23).map((value) => ({ - value: value.toString(), - text: padStart(value, 2, '0'), -})); - -const DAY_OPTIONS = makeSequence(1, 7).map((value) => ({ - value: value.toString(), - text: getDayName(value - 1), -})); - -const DATE_OPTIONS = makeSequence(1, 31).map((value) => ({ - value: value.toString(), - text: getOrdinalValue(value), -})); - -const MONTH_OPTIONS = makeSequence(1, 12).map((value) => ({ - value: value.toString(), - text: getMonthName(value - 1), -})); - -const UNITS = [ - { - value: MINUTE, - text: 'minute', - }, - { - value: HOUR, - text: 'hour', - }, - { - value: DAY, - text: 'day', - }, - { - value: WEEK, - text: 'week', - }, - { - value: MONTH, - text: 'month', - }, - { - value: YEAR, - text: 'year', - }, -]; - -const frequencyToFieldsMap = { - [MINUTE]: {}, - [HOUR]: { - minute: true, - }, - [DAY]: { - hour: true, - minute: true, - }, - [WEEK]: { - day: true, - hour: true, - minute: true, - }, - [MONTH]: { - date: true, - hour: true, - minute: true, - }, - [YEAR]: { - month: true, - date: true, - hour: true, - minute: true, - }, + return units.filter(({ value }) => !blockListedUnits.includes(value as string)); }; -const frequencyToBaselineFieldsMap = { - [MINUTE]: { - second: '0', - minute: '*', - hour: '*', - date: '*', - month: '*', - day: '?', - }, - [HOUR]: { - second: '0', - minute: '0', - hour: '*', - date: '*', - month: '*', - day: '?', - }, - [DAY]: { - second: '0', - minute: '0', - hour: '0', - date: '*', - month: '*', - day: '?', - }, - [WEEK]: { - second: '0', - minute: '0', - hour: '0', - date: '?', - month: '*', - day: '7', - }, - [MONTH]: { - second: '0', - minute: '0', - hour: '0', - date: '1', - month: '*', - day: '?', - }, - [YEAR]: { - second: '0', - minute: '0', - hour: '0', - date: '1', - month: '1', - day: '?', - }, -}; +interface Props { + frequencyBlockList?: string[]; + fieldToPreferredValueMap: FieldToValueMap; + frequency: Frequency; + cronExpression: string; + onChange: ({ + cronExpression, + fieldToPreferredValueMap, + frequency, + }: { + cronExpression: string; + fieldToPreferredValueMap: FieldToValueMap; + frequency: Frequency; + }) => void; +} -export class CronEditor extends Component { - static propTypes = { - fieldToPreferredValueMap: PropTypes.object.isRequired, - frequency: PropTypes.string.isRequired, - cronExpression: PropTypes.string.isRequired, - onChange: PropTypes.func.isRequired, - }; +type State = FieldToValueMap; - static getDerivedStateFromProps(props) { +export class CronEditor extends Component { + static getDerivedStateFromProps(props: Props) { const { cronExpression } = props; return cronExpressionToParts(cronExpression); } - constructor(props) { + constructor(props: Props) { super(props); const { cronExpression } = props; - const parsedCron = cronExpressionToParts(cronExpression); - this.state = { ...parsedCron, }; } - onChangeFrequency = (frequency) => { + onChangeFrequency = (frequency: Frequency) => { const { onChange, fieldToPreferredValueMap } = this.props; // Update fields which aren't editable with acceptable baseline values. - const editableFields = Object.keys(frequencyToFieldsMap[frequency]); - const inheritedFields = editableFields.reduce( - (baselineFields, field) => { + const editableFields = Object.keys(frequencyToFieldsMap[frequency]) as Field[]; + const inheritedFields = editableFields.reduce( + (fieldBaselines, field) => { if (fieldToPreferredValueMap[field] != null) { - baselineFields[field] = fieldToPreferredValueMap[field]; + fieldBaselines[field] = fieldToPreferredValueMap[field]; } - return baselineFields; + return fieldBaselines; }, { ...frequencyToBaselineFieldsMap[frequency] } ); @@ -232,18 +111,21 @@ export class CronEditor extends Component { }); }; - onChangeFields = (fields) => { + onChangeFields = (fields: FieldToValueMap) => { const { onChange, frequency, fieldToPreferredValueMap } = this.props; - const editableFields = Object.keys(frequencyToFieldsMap[frequency]); - const newFieldToPreferredValueMap = {}; + const editableFields = Object.keys(frequencyToFieldsMap[frequency]) as Field[]; + const newFieldToPreferredValueMap: FieldToValueMap = {}; - const editedFields = editableFields.reduce( + const editedFields = editableFields.reduce( (accumFields, field) => { if (fields[field] !== undefined) { accumFields[field] = fields[field]; - // Once the user touches a field, we want to persist its value as the user changes - // the cron frequency. + // If the user changes a field's value, we want to maintain that value in the relevant + // field, even as the frequency field changes. For example, if the user selects "Monthly" + // frequency and changes the "Hour" field to "10", that field should still say "10" if the + // user changes the frequency to "Weekly". We'll support this UX by storing these values + // in the fieldToPreferredValueMap. newFieldToPreferredValueMap[field] = fields[field]; } else { accumFields[field] = this.state[field]; @@ -271,10 +153,10 @@ export class CronEditor extends Component { const { minute, hour, day, date, month } = this.state; switch (frequency) { - case MINUTE: + case 'MINUTE': return; - case HOUR: + case 'HOUR': return ( ); - case DAY: + case 'DAY': return ( ); - case WEEK: + case 'WEEK': return ( ); - case MONTH: + case 'MONTH': return ( ); - case YEAR: + case 'YEAR': return ( @@ -352,9 +234,11 @@ export class CronEditor extends Component { fullWidth > this.onChangeFrequency(e.target.value)} + onChange={(e: React.ChangeEvent) => + this.onChangeFrequency(e.target.value as Frequency) + } fullWidth prepend={i18n.translate('esUi.cronEditor.textEveryLabel', { defaultMessage: 'Every', diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.tsx similarity index 83% rename from src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.js rename to src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.tsx index a04e83195b97f..fb793fd4ff605 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.tsx @@ -18,13 +18,17 @@ */ import React, { Fragment } from 'react'; -import PropTypes from 'prop-types'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; +import { EuiFormRow, EuiSelect, EuiSelectOption } from '@elastic/eui'; -import { EuiFormRow, EuiSelect } from '@elastic/eui'; +interface Props { + minute?: string; + minuteOptions: EuiSelectOption[]; + onChange: ({ minute }: { minute?: string }) => void; +} -export const CronHourly = ({ minute, minuteOptions, onChange }) => ( +export const CronHourly: React.FunctionComponent = ({ minute, minuteOptions, onChange }) => ( ( ); - -CronHourly.propTypes = { - minute: PropTypes.string.isRequired, - minuteOptions: PropTypes.array.isRequired, - onChange: PropTypes.func.isRequired, -}; diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.tsx similarity index 86% rename from src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.js rename to src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.tsx index 28057bd7d9293..729ef1f5f0c15 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.tsx @@ -18,13 +18,21 @@ */ import React, { Fragment } from 'react'; -import PropTypes from 'prop-types'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; +import { EuiFlexGroup, EuiFlexItem, EuiFormRow, EuiSelect, EuiSelectOption } from '@elastic/eui'; -import { EuiFlexGroup, EuiFlexItem, EuiFormRow, EuiSelect } from '@elastic/eui'; +interface Props { + minute?: string; + minuteOptions: EuiSelectOption[]; + hour?: string; + hourOptions: EuiSelectOption[]; + date?: string; + dateOptions: EuiSelectOption[]; + onChange: ({ minute, hour, date }: { minute?: string; hour?: string; date?: string }) => void; +} -export const CronMonthly = ({ +export const CronMonthly: React.FunctionComponent = ({ minute, minuteOptions, hour, @@ -94,13 +102,3 @@ export const CronMonthly = ({ ); - -CronMonthly.propTypes = { - minute: PropTypes.string.isRequired, - minuteOptions: PropTypes.array.isRequired, - hour: PropTypes.string.isRequired, - hourOptions: PropTypes.array.isRequired, - date: PropTypes.string.isRequired, - dateOptions: PropTypes.array.isRequired, - onChange: PropTypes.func.isRequired, -}; diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.tsx similarity index 86% rename from src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.js rename to src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.tsx index c06eecbb381b3..1f10ba5a4ab84 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.tsx @@ -18,13 +18,21 @@ */ import React, { Fragment } from 'react'; -import PropTypes from 'prop-types'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; +import { EuiFlexGroup, EuiFlexItem, EuiFormRow, EuiSelect, EuiSelectOption } from '@elastic/eui'; -import { EuiFlexGroup, EuiFlexItem, EuiFormRow, EuiSelect } from '@elastic/eui'; +interface Props { + minute?: string; + minuteOptions: EuiSelectOption[]; + hour?: string; + hourOptions: EuiSelectOption[]; + day?: string; + dayOptions: EuiSelectOption[]; + onChange: ({ minute, hour, day }: { minute?: string; hour?: string; day?: string }) => void; +} -export const CronWeekly = ({ +export const CronWeekly: React.FunctionComponent = ({ minute, minuteOptions, hour, @@ -94,13 +102,3 @@ export const CronWeekly = ({ ); - -CronWeekly.propTypes = { - minute: PropTypes.string.isRequired, - minuteOptions: PropTypes.array.isRequired, - hour: PropTypes.string.isRequired, - hourOptions: PropTypes.array.isRequired, - day: PropTypes.string.isRequired, - dayOptions: PropTypes.array.isRequired, - onChange: PropTypes.func.isRequired, -}; diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.tsx similarity index 86% rename from src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.js rename to src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.tsx index c3b9691750937..8b65a6f77cfc0 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.tsx @@ -18,13 +18,34 @@ */ import React, { Fragment } from 'react'; -import PropTypes from 'prop-types'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; -import { EuiFlexGroup, EuiFlexItem, EuiFormRow, EuiSelect } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiFormRow, EuiSelect, EuiSelectOption } from '@elastic/eui'; -export const CronYearly = ({ +interface Props { + minute?: string; + minuteOptions: EuiSelectOption[]; + hour?: string; + hourOptions: EuiSelectOption[]; + date?: string; + dateOptions: EuiSelectOption[]; + month?: string; + monthOptions: EuiSelectOption[]; + onChange: ({ + minute, + hour, + date, + month, + }: { + minute?: string; + hour?: string; + date?: string; + month?: string; + }) => void; +} + +export const CronYearly: React.FunctionComponent = ({ minute, minuteOptions, hour, @@ -115,15 +136,3 @@ export const CronYearly = ({ ); - -CronYearly.propTypes = { - minute: PropTypes.string.isRequired, - minuteOptions: PropTypes.array.isRequired, - hour: PropTypes.string.isRequired, - hourOptions: PropTypes.array.isRequired, - date: PropTypes.string.isRequired, - dateOptions: PropTypes.array.isRequired, - month: PropTypes.string.isRequired, - monthOptions: PropTypes.array.isRequired, - onChange: PropTypes.func.isRequired, -}; diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/index.js b/src/plugins/es_ui_shared/public/components/cron_editor/index.ts similarity index 92% rename from src/plugins/es_ui_shared/public/components/cron_editor/index.js rename to src/plugins/es_ui_shared/public/components/cron_editor/index.ts index 6c4539a6c3f75..b1e27feb6f835 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/index.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/index.ts @@ -17,5 +17,5 @@ * under the License. */ +export { Frequency } from './types'; export { CronEditor } from './cron_editor'; -export { MINUTE, HOUR, DAY, WEEK, MONTH, YEAR } from './services'; diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/services/cron.js b/src/plugins/es_ui_shared/public/components/cron_editor/services/cron.ts similarity index 81% rename from src/plugins/es_ui_shared/public/components/cron_editor/services/cron.js rename to src/plugins/es_ui_shared/public/components/cron_editor/services/cron.ts index 995169739f7dc..be78552584148 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/services/cron.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/services/cron.ts @@ -17,15 +17,10 @@ * under the License. */ -export const MINUTE = 'MINUTE'; -export const HOUR = 'HOUR'; -export const DAY = 'DAY'; -export const WEEK = 'WEEK'; -export const MONTH = 'MONTH'; -export const YEAR = 'YEAR'; +import { FieldToValueMap } from '../types'; -export function cronExpressionToParts(expression) { - const parsedCron = { +export function cronExpressionToParts(expression: string): FieldToValueMap { + const parsedCron: FieldToValueMap = { second: undefined, minute: undefined, hour: undefined, @@ -63,6 +58,13 @@ export function cronExpressionToParts(expression) { return parsedCron; } -export function cronPartsToExpression({ second, minute, hour, day, date, month }) { +export function cronPartsToExpression({ + second, + minute, + hour, + day, + date, + month, +}: FieldToValueMap): string { return `${second} ${minute} ${hour} ${date} ${month} ${day}`; } diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/services/humanized_numbers.js b/src/plugins/es_ui_shared/public/components/cron_editor/services/humanized_numbers.ts similarity index 87% rename from src/plugins/es_ui_shared/public/components/cron_editor/services/humanized_numbers.js rename to src/plugins/es_ui_shared/public/components/cron_editor/services/humanized_numbers.ts index 69fa085cc3f3e..25ac0db3d35d8 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/services/humanized_numbers.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/services/humanized_numbers.ts @@ -19,6 +19,9 @@ import { i18n } from '@kbn/i18n'; +export type DayOrdinal = 0 | 1 | 2 | 3 | 4 | 5 | 6; +export type MonthOrdinal = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11; + // The international ISO standard dictates Monday as the first day of the week, but cron patterns // use Sunday as the first day, so we're going with the cron way. const dayOrdinalToDayNameMap = { @@ -46,7 +49,7 @@ const monthOrdinalToMonthNameMap = { 11: i18n.translate('esUi.cronEditor.month.december', { defaultMessage: 'December' }), }; -export function getOrdinalValue(number) { +export function getOrdinalValue(number: number): string { // TODO: This is breaking reporting pdf generation. Possibly due to phantom not setting locale, // which is needed by i18n (formatjs). Need to verify, fix, and restore i18n in place of static stings. // return i18n.translate('esUi.cronEditor.number.ordinal', { @@ -57,15 +60,16 @@ export function getOrdinalValue(number) { // Protects against falsey (including 0) values const num = number && number.toString(); - let lastDigit = num && num.substr(-1); + const lastDigitString = num && num.substr(-1); let ordinal; - if (!lastDigit) { - return number; + if (!lastDigitString) { + return number.toString(); } - lastDigit = parseFloat(lastDigit); - switch (lastDigit) { + const lastDigitNumeric = parseFloat(lastDigitString); + + switch (lastDigitNumeric) { case 1: ordinal = 'st'; break; @@ -82,10 +86,10 @@ export function getOrdinalValue(number) { return `${num}${ordinal}`; } -export function getDayName(dayOrdinal) { +export function getDayName(dayOrdinal: DayOrdinal): string { return dayOrdinalToDayNameMap[dayOrdinal]; } -export function getMonthName(monthOrdinal) { +export function getMonthName(monthOrdinal: MonthOrdinal): string { return monthOrdinalToMonthNameMap[monthOrdinal]; } diff --git a/tasks/config/watch.js b/src/plugins/es_ui_shared/public/components/cron_editor/services/index.ts similarity index 80% rename from tasks/config/watch.js rename to src/plugins/es_ui_shared/public/components/cron_editor/services/index.ts index b132b7e5f8087..ff10a283c2fa1 100644 --- a/tasks/config/watch.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/services/index.ts @@ -17,9 +17,11 @@ * under the License. */ -module.exports = { - peg: { - files: ['src/legacy/utils/kuery/ast/*.peg'], - tasks: ['peg'], - }, -}; +export { cronExpressionToParts, cronPartsToExpression } from './cron'; +export { + getOrdinalValue, + getDayName, + getMonthName, + DayOrdinal, + MonthOrdinal, +} from './humanized_numbers'; diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/index.d.ts b/src/plugins/es_ui_shared/public/components/cron_editor/types.ts similarity index 76% rename from src/plugins/es_ui_shared/public/components/cron_editor/index.d.ts rename to src/plugins/es_ui_shared/public/components/cron_editor/types.ts index b318587057c76..3e5b7c916632a 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/index.d.ts +++ b/src/plugins/es_ui_shared/public/components/cron_editor/types.ts @@ -17,10 +17,8 @@ * under the License. */ -export declare const MINUTE: string; -export declare const HOUR: string; -export declare const DAY: string; -export declare const WEEK: string; -export declare const MONTH: string; -export declare const YEAR: string; -export declare const CronEditor: any; +export type Frequency = 'MINUTE' | 'HOUR' | 'DAY' | 'WEEK' | 'MONTH' | 'YEAR'; +export type Field = 'second' | 'minute' | 'hour' | 'day' | 'date' | 'month'; +export type FieldToValueMap = { + [key in Field]?: string; +}; diff --git a/src/plugins/es_ui_shared/public/index.ts b/src/plugins/es_ui_shared/public/index.ts index f48198459d48d..304916b1d379d 100644 --- a/src/plugins/es_ui_shared/public/index.ts +++ b/src/plugins/es_ui_shared/public/index.ts @@ -30,7 +30,7 @@ export { JsonEditor, OnJsonEditorUpdateHandler, JsonEditorState } from './compon export { SectionLoading } from './components/section_loading'; -export { CronEditor, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR } from './components/cron_editor'; +export { Frequency, CronEditor } from './components/cron_editor'; export { SendRequestConfig, diff --git a/src/plugins/es_ui_shared/public/request/use_request.test.ts b/src/plugins/es_ui_shared/public/request/use_request.test.ts index 2a639f93b47b4..822bf56e5e3cc 100644 --- a/src/plugins/es_ui_shared/public/request/use_request.test.ts +++ b/src/plugins/es_ui_shared/public/request/use_request.test.ts @@ -101,8 +101,9 @@ describe('useRequest hook', () => { const { setupSuccessRequest, completeRequest, hookResult } = helpers; setupSuccessRequest(); expect(hookResult.isInitialRequest).toBe(true); - - hookResult.resendRequest(); + act(() => { + hookResult.resendRequest(); + }); await completeRequest(); expect(hookResult.isInitialRequest).toBe(false); }); diff --git a/src/plugins/index_pattern_management/public/components/field_editor/__snapshots__/field_editor.test.tsx.snap b/src/plugins/index_pattern_management/public/components/field_editor/__snapshots__/field_editor.test.tsx.snap index 29cbec38a5982..d24b31599f903 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/__snapshots__/field_editor.test.tsx.snap +++ b/src/plugins/index_pattern_management/public/components/field_editor/__snapshots__/field_editor.test.tsx.snap @@ -54,7 +54,7 @@ exports[`FieldEditor should render create new scripted field correctly 1`] = ` @@ -294,7 +294,7 @@ exports[`FieldEditor should render edit scripted field correctly 1`] = ` @@ -586,7 +586,7 @@ exports[`FieldEditor should show conflict field warning 1`] = ` @@ -827,7 +827,7 @@ exports[`FieldEditor should show deprecated lang warning 1`] = ` @@ -1200,7 +1200,7 @@ exports[`FieldEditor should show multiple type field warning with a table contai diff --git a/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx b/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx index 29a87a65fdff7..a402dc59185e8 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx @@ -425,7 +425,7 @@ export class FieldEditor extends PureComponent } > diff --git a/src/plugins/saved_objects_management/public/management_section/objects_table/components/__snapshots__/flyout.test.tsx.snap b/src/plugins/saved_objects_management/public/management_section/objects_table/components/__snapshots__/flyout.test.tsx.snap index d06fd0df98a8c..a48965cf7f41c 100644 --- a/src/plugins/saved_objects_management/public/management_section/objects_table/components/__snapshots__/flyout.test.tsx.snap +++ b/src/plugins/saved_objects_management/public/management_section/objects_table/components/__snapshots__/flyout.test.tsx.snap @@ -180,6 +180,9 @@ exports[`Flyout conflicts should allow conflict resolution 2`] = ` "serverBasePath": "", }, "delete": [MockFunction], + "externalUrl": Object { + "validateUrl": [MockFunction], + }, "fetch": [MockFunction], "get": [MockFunction], "getLoadingCount$": [MockFunction], diff --git a/src/plugins/saved_objects_tagging_oss/public/api.mock.ts b/src/plugins/saved_objects_tagging_oss/public/api.mock.ts index 87a3fd8f5b499..1e66a9baa812e 100644 --- a/src/plugins/saved_objects_tagging_oss/public/api.mock.ts +++ b/src/plugins/saved_objects_tagging_oss/public/api.mock.ts @@ -18,10 +18,10 @@ */ import { ITagsClient } from '../common'; -import { SavedObjectsTaggingApiUi, SavedObjectsTaggingApiUiComponent } from './api'; +import { SavedObjectsTaggingApiUi, SavedObjectsTaggingApiUiComponent, ITagsCache } from './api'; -const createClientMock = (): jest.Mocked => { - const mock = { +const createClientMock = () => { + const mock: jest.Mocked = { create: jest.fn(), get: jest.fn(), getAll: jest.fn(), @@ -32,14 +32,25 @@ const createClientMock = (): jest.Mocked => { return mock; }; +const createCacheMock = () => { + const mock: jest.Mocked = { + getState: jest.fn(), + getState$: jest.fn(), + }; + + return mock; +}; + interface SavedObjectsTaggingApiMock { client: jest.Mocked; + cache: jest.Mocked; ui: SavedObjectsTaggingApiUiMock; } const createApiMock = (): SavedObjectsTaggingApiMock => { - const mock = { + const mock: SavedObjectsTaggingApiMock = { client: createClientMock(), + cache: createCacheMock(), ui: createApiUiMock(), }; @@ -50,8 +61,8 @@ type SavedObjectsTaggingApiUiMock = Omit, components: SavedObjectsTaggingApiUiComponentMock; }; -const createApiUiMock = (): SavedObjectsTaggingApiUiMock => { - const mock = { +const createApiUiMock = () => { + const mock: SavedObjectsTaggingApiUiMock = { components: createApiUiComponentsMock(), // TS is very picky with type guards hasTagDecoration: jest.fn() as any, @@ -69,8 +80,8 @@ const createApiUiMock = (): SavedObjectsTaggingApiUiMock => { type SavedObjectsTaggingApiUiComponentMock = jest.Mocked; -const createApiUiComponentsMock = (): SavedObjectsTaggingApiUiComponentMock => { - const mock = { +const createApiUiComponentsMock = () => { + const mock: SavedObjectsTaggingApiUiComponentMock = { TagList: jest.fn(), TagSelector: jest.fn(), SavedObjectSaveModalTagSelector: jest.fn(), @@ -82,6 +93,7 @@ const createApiUiComponentsMock = (): SavedObjectsTaggingApiUiComponentMock => { export const taggingApiMock = { create: createApiMock, createClient: createClientMock, + createCache: createCacheMock, createUi: createApiUiMock, createComponents: createApiUiComponentsMock, }; diff --git a/src/plugins/saved_objects_tagging_oss/public/api.ts b/src/plugins/saved_objects_tagging_oss/public/api.ts index 81f7cc9326a77..987930af1e3e4 100644 --- a/src/plugins/saved_objects_tagging_oss/public/api.ts +++ b/src/plugins/saved_objects_tagging_oss/public/api.ts @@ -17,22 +17,49 @@ * under the License. */ +import { Observable } from 'rxjs'; import { SearchFilterConfig, EuiTableFieldDataColumnType } from '@elastic/eui'; import type { FunctionComponent } from 'react'; import { SavedObject, SavedObjectReference } from '../../../core/types'; import { SavedObjectsFindOptionsReference } from '../../../core/public'; import { SavedObject as SavedObjectClass } from '../../saved_objects/public'; import { TagDecoratedSavedObject } from './decorator'; -import { ITagsClient } from '../common'; +import { ITagsClient, Tag } from '../common'; /** * @public */ export interface SavedObjectsTaggingApi { + /** + * The client to perform tag-related operations on the server-side + */ client: ITagsClient; + /** + * A client-side auto-refreshing cache of the existing tags. Can be used + * to synchronously access the list of tags. + */ + cache: ITagsCache; + /** + * UI API to use to add tagging capabilities to an application + */ ui: SavedObjectsTaggingApiUi; } +/** + * @public + */ +export interface ITagsCache { + /** + * Return the current state of the cache + */ + getState(): Tag[]; + + /** + * Return an observable that will emit everytime the cache's state mutates. + */ + getState$(): Observable; +} + /** * @public */ diff --git a/src/plugins/saved_objects_tagging_oss/public/index.ts b/src/plugins/saved_objects_tagging_oss/public/index.ts index bc824621830d2..ef3087f944add 100644 --- a/src/plugins/saved_objects_tagging_oss/public/index.ts +++ b/src/plugins/saved_objects_tagging_oss/public/index.ts @@ -26,6 +26,7 @@ export { SavedObjectsTaggingApi, SavedObjectsTaggingApiUi, SavedObjectsTaggingApiUiComponent, + ITagsCache, TagListComponentProps, TagSelectorComponentProps, GetSearchBarFilterOptions, diff --git a/src/plugins/telemetry_management_section/public/components/__snapshots__/telemetry_management_section.test.tsx.snap b/src/plugins/telemetry_management_section/public/components/__snapshots__/telemetry_management_section.test.tsx.snap index cad06255ffe98..896b1671328a9 100644 --- a/src/plugins/telemetry_management_section/public/components/__snapshots__/telemetry_management_section.test.tsx.snap +++ b/src/plugins/telemetry_management_section/public/components/__snapshots__/telemetry_management_section.test.tsx.snap @@ -321,6 +321,9 @@ exports[`TelemetryManagementSectionComponent renders null because allowChangingO "serverBasePath": "", }, "delete": [MockFunction], + "externalUrl": Object { + "validateUrl": [MockFunction], + }, "fetch": [MockFunction], "get": [MockFunction], "getLoadingCount$": [MockFunction], diff --git a/src/plugins/telemetry_management_section/public/components/opt_in_example_flyout.tsx b/src/plugins/telemetry_management_section/public/components/opt_in_example_flyout.tsx index 402fc55eaf7c3..bd78cdc931d0a 100644 --- a/src/plugins/telemetry_management_section/public/components/opt_in_example_flyout.tsx +++ b/src/plugins/telemetry_management_section/public/components/opt_in_example_flyout.tsx @@ -49,6 +49,8 @@ interface State { * React component for displaying the example data associated with the Telemetry opt-in banner. */ export class OptInExampleFlyout extends React.PureComponent { + _isMounted = false; + public readonly state: State = { data: null, isLoading: true, @@ -56,14 +58,18 @@ export class OptInExampleFlyout extends React.PureComponent { }; async componentDidMount() { + this._isMounted = true; + try { const { fetchExample } = this.props; const clusters = await fetchExample(); - this.setState({ - data: Array.isArray(clusters) ? clusters : null, - isLoading: false, - hasPrivilegeToRead: true, - }); + if (this._isMounted) { + this.setState({ + data: Array.isArray(clusters) ? clusters : null, + isLoading: false, + hasPrivilegeToRead: true, + }); + } } catch (err) { this.setState({ isLoading: false, @@ -72,6 +78,10 @@ export class OptInExampleFlyout extends React.PureComponent { } } + componentWillUnmount() { + this._isMounted = false; + } + renderBody({ data, isLoading, hasPrivilegeToRead }: State) { if (isLoading) { return loadingSpinner; diff --git a/src/plugins/ui_actions/kibana.json b/src/plugins/ui_actions/kibana.json index 337c5ddf0fd5c..ca979aa021026 100644 --- a/src/plugins/ui_actions/kibana.json +++ b/src/plugins/ui_actions/kibana.json @@ -3,9 +3,6 @@ "version": "kibana", "server": false, "ui": true, - "extraPublicDirs": [ - "public/tests/test_samples" - ], "requiredBundles": [ "kibanaUtils", "kibanaReact" diff --git a/src/plugins/vis_default_editor/public/components/agg_select.tsx b/src/plugins/vis_default_editor/public/components/agg_select.tsx index 9d45b72d35cc0..689cc52691bb6 100644 --- a/src/plugins/vis_default_editor/public/components/agg_select.tsx +++ b/src/plugins/vis_default_editor/public/components/agg_select.tsx @@ -77,15 +77,15 @@ function DefaultEditorAggSelect({ } const helpLink = value && aggHelpLink && ( - - + + - - + + ); const errors = aggError ? [aggError] : []; diff --git a/src/plugins/vis_type_markdown/public/markdown_vis_controller.test.tsx b/src/plugins/vis_type_markdown/public/markdown_vis_controller.test.tsx index 7bc8cdbd14170..e9494e086a734 100644 --- a/src/plugins/vis_type_markdown/public/markdown_vis_controller.test.tsx +++ b/src/plugins/vis_type_markdown/public/markdown_vis_controller.test.tsx @@ -18,7 +18,7 @@ */ import React from 'react'; -import { wait, render } from '@testing-library/react'; +import { waitFor, render } from '@testing-library/react'; import MarkdownVisComponent from './markdown_vis_controller'; describe('markdown vis controller', () => { @@ -36,7 +36,7 @@ describe('markdown vis controller', () => { ); - await wait(() => getByTestId('markdownBody')); + await waitFor(() => getByTestId('markdownBody')); expect(getByText('markdown')).toMatchInlineSnapshot(`
{ ); - await wait(() => getByTestId('markdownBody')); + await waitFor(() => getByTestId('markdownBody')); expect(getByText(/testing/i)).toMatchInlineSnapshot(`

@@ -82,7 +82,7 @@ describe('markdown vis controller', () => { ); - await wait(() => getByTestId('markdownBody')); + await waitFor(() => getByTestId('markdownBody')); expect(getByText(/initial/i)).toBeInTheDocument(); @@ -112,7 +112,7 @@ describe('markdown vis controller', () => { ); - await wait(() => getByTestId('markdownBody')); + await waitFor(() => getByTestId('markdownBody')); expect(renderComplete).toHaveBeenCalledTimes(1); }); @@ -122,7 +122,7 @@ describe('markdown vis controller', () => { ); - await wait(() => getByTestId('markdownBody')); + await waitFor(() => getByTestId('markdownBody')); expect(renderComplete).toHaveBeenCalledTimes(1); @@ -139,7 +139,7 @@ describe('markdown vis controller', () => { ); - await wait(() => getByTestId('markdownBody')); + await waitFor(() => getByTestId('markdownBody')); expect(renderComplete).toHaveBeenCalledTimes(1); diff --git a/src/plugins/vis_type_vega/public/vega_visualization.test.js b/src/plugins/vis_type_vega/public/vega_visualization.test.js index 8a073ca32b94a..e4c4c1df202ef 100644 --- a/src/plugins/vis_type_vega/public/vega_visualization.test.js +++ b/src/plugins/vis_type_vega/public/vega_visualization.test.js @@ -17,6 +17,8 @@ * under the License. */ +import 'jest-canvas-mock'; + import $ from 'jquery'; import 'leaflet/dist/leaflet.js'; diff --git a/src/plugins/vis_type_vislib/public/vislib/components/legend/legend.test.tsx b/src/plugins/vis_type_vislib/public/vislib/components/legend/legend.test.tsx index a3fb536d0aec5..7acc97404c11c 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/legend/legend.test.tsx +++ b/src/plugins/vis_type_vislib/public/vislib/components/legend/legend.test.tsx @@ -25,6 +25,7 @@ import { EuiButtonGroup } from '@elastic/eui'; import { VisLegend, VisLegendProps } from './legend'; import { legendColors } from './models'; +import { act } from '@testing-library/react'; jest.mock('@elastic/eui', () => { const original = jest.requireActual('@elastic/eui'); @@ -206,7 +207,9 @@ describe('VisLegend Component', () => { const first = getLegendItems(wrapper).first(); first.simulate('click'); const filterGroup = wrapper.find(EuiButtonGroup).first(); - filterGroup.getElement().props.onChange('filterIn'); + act(() => { + filterGroup.getElement().props.onChange('filterIn'); + }); expect(fireEvent).toHaveBeenCalledWith({ name: 'filterBucket', @@ -219,7 +222,9 @@ describe('VisLegend Component', () => { const first = getLegendItems(wrapper).first(); first.simulate('click'); const filterGroup = wrapper.find(EuiButtonGroup).first(); - filterGroup.getElement().props.onChange('filterOut'); + act(() => { + filterGroup.getElement().props.onChange('filterOut'); + }); expect(fireEvent).toHaveBeenCalledWith({ name: 'filterBucket', diff --git a/tasks/config/run.js b/tasks/config/run.js deleted file mode 100644 index 0a1bb9617e1f9..0000000000000 --- a/tasks/config/run.js +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -const { version } = require('../../package.json'); -const KIBANA_INSTALL_DIR = - process.env.KIBANA_INSTALL_DIR || - `./build/oss/kibana-${version}-SNAPSHOT-${process.platform}-x86_64`; - -module.exports = function () { - const NODE = 'node'; - const YARN = 'yarn'; - const scriptWithGithubChecks = ({ title, options, cmd, args }) => - process.env.CHECKS_REPORTER_ACTIVE === 'true' - ? { - options, - cmd: YARN, - args: ['run', 'github-checks-reporter', title, cmd, ...args], - } - : { options, cmd, args }; - const gruntTaskWithGithubChecks = (title, task) => - scriptWithGithubChecks({ - title, - cmd: YARN, - args: ['run', 'grunt', task], - }); - - return { - // used by the test and jenkins:unit tasks - // runs the eslint script to check for linting errors - eslint: scriptWithGithubChecks({ - title: 'eslint', - cmd: NODE, - args: ['scripts/eslint', '--no-cache'], - }), - - sasslint: scriptWithGithubChecks({ - title: 'sasslint', - cmd: NODE, - args: ['scripts/sasslint'], - }), - - // used by the test tasks - // runs the check_file_casing script to ensure filenames use correct casing - checkFileCasing: scriptWithGithubChecks({ - title: 'Check file casing', - cmd: NODE, - args: [ - 'scripts/check_file_casing', - '--quiet', // only log errors, not warnings - ], - }), - - // used by the test tasks - // runs the check_published_api_changes script to ensure API changes are explictily accepted - checkDocApiChanges: scriptWithGithubChecks({ - title: 'Check core API changes', - cmd: NODE, - args: ['scripts/check_published_api_changes'], - }), - - // used by the test and jenkins:unit tasks - // runs the typecheck script to check for Typescript type errors - typeCheck: scriptWithGithubChecks({ - title: 'Type check', - cmd: NODE, - args: ['scripts/type_check'], - }), - - // used by the test and jenkins:unit tasks - // ensures that all typescript files belong to a typescript project - checkTsProjects: scriptWithGithubChecks({ - title: 'TypeScript - all files belong to a TypeScript project', - cmd: NODE, - args: ['scripts/check_ts_projects'], - }), - - // used by the test and jenkins:unit tasks - // runs the i18n_check script to check i18n engine usage - i18nCheck: scriptWithGithubChecks({ - title: 'Internationalization check', - cmd: NODE, - args: ['scripts/i18n_check', '--ignore-missing'], - }), - - telemetryCheck: scriptWithGithubChecks({ - title: 'Telemetry Schema check', - cmd: NODE, - args: ['scripts/telemetry_check'], - }), - - // used by the test:quick task - // runs all node.js/server mocha tests - mocha: scriptWithGithubChecks({ - title: 'Mocha tests', - cmd: NODE, - args: ['scripts/mocha'], - }), - - // used by the test:mochaCoverage task - mochaCoverage: scriptWithGithubChecks({ - title: 'Mocha tests coverage', - cmd: YARN, - args: [ - 'nyc', - '--reporter=html', - '--reporter=json-summary', - '--report-dir=./target/kibana-coverage/mocha', - NODE, - 'scripts/mocha', - ], - }), - - verifyNotice: scriptWithGithubChecks({ - title: 'Verify NOTICE.txt', - options: { - wait: true, - }, - cmd: NODE, - args: ['scripts/notice', '--validate'], - }), - - test_hardening: scriptWithGithubChecks({ - title: 'Node.js hardening tests', - cmd: NODE, - args: ['scripts/test_hardening.js'], - }), - - apiIntegrationTests: scriptWithGithubChecks({ - title: 'API integration tests', - cmd: NODE, - args: [ - 'scripts/functional_tests', - '--config', - 'test/api_integration/config.js', - '--bail', - '--debug', - ], - }), - - serverIntegrationTests: scriptWithGithubChecks({ - title: 'Server integration tests', - cmd: NODE, - args: [ - 'scripts/functional_tests', - '--config', - 'test/server_integration/http/ssl/config.js', - '--config', - 'test/server_integration/http/ssl_redirect/config.js', - '--config', - 'test/server_integration/http/platform/config.ts', - '--config', - 'test/server_integration/http/ssl_with_p12/config.js', - '--config', - 'test/server_integration/http/ssl_with_p12_intermediate/config.js', - '--bail', - '--debug', - '--kibana-install-dir', - KIBANA_INSTALL_DIR, - ], - }), - - interpreterFunctionalTestsRelease: scriptWithGithubChecks({ - title: 'Interpreter functional tests', - cmd: NODE, - args: [ - 'scripts/functional_tests', - '--config', - 'test/interpreter_functional/config.ts', - '--bail', - '--debug', - '--kibana-install-dir', - KIBANA_INSTALL_DIR, - ], - }), - - pluginFunctionalTestsRelease: scriptWithGithubChecks({ - title: 'Plugin functional tests', - cmd: NODE, - args: [ - 'scripts/functional_tests', - '--config', - 'test/plugin_functional/config.ts', - '--bail', - '--debug', - ], - }), - - exampleFunctionalTestsRelease: scriptWithGithubChecks({ - title: 'Example functional tests', - cmd: NODE, - args: [ - 'scripts/functional_tests', - '--config', - 'test/examples/config.js', - '--bail', - '--debug', - ], - }), - - functionalTests: scriptWithGithubChecks({ - title: 'Functional tests', - cmd: NODE, - args: [ - 'scripts/functional_tests', - '--config', - 'test/functional/config.js', - '--bail', - '--debug', - ], - }), - - licenses: scriptWithGithubChecks({ - title: 'Check licenses', - cmd: NODE, - args: ['scripts/check_licenses', '--dev'], - }), - - test_jest: gruntTaskWithGithubChecks('Jest tests', 'test:jest'), - test_jest_integration: gruntTaskWithGithubChecks( - 'Jest integration tests', - 'test:jest_integration' - ), - test_projects: gruntTaskWithGithubChecks('Project tests', 'test:projects'), - }; -}; diff --git a/tasks/test.js b/tasks/test.js deleted file mode 100644 index f370ea0b948c6..0000000000000 --- a/tasks/test.js +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { run } from '../utilities/visual_regression'; - -module.exports = function (grunt) { - grunt.registerTask( - 'test:visualRegression:buildGallery', - 'Compare screenshots and generate diff images.', - function () { - const done = this.async(); - run(done); - } - ); - - grunt.registerTask('test:quick', [ - 'checkPlugins', - 'run:mocha', - 'run:functionalTests', - 'test:jest', - 'test:jest_integration', - 'test:projects', - 'run:apiIntegrationTests', - ]); - - grunt.registerTask('test:mochaCoverage', ['run:mochaCoverage']); - - grunt.registerTask('test', (subTask) => { - if (subTask) grunt.fail.fatal(`invalid task "test:${subTask}"`); - - grunt.task.run( - [ - !grunt.option('quick') && 'run:eslint', - !grunt.option('quick') && 'run:sasslint', - !grunt.option('quick') && 'run:checkTsProjects', - !grunt.option('quick') && 'run:checkDocApiChanges', - !grunt.option('quick') && 'run:typeCheck', - !grunt.option('quick') && 'run:i18nCheck', - 'run:checkFileCasing', - 'run:licenses', - 'test:quick', - ].filter(Boolean) - ); - }); - - grunt.registerTask('quick-test', ['test:quick']); // historical alias - - grunt.registerTask('test:projects', function () { - const done = this.async(); - runProjectsTests().then(done, done); - }); - - function runProjectsTests() { - const serverCmd = { - cmd: 'yarn', - args: ['kbn', 'run', 'test', '--exclude', 'kibana', '--oss', '--skip-kibana-plugins'], - opts: { stdio: 'inherit' }, - }; - - return new Promise((resolve, reject) => { - grunt.util.spawn(serverCmd, (error, result, code) => { - if (error || code !== 0) { - const error = new Error(`projects tests exited with code ${code}`); - grunt.fail.fatal(error); - reject(error); - return; - } - - grunt.log.writeln(result); - resolve(); - }); - }); - } -}; diff --git a/tasks/test_jest.js b/tasks/test_jest.js deleted file mode 100644 index 810ed42324840..0000000000000 --- a/tasks/test_jest.js +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -const { resolve } = require('path'); - -module.exports = function (grunt) { - grunt.registerTask('test:jest', function () { - const done = this.async(); - runJest(resolve(__dirname, '../scripts/jest.js'), ['--maxWorkers=10']).then(done, done); - }); - - grunt.registerTask('test:jest_integration', function () { - const done = this.async(); - runJest(resolve(__dirname, '../scripts/jest_integration.js')).then(done, done); - }); - - function runJest(jestScript, args = []) { - const serverCmd = { - cmd: 'node', - args: [jestScript, '--ci', ...args], - opts: { stdio: 'inherit' }, - }; - - return new Promise((resolve, reject) => { - grunt.util.spawn(serverCmd, (error, result, code) => { - if (error || code !== 0) { - const error = new Error(`jest exited with code ${code}`); - grunt.fail.fatal(error); - reject(error); - return; - } - - grunt.log.writeln(result); - resolve(); - }); - }); - } -}; diff --git a/test/functional/page_objects/common_page.ts b/test/functional/page_objects/common_page.ts index f52343a9d913b..bd084fe1fb081 100644 --- a/test/functional/page_objects/common_page.ts +++ b/test/functional/page_objects/common_page.ts @@ -467,6 +467,13 @@ export function CommonPageProvider({ getService, getPageObjects }: FtrProviderCo await button.click(); } } + + /** + * Get visible text of the Welcome Banner + */ + async getWelcomeText() { + return await testSubjects.getVisibleText('global-banner-item'); + } } return new CommonPage(); diff --git a/test/scripts/checks/bundle_limits.sh b/test/scripts/checks/bundle_limits.sh index 10d9d9343fda4..cfe08d73bb558 100755 --- a/test/scripts/checks/bundle_limits.sh +++ b/test/scripts/checks/bundle_limits.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -node scripts/build_kibana_platform_plugins --validate-limits +checks-reporter-with-killswitch "Check Bundle Limits" \ + node scripts/build_kibana_platform_plugins --validate-limits diff --git a/test/scripts/checks/doc_api_changes.sh b/test/scripts/checks/doc_api_changes.sh index 503d12b2f6d73..f2f508fd8f7d4 100755 --- a/test/scripts/checks/doc_api_changes.sh +++ b/test/scripts/checks/doc_api_changes.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:checkDocApiChanges +checks-reporter-with-killswitch "Check Doc API Changes" \ + node scripts/check_published_api_changes diff --git a/test/scripts/checks/file_casing.sh b/test/scripts/checks/file_casing.sh index 513664263791b..b30dfaab62a98 100755 --- a/test/scripts/checks/file_casing.sh +++ b/test/scripts/checks/file_casing.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:checkFileCasing +checks-reporter-with-killswitch "Check File Casing" \ + node scripts/check_file_casing --quiet diff --git a/test/scripts/checks/i18n.sh b/test/scripts/checks/i18n.sh index 7a6fd46c46c76..e7a2060aaa73a 100755 --- a/test/scripts/checks/i18n.sh +++ b/test/scripts/checks/i18n.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:i18nCheck +checks-reporter-with-killswitch "Check i18n" \ + node scripts/i18n_check --ignore-missing diff --git a/test/scripts/checks/jest_configs.sh b/test/scripts/checks/jest_configs.sh old mode 100644 new mode 100755 index 28cb1386c748f..67fbee0b9fdf0 --- a/test/scripts/checks/jest_configs.sh +++ b/test/scripts/checks/jest_configs.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -checks-reporter-with-killswitch "Check Jest Configs" node scripts/check_jest_configs +checks-reporter-with-killswitch "Check Jest Configs" \ + node scripts/check_jest_configs diff --git a/test/scripts/checks/licenses.sh b/test/scripts/checks/licenses.sh index a08d7d07a24a1..22494f11ce77c 100755 --- a/test/scripts/checks/licenses.sh +++ b/test/scripts/checks/licenses.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:licenses +checks-reporter-with-killswitch "Check Licenses" \ + node scripts/check_licenses --dev diff --git a/test/scripts/checks/mocha_coverage.sh b/test/scripts/checks/mocha_coverage.sh new file mode 100755 index 0000000000000..e1afad0ab775f --- /dev/null +++ b/test/scripts/checks/mocha_coverage.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +source src/dev/ci_setup/setup_env.sh + +yarn nyc --reporter=html --reporter=json-summary --report-dir=./target/kibana-coverage/mocha node scripts/mocha diff --git a/test/scripts/checks/plugins_with_circular_deps.sh b/test/scripts/checks/plugins_with_circular_deps.sh old mode 100644 new mode 100755 index 77880243538d2..a608d7e7b2edf --- a/test/scripts/checks/plugins_with_circular_deps.sh +++ b/test/scripts/checks/plugins_with_circular_deps.sh @@ -2,5 +2,5 @@ source src/dev/ci_setup/setup_env.sh -checks-reporter-with-killswitch "Check plugins with circular dependencies" \ +checks-reporter-with-killswitch "Check Plugins With Circular Dependencies" \ node scripts/find_plugins_with_circular_deps diff --git a/test/scripts/checks/telemetry.sh b/test/scripts/checks/telemetry.sh index c74ec295b385c..1622704b1fa92 100755 --- a/test/scripts/checks/telemetry.sh +++ b/test/scripts/checks/telemetry.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:telemetryCheck +checks-reporter-with-killswitch "Check Telemetry Schema" \ + node scripts/telemetry_check diff --git a/test/scripts/checks/test_hardening.sh b/test/scripts/checks/test_hardening.sh index 9184758577654..cd0c5a7d3c3aa 100755 --- a/test/scripts/checks/test_hardening.sh +++ b/test/scripts/checks/test_hardening.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:test_hardening +checks-reporter-with-killswitch "Test Hardening" \ + node scripts/test_hardening diff --git a/test/scripts/checks/test_projects.sh b/test/scripts/checks/test_projects.sh index 5f9aafe80e10e..56f15f6839e9d 100755 --- a/test/scripts/checks/test_projects.sh +++ b/test/scripts/checks/test_projects.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:test_projects +checks-reporter-with-killswitch "Test Projects" \ + yarn kbn run test --exclude kibana --oss --skip-kibana-plugins diff --git a/test/scripts/checks/ts_projects.sh b/test/scripts/checks/ts_projects.sh index d667c753baec2..467beb2977efc 100755 --- a/test/scripts/checks/ts_projects.sh +++ b/test/scripts/checks/ts_projects.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:checkTsProjects +checks-reporter-with-killswitch "Check TypeScript Projects" \ + node scripts/check_ts_projects diff --git a/test/scripts/checks/type_check.sh b/test/scripts/checks/type_check.sh index 07c49638134be..5e091625de4ed 100755 --- a/test/scripts/checks/type_check.sh +++ b/test/scripts/checks/type_check.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:typeCheck +checks-reporter-with-killswitch "Check Types" \ + node scripts/type_check diff --git a/test/scripts/checks/verify_notice.sh b/test/scripts/checks/verify_notice.sh index 9f8343e540861..99bfd55edd3c1 100755 --- a/test/scripts/checks/verify_notice.sh +++ b/test/scripts/checks/verify_notice.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:verifyNotice +checks-reporter-with-killswitch "Verify NOTICE" \ + node scripts/notice --validate diff --git a/test/scripts/jenkins_ci_group.sh b/test/scripts/jenkins_ci_group.sh index f9e9d40cd8b0d..4faf645975c77 100755 --- a/test/scripts/jenkins_ci_group.sh +++ b/test/scripts/jenkins_ci_group.sh @@ -13,9 +13,9 @@ if [[ -z "$CODE_COVERAGE" ]]; then if [[ ! "$TASK_QUEUE_PROCESS_ID" && "$CI_GROUP" == "1" ]]; then source test/scripts/jenkins_build_kbn_sample_panel_action.sh - yarn run grunt run:pluginFunctionalTestsRelease --from=source; - yarn run grunt run:exampleFunctionalTestsRelease --from=source; - yarn run grunt run:interpreterFunctionalTestsRelease; + ./test/scripts/test/plugin_functional.sh + ./test/scripts/test/example_functional.sh + ./test/scripts/test/interpreter_functional.sh fi else echo " -> Running Functional tests with code coverage" diff --git a/test/scripts/jenkins_docs.sh b/test/scripts/jenkins_docs.sh index bd606d60101d8..f447afda1f948 100755 --- a/test/scripts/jenkins_docs.sh +++ b/test/scripts/jenkins_docs.sh @@ -3,4 +3,4 @@ set -e source "$(dirname $0)/../../src/dev/ci_setup/setup.sh" -"$(FORCE_COLOR=0 yarn bin)/grunt" jenkins:docs; +"$(FORCE_COLOR=0 yarn bin)/grunt" docker:docs; diff --git a/test/scripts/jenkins_plugin_functional.sh b/test/scripts/jenkins_plugin_functional.sh index 1d691d98982de..1811bdeb4ed4b 100755 --- a/test/scripts/jenkins_plugin_functional.sh +++ b/test/scripts/jenkins_plugin_functional.sh @@ -10,6 +10,6 @@ cd -; pwd -yarn run grunt run:pluginFunctionalTestsRelease --from=source; -yarn run grunt run:exampleFunctionalTestsRelease --from=source; -yarn run grunt run:interpreterFunctionalTestsRelease; +./test/scripts/test/plugin_functional.sh +./test/scripts/test/example_functional.sh +./test/scripts/test/interpreter_functional.sh diff --git a/test/scripts/jenkins_unit.sh b/test/scripts/jenkins_unit.sh index 1f6a3d440734b..c788a4a5b01ae 100755 --- a/test/scripts/jenkins_unit.sh +++ b/test/scripts/jenkins_unit.sh @@ -9,20 +9,43 @@ rename_coverage_file() { } if [[ -z "$CODE_COVERAGE" ]] ; then - "$(FORCE_COLOR=0 yarn bin)/grunt" jenkins:unit --dev; + # Lint + ./test/scripts/lint/eslint.sh + ./test/scripts/lint/sasslint.sh + + # Test + ./test/scripts/test/jest_integration.sh + ./test/scripts/test/mocha.sh + ./test/scripts/test/jest_unit.sh + ./test/scripts/test/api_integration.sh + + # Check + ./test/scripts/checks/telemetry.sh + ./test/scripts/checks/ts_projects.sh + ./test/scripts/checks/jest_configs.sh + ./test/scripts/checks/doc_api_changes.sh + ./test/scripts/checks/type_check.sh + ./test/scripts/checks/bundle_limits.sh + ./test/scripts/checks/i18n.sh + ./test/scripts/checks/file_casing.sh + ./test/scripts/checks/licenses.sh + ./test/scripts/checks/plugins_with_circular_deps.sh + ./test/scripts/checks/verify_notice.sh + ./test/scripts/checks/test_projects.sh + ./test/scripts/checks/test_hardening.sh else - echo " -> Running jest tests with coverage" - node scripts/jest --ci --verbose --coverage - rename_coverage_file "oss" - echo "" - echo "" - echo " -> Running jest integration tests with coverage" - node --max-old-space-size=8192 scripts/jest_integration --ci --verbose --coverage || true; - rename_coverage_file "oss-integration" - echo "" - echo "" + # echo " -> Running jest tests with coverage" + # node scripts/jest --ci --verbose --coverage + # rename_coverage_file "oss" + # echo "" + # echo "" + # echo " -> Running jest integration tests with coverage" + # node --max-old-space-size=8192 scripts/jest_integration --ci --verbose --coverage || true; + # rename_coverage_file "oss-integration" + # echo "" + # echo "" echo " -> Running mocha tests with coverage" - yarn run grunt "test:mochaCoverage"; + ./test/scripts/checks/mocha_coverage.sh echo "" echo "" fi diff --git a/test/scripts/lint/eslint.sh b/test/scripts/lint/eslint.sh index c3211300b96c5..053150e42f409 100755 --- a/test/scripts/lint/eslint.sh +++ b/test/scripts/lint/eslint.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:eslint +checks-reporter-with-killswitch "Lint: eslint" \ + node scripts/eslint --no-cache diff --git a/test/scripts/lint/sasslint.sh b/test/scripts/lint/sasslint.sh index b9c683bcb049e..72e341cdcda16 100755 --- a/test/scripts/lint/sasslint.sh +++ b/test/scripts/lint/sasslint.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:sasslint +checks-reporter-with-killswitch "Lint: sasslint" \ + node scripts/sasslint diff --git a/test/scripts/server_integration.sh b/test/scripts/server_integration.sh deleted file mode 100755 index 82bc733e51b26..0000000000000 --- a/test/scripts/server_integration.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -source test/scripts/jenkins_test_setup_oss.sh - -yarn run grunt run:serverIntegrationTests diff --git a/test/scripts/test/api_integration.sh b/test/scripts/test/api_integration.sh index 152c97a3ca7df..bf6f683989fe5 100755 --- a/test/scripts/test/api_integration.sh +++ b/test/scripts/test/api_integration.sh @@ -2,4 +2,8 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:apiIntegrationTests +checks-reporter-with-killswitch "API Integration Tests" \ + node scripts/functional_tests \ + --config test/api_integration/config.js \ + --bail \ + --debug diff --git a/test/scripts/test/example_functional.sh b/test/scripts/test/example_functional.sh new file mode 100755 index 0000000000000..08915085505bc --- /dev/null +++ b/test/scripts/test/example_functional.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +source test/scripts/jenkins_test_setup_oss.sh + +checks-reporter-with-killswitch "Example Functional Tests" \ + node scripts/functional_tests \ + --config test/examples/config.js \ + --bail \ + --debug diff --git a/test/scripts/test/interpreter_functional.sh b/test/scripts/test/interpreter_functional.sh new file mode 100755 index 0000000000000..1558989c0fdfc --- /dev/null +++ b/test/scripts/test/interpreter_functional.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +source test/scripts/jenkins_test_setup_oss.sh + +checks-reporter-with-killswitch "Interpreter Functional Tests" \ + node scripts/functional_tests \ + --config test/interpreter_functional/config.ts \ + --bail \ + --debug \ + --kibana-install-dir $KIBANA_INSTALL_DIR diff --git a/test/scripts/test/jest_integration.sh b/test/scripts/test/jest_integration.sh index 73dbbddfb38f6..8791248e9a166 100755 --- a/test/scripts/test/jest_integration.sh +++ b/test/scripts/test/jest_integration.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:test_jest_integration +checks-reporter-with-killswitch "Jest Integration Tests" \ + node scripts/jest_integration diff --git a/test/scripts/test/jest_unit.sh b/test/scripts/test/jest_unit.sh index e25452698cebc..de5e16c2b1366 100755 --- a/test/scripts/test/jest_unit.sh +++ b/test/scripts/test/jest_unit.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:test_jest +checks-reporter-with-killswitch "Jest Unit Tests" \ + node scripts/jest diff --git a/test/scripts/test/karma_ci.sh b/test/scripts/test/karma_ci.sh deleted file mode 100755 index e9985300ba19d..0000000000000 --- a/test/scripts/test/karma_ci.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -source src/dev/ci_setup/setup_env.sh - -yarn run grunt run:test_karma_ci diff --git a/test/scripts/test/mocha.sh b/test/scripts/test/mocha.sh index 43c00f0a09dcf..e5f3259926e42 100755 --- a/test/scripts/test/mocha.sh +++ b/test/scripts/test/mocha.sh @@ -2,4 +2,5 @@ source src/dev/ci_setup/setup_env.sh -yarn run grunt run:mocha +checks-reporter-with-killswitch "Mocha Tests" \ + node scripts/mocha diff --git a/test/scripts/test/plugin_functional.sh b/test/scripts/test/plugin_functional.sh new file mode 100755 index 0000000000000..e0af062e1de4a --- /dev/null +++ b/test/scripts/test/plugin_functional.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +source test/scripts/jenkins_test_setup_oss.sh + +checks-reporter-with-killswitch "Plugin Functional Tests" \ + node scripts/functional_tests \ + --config test/plugin_functional/config.ts \ + --bail \ + --debug diff --git a/test/scripts/test/server_integration.sh b/test/scripts/test/server_integration.sh new file mode 100755 index 0000000000000..1ff4a772bb6e0 --- /dev/null +++ b/test/scripts/test/server_integration.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +source test/scripts/jenkins_test_setup_oss.sh + +checks-reporter-with-killswitch "Server Integration Tests" \ + node scripts/functional_tests \ + --config test/server_integration/http/ssl/config.js \ + --config test/server_integration/http/ssl_redirect/config.js \ + --config test/server_integration/http/platform/config.ts \ + --config test/server_integration/http/ssl_with_p12/config.js \ + --config test/server_integration/http/ssl_with_p12_intermediate/config.js \ + --bail \ + --debug \ + --kibana-install-dir $KIBANA_INSTALL_DIR diff --git a/vars/kibanaCoverage.groovy b/vars/kibanaCoverage.groovy index 521672e4bf48c..422a6c188979d 100644 --- a/vars/kibanaCoverage.groovy +++ b/vars/kibanaCoverage.groovy @@ -59,7 +59,7 @@ def uploadBaseWebsiteFiles(prefix) { def uploadCoverageHtmls(prefix) { [ 'target/kibana-coverage/functional-combined', - 'target/kibana-coverage/jest-combined', + // 'target/kibana-coverage/jest-combined', skipped due to failures 'target/kibana-coverage/mocha-combined', ].each { uploadWithVault(prefix, it) } } @@ -200,13 +200,14 @@ def ingest(jobName, buildNumber, buildUrl, timestamp, previousSha, teamAssignmen def runTests() { parallel([ 'kibana-intake-agent': workers.intake('kibana-intake', './test/scripts/jenkins_unit.sh'), - 'x-pack-intake-agent': { - withEnv([ - 'NODE_ENV=test' // Needed for jest tests only - ]) { - workers.intake('x-pack-intake', './test/scripts/jenkins_xpack.sh')() - } - }, + // skipping due to failures + // 'x-pack-intake-agent': { + // withEnv([ + // 'NODE_ENV=test' // Needed for jest tests only + // ]) { + // workers.intake('x-pack-intake', './test/scripts/jenkins_xpack.sh')() + // } + // }, 'kibana-oss-agent' : workers.functional( 'kibana-oss-tests', { kibanaPipeline.buildOss() }, diff --git a/vars/tasks.groovy b/vars/tasks.groovy index 348da83cc1364..22f446eeb00da 100644 --- a/vars/tasks.groovy +++ b/vars/tasks.groovy @@ -75,7 +75,7 @@ def functionalOss(Map params = [:]) { } if (config.serverIntegration) { - task(kibanaPipeline.scriptTaskDocker('serverIntegration', './test/scripts/server_integration.sh')) + task(kibanaPipeline.scriptTaskDocker('serverIntegration', './test/scripts/test/server_integration.sh')) } } } diff --git a/x-pack/plugins/alerts/common/disabled_action_groups.test.ts b/x-pack/plugins/alerts/common/disabled_action_groups.test.ts new file mode 100644 index 0000000000000..96db7bfd8710d --- /dev/null +++ b/x-pack/plugins/alerts/common/disabled_action_groups.test.ts @@ -0,0 +1,19 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { isActionGroupDisabledForActionTypeId } from './disabled_action_groups'; +import { RecoveredActionGroup } from './builtin_action_groups'; + +test('returns false if action group id has no disabled types', () => { + expect(isActionGroupDisabledForActionTypeId('enabledActionGroup', '.jira')).toBeFalsy(); +}); + +test('returns false if action group id does not contains type', () => { + expect(isActionGroupDisabledForActionTypeId(RecoveredActionGroup.id, '.email')).toBeFalsy(); +}); + +test('returns true if action group id does contain type', () => { + expect(isActionGroupDisabledForActionTypeId(RecoveredActionGroup.id, '.jira')).toBeTruthy(); +}); diff --git a/x-pack/plugins/alerts/common/disabled_action_groups.ts b/x-pack/plugins/alerts/common/disabled_action_groups.ts new file mode 100644 index 0000000000000..525a267a278ea --- /dev/null +++ b/x-pack/plugins/alerts/common/disabled_action_groups.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; + * you may not use this file except in compliance with the Elastic License. + */ +import { RecoveredActionGroup } from './builtin_action_groups'; + +const DisabledActionGroupsByActionType: Record = { + [RecoveredActionGroup.id]: ['.jira', '.servicenow', '.resilient'], +}; + +export const DisabledActionTypeIdsForActionGroup: Map = new Map( + Object.entries(DisabledActionGroupsByActionType) +); + +export function isActionGroupDisabledForActionTypeId( + actionGroup: string, + actionTypeId: string +): boolean { + return ( + DisabledActionTypeIdsForActionGroup.has(actionGroup) && + DisabledActionTypeIdsForActionGroup.get(actionGroup)!.includes(actionTypeId) + ); +} diff --git a/x-pack/plugins/alerts/common/index.ts b/x-pack/plugins/alerts/common/index.ts index 4d0e7bf7eb0bc..3e551facd98a0 100644 --- a/x-pack/plugins/alerts/common/index.ts +++ b/x-pack/plugins/alerts/common/index.ts @@ -13,6 +13,7 @@ export * from './alert_task_instance'; export * from './alert_navigation'; export * from './alert_instance_summary'; export * from './builtin_action_groups'; +export * from './disabled_action_groups'; export interface AlertingFrameworkHealth { isSufficientlySecure: boolean; diff --git a/x-pack/plugins/alerts/server/alerts_client_factory.test.ts b/x-pack/plugins/alerts/server/alerts_client_factory.test.ts index 49a90c62bc581..93a479eeef487 100644 --- a/x-pack/plugins/alerts/server/alerts_client_factory.test.ts +++ b/x-pack/plugins/alerts/server/alerts_client_factory.test.ts @@ -33,6 +33,7 @@ const savedObjectsService = savedObjectsServiceMock.createInternalStartContract( const features = featuresPluginMock.createStart(); const securityPluginSetup = securityMock.createSetup(); +const securityPluginStart = securityMock.createStart(); const alertsClientFactoryParams: jest.Mocked = { logger: loggingSystemMock.create().get(), taskManager: taskManagerMock.createStart(), @@ -77,7 +78,7 @@ beforeEach(() => { test('creates an alerts client with proper constructor arguments when security is enabled', async () => { const factory = new AlertsClientFactory(); - factory.initialize({ securityPluginSetup, ...alertsClientFactoryParams }); + factory.initialize({ securityPluginSetup, securityPluginStart, ...alertsClientFactoryParams }); const request = KibanaRequest.from(fakeRequest); const { AlertsAuthorizationAuditLogger } = jest.requireMock('./authorization/audit_logger'); @@ -98,7 +99,7 @@ test('creates an alerts client with proper constructor arguments when security i const { AlertsAuthorization } = jest.requireMock('./authorization/alerts_authorization'); expect(AlertsAuthorization).toHaveBeenCalledWith({ request, - authorization: securityPluginSetup.authz, + authorization: securityPluginStart.authz, alertTypeRegistry: alertsClientFactoryParams.alertTypeRegistry, features: alertsClientFactoryParams.features, auditLogger: expect.any(AlertsAuthorizationAuditLogger), @@ -188,11 +189,12 @@ test('getUserName() returns a name when security is enabled', async () => { factory.initialize({ ...alertsClientFactoryParams, securityPluginSetup, + securityPluginStart, }); factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; - securityPluginSetup.authc.getCurrentUser.mockReturnValueOnce(({ + securityPluginStart.authc.getCurrentUser.mockReturnValueOnce(({ username: 'bob', } as unknown) as AuthenticatedUser); const userNameResult = await constructorCall.getUserName(); @@ -225,7 +227,7 @@ test('createAPIKey() returns { apiKeysEnabled: false } when security is enabled factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; - securityPluginSetup.authc.grantAPIKeyAsInternalUser.mockResolvedValueOnce(null); + securityPluginStart.authc.apiKeys.grantAsInternalUser.mockResolvedValueOnce(null); const createAPIKeyResult = await constructorCall.createAPIKey(); expect(createAPIKeyResult).toEqual({ apiKeysEnabled: false }); }); @@ -235,11 +237,12 @@ test('createAPIKey() returns an API key when security is enabled', async () => { factory.initialize({ ...alertsClientFactoryParams, securityPluginSetup, + securityPluginStart, }); factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; - securityPluginSetup.authc.grantAPIKeyAsInternalUser.mockResolvedValueOnce({ + securityPluginStart.authc.apiKeys.grantAsInternalUser.mockResolvedValueOnce({ api_key: '123', id: 'abc', name: '', @@ -256,11 +259,12 @@ test('createAPIKey() throws when security plugin createAPIKey throws an error', factory.initialize({ ...alertsClientFactoryParams, securityPluginSetup, + securityPluginStart, }); factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; - securityPluginSetup.authc.grantAPIKeyAsInternalUser.mockRejectedValueOnce( + securityPluginStart.authc.apiKeys.grantAsInternalUser.mockRejectedValueOnce( new Error('TLS disabled') ); await expect(constructorCall.createAPIKey()).rejects.toThrowErrorMatchingInlineSnapshot( diff --git a/x-pack/plugins/alerts/server/alerts_client_factory.ts b/x-pack/plugins/alerts/server/alerts_client_factory.ts index 9d71b5f817b2c..86091c89b6031 100644 --- a/x-pack/plugins/alerts/server/alerts_client_factory.ts +++ b/x-pack/plugins/alerts/server/alerts_client_factory.ts @@ -14,7 +14,7 @@ import { PluginStartContract as ActionsPluginStartContract } from '../../actions import { AlertsClient } from './alerts_client'; import { ALERTS_FEATURE_ID } from '../common'; import { AlertTypeRegistry, SpaceIdToNamespaceFunction } from './types'; -import { SecurityPluginSetup } from '../../security/server'; +import { SecurityPluginSetup, SecurityPluginStart } from '../../security/server'; import { EncryptedSavedObjectsClient } from '../../encrypted_saved_objects/server'; import { TaskManagerStartContract } from '../../task_manager/server'; import { PluginStartContract as FeaturesPluginStart } from '../../features/server'; @@ -28,6 +28,7 @@ export interface AlertsClientFactoryOpts { taskManager: TaskManagerStartContract; alertTypeRegistry: AlertTypeRegistry; securityPluginSetup?: SecurityPluginSetup; + securityPluginStart?: SecurityPluginStart; getSpaceId: (request: KibanaRequest) => string | undefined; getSpace: (request: KibanaRequest) => Promise; spaceIdToNamespace: SpaceIdToNamespaceFunction; @@ -44,6 +45,7 @@ export class AlertsClientFactory { private taskManager!: TaskManagerStartContract; private alertTypeRegistry!: AlertTypeRegistry; private securityPluginSetup?: SecurityPluginSetup; + private securityPluginStart?: SecurityPluginStart; private getSpaceId!: (request: KibanaRequest) => string | undefined; private getSpace!: (request: KibanaRequest) => Promise; private spaceIdToNamespace!: SpaceIdToNamespaceFunction; @@ -64,6 +66,7 @@ export class AlertsClientFactory { this.taskManager = options.taskManager; this.alertTypeRegistry = options.alertTypeRegistry; this.securityPluginSetup = options.securityPluginSetup; + this.securityPluginStart = options.securityPluginStart; this.spaceIdToNamespace = options.spaceIdToNamespace; this.encryptedSavedObjectsClient = options.encryptedSavedObjectsClient; this.actions = options.actions; @@ -73,10 +76,10 @@ export class AlertsClientFactory { } public create(request: KibanaRequest, savedObjects: SavedObjectsServiceStart): AlertsClient { - const { securityPluginSetup, actions, eventLog, features } = this; + const { securityPluginSetup, securityPluginStart, actions, eventLog, features } = this; const spaceId = this.getSpaceId(request); const authorization = new AlertsAuthorization({ - authorization: securityPluginSetup?.authz, + authorization: securityPluginStart?.authz, request, getSpace: this.getSpace, alertTypeRegistry: this.alertTypeRegistry, @@ -102,25 +105,22 @@ export class AlertsClientFactory { encryptedSavedObjectsClient: this.encryptedSavedObjectsClient, auditLogger: securityPluginSetup?.audit.asScoped(request), async getUserName() { - if (!securityPluginSetup) { + if (!securityPluginStart) { return null; } - const user = await securityPluginSetup.authc.getCurrentUser(request); + const user = await securityPluginStart.authc.getCurrentUser(request); return user ? user.username : null; }, async createAPIKey(name: string) { - if (!securityPluginSetup) { + if (!securityPluginStart) { return { apiKeysEnabled: false }; } // Create an API key using the new grant API - in this case the Kibana system user is creating the // API key for the user, instead of having the user create it themselves, which requires api_key // privileges - const createAPIKeyResult = await securityPluginSetup.authc.grantAPIKeyAsInternalUser( + const createAPIKeyResult = await securityPluginStart.authc.apiKeys.grantAsInternalUser( request, - { - name, - role_descriptors: {}, - } + { name, role_descriptors: {} } ); if (!createAPIKeyResult) { return { apiKeysEnabled: false }; diff --git a/x-pack/plugins/alerts/server/invalidate_pending_api_keys/task.ts b/x-pack/plugins/alerts/server/invalidate_pending_api_keys/task.ts index 119c3b697fd2e..91c3f5954d6d0 100644 --- a/x-pack/plugins/alerts/server/invalidate_pending_api_keys/task.ts +++ b/x-pack/plugins/alerts/server/invalidate_pending_api_keys/task.ts @@ -12,7 +12,7 @@ import { SavedObjectsClientContract, } from 'kibana/server'; import { EncryptedSavedObjectsClient } from '../../../encrypted_saved_objects/server'; -import { InvalidateAPIKeyParams, SecurityPluginSetup } from '../../../security/server'; +import { InvalidateAPIKeyParams, SecurityPluginStart } from '../../../security/server'; import { RunContext, TaskManagerSetupContract, @@ -29,12 +29,12 @@ export const TASK_ID = `Alerts-${TASK_TYPE}`; const invalidateAPIKey = async ( params: InvalidateAPIKeyParams, - securityPluginSetup?: SecurityPluginSetup + securityPluginStart?: SecurityPluginStart ): Promise => { - if (!securityPluginSetup) { + if (!securityPluginStart) { return { apiKeysEnabled: false }; } - const invalidateAPIKeyResult = await securityPluginSetup.authc.invalidateAPIKeyAsInternalUser( + const invalidateAPIKeyResult = await securityPluginStart.authc.apiKeys.invalidateAsInternalUser( params ); // Null when Elasticsearch security is disabled @@ -51,16 +51,9 @@ export function initializeApiKeyInvalidator( logger: Logger, coreStartServices: Promise<[CoreStart, AlertingPluginsStart, unknown]>, taskManager: TaskManagerSetupContract, - config: Promise, - securityPluginSetup?: SecurityPluginSetup + config: Promise ) { - registerApiKeyInvalitorTaskDefinition( - logger, - coreStartServices, - taskManager, - config, - securityPluginSetup - ); + registerApiKeyInvalidatorTaskDefinition(logger, coreStartServices, taskManager, config); } export async function scheduleApiKeyInvalidatorTask( @@ -84,17 +77,16 @@ export async function scheduleApiKeyInvalidatorTask( } } -function registerApiKeyInvalitorTaskDefinition( +function registerApiKeyInvalidatorTaskDefinition( logger: Logger, coreStartServices: Promise<[CoreStart, AlertingPluginsStart, unknown]>, taskManager: TaskManagerSetupContract, - config: Promise, - securityPluginSetup?: SecurityPluginSetup + config: Promise ) { taskManager.registerTaskDefinitions({ [TASK_TYPE]: { title: 'Invalidate alert API Keys', - createTaskRunner: taskRunner(logger, coreStartServices, config, securityPluginSetup), + createTaskRunner: taskRunner(logger, coreStartServices, config), }, }); } @@ -120,8 +112,7 @@ function getFakeKibanaRequest(basePath: string) { function taskRunner( logger: Logger, coreStartServices: Promise<[CoreStart, AlertingPluginsStart, unknown]>, - config: Promise, - securityPluginSetup?: SecurityPluginSetup + config: Promise ) { return ({ taskInstance }: RunContext) => { const { state } = taskInstance; @@ -130,7 +121,10 @@ function taskRunner( let totalInvalidated = 0; const configResult = await config; try { - const [{ savedObjects, http }, { encryptedSavedObjects }] = await coreStartServices; + const [ + { savedObjects, http }, + { encryptedSavedObjects, security }, + ] = await coreStartServices; const savedObjectsClient = savedObjects.getScopedClient( getFakeKibanaRequest(http.basePath.serverBasePath), { @@ -160,7 +154,7 @@ function taskRunner( savedObjectsClient, apiKeysToInvalidate, encryptedSavedObjectsClient, - securityPluginSetup + security ); hasApiKeysPendingInvalidation = apiKeysToInvalidate.total > PAGE_SIZE; @@ -197,7 +191,7 @@ async function invalidateApiKeys( savedObjectsClient: SavedObjectsClientContract, apiKeysToInvalidate: SavedObjectsFindResponse, encryptedSavedObjectsClient: EncryptedSavedObjectsClient, - securityPluginSetup?: SecurityPluginSetup + securityPluginStart?: SecurityPluginStart ) { let totalInvalidated = 0; await Promise.all( @@ -207,7 +201,7 @@ async function invalidateApiKeys( apiKeyObj.id ); const apiKeyId = decryptedApiKey.attributes.apiKeyId; - const response = await invalidateAPIKey({ id: apiKeyId }, securityPluginSetup); + const response = await invalidateAPIKey({ id: apiKeyId }, securityPluginStart); if (response.apiKeysEnabled === true && response.result.error_count > 0) { logger.error(`Failed to invalidate API Key [id="${apiKeyObj.attributes.apiKeyId}"]`); } else { diff --git a/x-pack/plugins/alerts/server/plugin.ts b/x-pack/plugins/alerts/server/plugin.ts index bafb89c64076b..e526c65b90102 100644 --- a/x-pack/plugins/alerts/server/plugin.ts +++ b/x-pack/plugins/alerts/server/plugin.ts @@ -8,7 +8,7 @@ import { first, map } from 'rxjs/operators'; import { Observable } from 'rxjs'; import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; import { combineLatest } from 'rxjs'; -import { SecurityPluginSetup } from '../../security/server'; +import { SecurityPluginSetup, SecurityPluginStart } from '../../security/server'; import { EncryptedSavedObjectsPluginSetup, EncryptedSavedObjectsPluginStart, @@ -115,6 +115,7 @@ export interface AlertingPluginsStart { features: FeaturesPluginStart; eventLog: IEventLogClientService; spaces?: SpacesPluginStart; + security?: SecurityPluginStart; } export class AlertingPlugin { @@ -203,8 +204,7 @@ export class AlertingPlugin { this.logger, core.getStartServices(), plugins.taskManager, - this.config, - this.security + this.config ); core.getStartServices().then(async ([, startPlugins]) => { @@ -279,6 +279,7 @@ export class AlertingPlugin { logger, taskManager: plugins.taskManager, securityPluginSetup: security, + securityPluginStart: plugins.security, encryptedSavedObjectsClient, spaceIdToNamespace, getSpaceId(request: KibanaRequest) { diff --git a/x-pack/plugins/apm/common/agent_configuration/setting_definitions/general_settings.ts b/x-pack/plugins/apm/common/agent_configuration/setting_definitions/general_settings.ts index 43b3748231290..e978b6d55251b 100644 --- a/x-pack/plugins/apm/common/agent_configuration/setting_definitions/general_settings.ts +++ b/x-pack/plugins/apm/common/agent_configuration/setting_definitions/general_settings.ts @@ -110,7 +110,7 @@ export const generalSettings: RawSettingDefinition[] = [ { text: 'critical', value: 'critical' }, { text: 'off', value: 'off' }, ], - includeAgents: ['dotnet', 'ruby', 'java', 'python'], + includeAgents: ['dotnet', 'ruby', 'java', 'python', 'nodejs'], }, // Recording @@ -235,7 +235,7 @@ export const generalSettings: RawSettingDefinition[] = [ 'Sometimes it is necessary to sanitize, i.e., remove, sensitive data sent to Elastic APM. This config accepts a list of wildcard patterns of field names which should be sanitized. These apply to HTTP headers (including cookies) and `application/x-www-form-urlencoded` data (POST form fields). The query string and the captured request body (such as `application/json` data) will not get sanitized.', } ), - includeAgents: ['java', 'python'], + includeAgents: ['java', 'python', 'go'], }, // Ignore transactions based on URLs diff --git a/x-pack/plugins/apm/common/agent_configuration/setting_definitions/index.test.ts b/x-pack/plugins/apm/common/agent_configuration/setting_definitions/index.test.ts index c9637f20a51bc..abe353ab8f3a3 100644 --- a/x-pack/plugins/apm/common/agent_configuration/setting_definitions/index.test.ts +++ b/x-pack/plugins/apm/common/agent_configuration/setting_definitions/index.test.ts @@ -46,6 +46,7 @@ describe('filterByAgent', () => { 'capture_body', 'capture_headers', 'recording', + 'sanitize_field_names', 'span_frames_min_duration', 'stack_trace_limit', 'transaction_max_spans', @@ -100,6 +101,7 @@ describe('filterByAgent', () => { it('nodejs', () => { expect(getSettingKeysForAgent('nodejs')).toEqual([ 'capture_body', + 'log_level', 'transaction_max_spans', 'transaction_sample_rate', ]); diff --git a/x-pack/plugins/data_enhanced/server/plugin.ts b/x-pack/plugins/data_enhanced/server/plugin.ts index 956568fbe7632..d0757ca5111b6 100644 --- a/x-pack/plugins/data_enhanced/server/plugin.ts +++ b/x-pack/plugins/data_enhanced/server/plugin.ts @@ -28,6 +28,7 @@ interface SetupDependencies { export class EnhancedDataServerPlugin implements Plugin { private readonly logger: Logger; + private sessionService!: BackgroundSessionService; constructor(private initializerContext: PluginInitializerContext) { this.logger = initializerContext.logger.get('data_enhanced'); @@ -53,10 +54,12 @@ export class EnhancedDataServerPlugin implements Plugin new Promise((resolve) => setImmediate(resolve)); describe('BackgroundSessionService', () => { let savedObjectsClient: jest.Mocked; let service: BackgroundSessionService; + const MOCK_SESSION_ID = 'session-id-mock'; + const MOCK_ASYNC_ID = '123456'; + const MOCK_KEY_HASH = '608de49a4600dbb5b173492759792e4a'; + + const createMockInternalSavedObjectClient = ( + findSpy?: jest.SpyInstance, + bulkUpdateSpy?: jest.SpyInstance + ) => { + Object.defineProperty(service, 'internalSavedObjectsClient', { + get: () => { + const find = + findSpy || + (() => { + return { + saved_objects: [ + { + attributes: { + sessionId: MOCK_SESSION_ID, + idMapping: { + 'another-key': 'another-async-id', + }, + }, + id: MOCK_SESSION_ID, + version: '1', + }, + ], + }; + }); + + const bulkUpdate = + bulkUpdateSpy || + (() => { + return { + saved_objects: [], + }; + }); + return { + find, + bulkUpdate, + }; + }, + }); + }; + + const createMockIdMapping = ( + mapValues: any[], + insertTime?: moment.Moment, + retryCount?: number + ): Map => { + const fakeMap = new Map(); + fakeMap.set(MOCK_SESSION_ID, { + ids: new Map(mapValues), + insertTime: insertTime || moment(), + retryCount: retryCount || 0, + }); + return fakeMap; + }; + const sessionId = 'd7170a35-7e2c-48d6-8dec-9a056721b489'; const mockSavedObject: SavedObject = { id: 'd7170a35-7e2c-48d6-8dec-9a056721b489', @@ -30,9 +99,14 @@ describe('BackgroundSessionService', () => { references: [], }; - beforeEach(() => { + beforeEach(async () => { savedObjectsClient = savedObjectsClientMock.create(); - service = new BackgroundSessionService(); + const mockLogger: any = { + debug: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }; + service = new BackgroundSessionService(mockLogger); }); it('search throws if `name` is not provided', () => { @@ -199,6 +273,13 @@ describe('BackgroundSessionService', () => { const created = new Date().toISOString(); const expires = new Date().toISOString(); + const mockIdMapping = createMockIdMapping([]); + const setSpy = jest.fn(); + mockIdMapping.set = setSpy; + Object.defineProperty(service, 'sessionSearchMap', { + get: () => mockIdMapping, + }); + await service.trackId( searchRequest, searchId, @@ -223,12 +304,17 @@ describe('BackgroundSessionService', () => { initialState: {}, restoreState: {}, status: BackgroundSessionStatus.IN_PROGRESS, - idMapping: { [requestHash]: searchId }, + idMapping: {}, appId, urlGeneratorId, + sessionId, }, { id: sessionId } ); + + const [setSessionId, setParams] = setSpy.mock.calls[0]; + expect(setParams.ids.get(requestHash)).toBe(searchId); + expect(setSessionId).toBe(sessionId); }); it('updates saved object when `isStored` is `true`', async () => { @@ -309,4 +395,204 @@ describe('BackgroundSessionService', () => { expect(id).toBe(searchId); }); }); + + describe('Monitor', () => { + beforeEach(async () => { + jest.useFakeTimers(); + const config$ = new BehaviorSubject({ + search: { + sendToBackground: { + enabled: true, + }, + }, + }); + await service.start(coreMock.createStart(), config$); + await flushPromises(); + }); + + afterEach(() => { + jest.useRealTimers(); + service.stop(); + }); + + it('schedules the next iteration', async () => { + const findSpy = jest.fn().mockResolvedValue({ saved_objects: [] }); + createMockInternalSavedObjectClient(findSpy); + + const mockIdMapping = createMockIdMapping([[MOCK_KEY_HASH, MOCK_ASYNC_ID]], moment()); + + Object.defineProperty(service, 'sessionSearchMap', { + get: () => mockIdMapping, + }); + + jest.advanceTimersByTime(INMEM_TRACKING_INTERVAL); + expect(findSpy).toHaveBeenCalledTimes(1); + await flushPromises(); + + jest.advanceTimersByTime(INMEM_TRACKING_INTERVAL); + expect(findSpy).toHaveBeenCalledTimes(2); + }); + + it('should delete expired IDs', async () => { + const findSpy = jest.fn().mockResolvedValueOnce({ saved_objects: [] }); + createMockInternalSavedObjectClient(findSpy); + + const mockIdMapping = createMockIdMapping( + [[MOCK_KEY_HASH, MOCK_ASYNC_ID]], + moment().subtract(2, 'm') + ); + + const deleteSpy = jest.spyOn(mockIdMapping, 'delete'); + Object.defineProperty(service, 'sessionSearchMap', { + get: () => mockIdMapping, + }); + + // Get setInterval to fire + jest.advanceTimersByTime(INMEM_TRACKING_INTERVAL); + + expect(findSpy).not.toHaveBeenCalled(); + expect(deleteSpy).toHaveBeenCalledTimes(1); + }); + + it('should delete IDs that passed max retries', async () => { + const findSpy = jest.fn().mockResolvedValueOnce({ saved_objects: [] }); + createMockInternalSavedObjectClient(findSpy); + + const mockIdMapping = createMockIdMapping( + [[MOCK_KEY_HASH, MOCK_ASYNC_ID]], + moment(), + MAX_UPDATE_RETRIES + ); + + const deleteSpy = jest.spyOn(mockIdMapping, 'delete'); + Object.defineProperty(service, 'sessionSearchMap', { + get: () => mockIdMapping, + }); + + // Get setInterval to fire + jest.advanceTimersByTime(INMEM_TRACKING_INTERVAL); + + expect(findSpy).not.toHaveBeenCalled(); + expect(deleteSpy).toHaveBeenCalledTimes(1); + }); + + it('should not fetch when no IDs are mapped', async () => { + const findSpy = jest.fn().mockResolvedValueOnce({ saved_objects: [] }); + createMockInternalSavedObjectClient(findSpy); + + jest.advanceTimersByTime(INMEM_TRACKING_INTERVAL); + expect(findSpy).not.toHaveBeenCalled(); + }); + + it('should try to fetch saved objects if some ids are mapped', async () => { + const mockIdMapping = createMockIdMapping([[MOCK_KEY_HASH, MOCK_ASYNC_ID]]); + Object.defineProperty(service, 'sessionSearchMap', { + get: () => mockIdMapping, + }); + + const findSpy = jest.fn().mockResolvedValueOnce({ saved_objects: [] }); + const bulkUpdateSpy = jest.fn().mockResolvedValueOnce({ saved_objects: [] }); + createMockInternalSavedObjectClient(findSpy, bulkUpdateSpy); + + jest.advanceTimersByTime(INMEM_TRACKING_INTERVAL); + expect(findSpy).toHaveBeenCalledTimes(1); + expect(bulkUpdateSpy).not.toHaveBeenCalled(); + }); + + it('should update saved objects if they are found, and delete session on success', async () => { + const mockIdMapping = createMockIdMapping([[MOCK_KEY_HASH, MOCK_ASYNC_ID]], undefined, 1); + const mockMapDeleteSpy = jest.fn(); + const mockSessionDeleteSpy = jest.fn(); + mockIdMapping.delete = mockMapDeleteSpy; + mockIdMapping.get(MOCK_SESSION_ID)!.ids.delete = mockSessionDeleteSpy; + Object.defineProperty(service, 'sessionSearchMap', { + get: () => mockIdMapping, + }); + + const findSpy = jest.fn().mockResolvedValueOnce({ + saved_objects: [ + { + id: MOCK_SESSION_ID, + attributes: { + idMapping: { + b: 'c', + }, + }, + }, + ], + }); + const bulkUpdateSpy = jest.fn().mockResolvedValueOnce({ + saved_objects: [ + { + id: MOCK_SESSION_ID, + attributes: { + idMapping: { + b: 'c', + [MOCK_KEY_HASH]: MOCK_ASYNC_ID, + }, + }, + }, + ], + }); + createMockInternalSavedObjectClient(findSpy, bulkUpdateSpy); + + jest.advanceTimersByTime(INMEM_TRACKING_INTERVAL); + + // Release timers to call check after test actions are done. + jest.useRealTimers(); + await new Promise((r) => setTimeout(r, 15)); + + expect(findSpy).toHaveBeenCalledTimes(1); + expect(bulkUpdateSpy).toHaveBeenCalledTimes(1); + expect(mockSessionDeleteSpy).toHaveBeenCalledTimes(2); + expect(mockSessionDeleteSpy).toBeCalledWith('b'); + expect(mockSessionDeleteSpy).toBeCalledWith(MOCK_KEY_HASH); + expect(mockMapDeleteSpy).toBeCalledTimes(1); + }); + + it('should update saved objects if they are found, and increase retryCount on error', async () => { + const mockIdMapping = createMockIdMapping([[MOCK_KEY_HASH, MOCK_ASYNC_ID]]); + const mockMapDeleteSpy = jest.fn(); + const mockSessionDeleteSpy = jest.fn(); + mockIdMapping.delete = mockMapDeleteSpy; + mockIdMapping.get(MOCK_SESSION_ID)!.ids.delete = mockSessionDeleteSpy; + Object.defineProperty(service, 'sessionSearchMap', { + get: () => mockIdMapping, + }); + + const findSpy = jest.fn().mockResolvedValueOnce({ + saved_objects: [ + { + id: MOCK_SESSION_ID, + attributes: { + idMapping: { + b: 'c', + }, + }, + }, + ], + }); + const bulkUpdateSpy = jest.fn().mockResolvedValueOnce({ + saved_objects: [ + { + id: MOCK_SESSION_ID, + error: 'not ok', + }, + ], + }); + createMockInternalSavedObjectClient(findSpy, bulkUpdateSpy); + + jest.advanceTimersByTime(INMEM_TRACKING_INTERVAL); + + // Release timers to call check after test actions are done. + jest.useRealTimers(); + await new Promise((r) => setTimeout(r, 15)); + + expect(findSpy).toHaveBeenCalledTimes(1); + expect(bulkUpdateSpy).toHaveBeenCalledTimes(1); + expect(mockSessionDeleteSpy).not.toHaveBeenCalled(); + expect(mockMapDeleteSpy).not.toHaveBeenCalled(); + expect(mockIdMapping.get(MOCK_SESSION_ID)!.retryCount).toBe(1); + }); + }); }); diff --git a/x-pack/plugins/data_enhanced/server/search/session/session_service.ts b/x-pack/plugins/data_enhanced/server/search/session/session_service.ts index 65a9e0901d738..96d66157c48ec 100644 --- a/x-pack/plugins/data_enhanced/server/search/session/session_service.ts +++ b/x-pack/plugins/data_enhanced/server/search/session/session_service.ts @@ -4,9 +4,17 @@ * you may not use this file except in compliance with the Elastic License. */ -import { CoreStart, KibanaRequest, SavedObjectsClientContract } from 'kibana/server'; +import moment, { Moment } from 'moment'; import { from, Observable } from 'rxjs'; -import { switchMap } from 'rxjs/operators'; +import { first, switchMap } from 'rxjs/operators'; +import { + CoreStart, + KibanaRequest, + SavedObjectsClient, + SavedObjectsClientContract, + Logger, + SavedObject, +} from '../../../../../../src/core/server'; import { IKibanaSearchRequest, IKibanaSearchResponse, @@ -25,21 +33,154 @@ import { } from '../../../common'; import { BACKGROUND_SESSION_TYPE } from '../../saved_objects'; import { createRequestHash } from './utils'; +import { ConfigSchema } from '../../../config'; +const INMEM_MAX_SESSIONS = 10000; const DEFAULT_EXPIRATION = 7 * 24 * 60 * 60 * 1000; +export const INMEM_TRACKING_INTERVAL = 10 * 1000; +export const INMEM_TRACKING_TIMEOUT_SEC = 60; +export const MAX_UPDATE_RETRIES = 3; export interface BackgroundSessionDependencies { savedObjectsClient: SavedObjectsClientContract; } +export interface SessionInfo { + insertTime: Moment; + retryCount: number; + ids: Map; +} + export class BackgroundSessionService implements ISessionService { /** * Map of sessionId to { [requestHash]: searchId } * @private */ - private sessionSearchMap = new Map>(); + private sessionSearchMap = new Map(); + private internalSavedObjectsClient!: SavedObjectsClientContract; + private monitorTimer!: NodeJS.Timeout; + + constructor(private readonly logger: Logger) {} + + public async start(core: CoreStart, config$: Observable) { + return this.setupMonitoring(core, config$); + } + + public stop() { + this.sessionSearchMap.clear(); + clearTimeout(this.monitorTimer); + } + + private setupMonitoring = async (core: CoreStart, config$: Observable) => { + const config = await config$.pipe(first()).toPromise(); + if (config.search.sendToBackground.enabled) { + this.logger.debug(`setupMonitoring | Enabling monitoring`); + const internalRepo = core.savedObjects.createInternalRepository([BACKGROUND_SESSION_TYPE]); + this.internalSavedObjectsClient = new SavedObjectsClient(internalRepo); + this.monitorMappedIds(); + } + }; + + /** + * Gets all {@link SessionSavedObjectAttributes | Background Searches} that + * currently being tracked by the service. + * + * @remarks + * Uses `internalSavedObjectsClient` as this is called asynchronously, not within the + * context of a user's session. + */ + private async getAllMappedSavedObjects() { + const activeMappingIds = Array.from(this.sessionSearchMap.keys()) + .map((sessionId) => `"${sessionId}"`) + .join(' | '); + const res = await this.internalSavedObjectsClient.find({ + perPage: INMEM_MAX_SESSIONS, // If there are more sessions in memory, they will be synced when some items are cleared out. + type: BACKGROUND_SESSION_TYPE, + search: activeMappingIds, + searchFields: ['sessionId'], + namespaces: ['*'], + }); + this.logger.debug(`getAllMappedSavedObjects | Got ${res.saved_objects.length} items`); + return res.saved_objects; + } - constructor() {} + private clearSessions = () => { + const curTime = moment(); + + this.sessionSearchMap.forEach((sessionInfo, sessionId) => { + if ( + moment.duration(curTime.diff(sessionInfo.insertTime)).asSeconds() > + INMEM_TRACKING_TIMEOUT_SEC + ) { + this.logger.debug(`clearSessions | Deleting expired session ${sessionId}`); + this.sessionSearchMap.delete(sessionId); + } else if (sessionInfo.retryCount >= MAX_UPDATE_RETRIES) { + this.logger.warn(`clearSessions | Deleting failed session ${sessionId}`); + this.sessionSearchMap.delete(sessionId); + } + }); + }; + + private async monitorMappedIds() { + this.monitorTimer = setTimeout(async () => { + try { + this.clearSessions(); + + if (!this.sessionSearchMap.size) return; + this.logger.debug(`monitorMappedIds | Map contains ${this.sessionSearchMap.size} items`); + + const savedSessions = await this.getAllMappedSavedObjects(); + const updatedSessions = await this.updateAllSavedObjects(savedSessions); + + updatedSessions.forEach((updatedSavedObject) => { + const sessionInfo = this.sessionSearchMap.get(updatedSavedObject.id)!; + if (updatedSavedObject.error) { + // Retry next time + sessionInfo.retryCount++; + } else if (updatedSavedObject.attributes.idMapping) { + // Delete the ids that we just saved, avoiding a potential new ids being lost. + Object.keys(updatedSavedObject.attributes.idMapping).forEach((key) => { + sessionInfo.ids.delete(key); + }); + // If the session object is empty, delete it as well + if (!sessionInfo.ids.entries.length) { + this.sessionSearchMap.delete(updatedSavedObject.id); + } else { + sessionInfo.retryCount = 0; + } + } + }); + } catch (e) { + this.logger.error(`monitorMappedIds | Error while updating sessions. ${e}`); + } finally { + this.monitorMappedIds(); + } + }, INMEM_TRACKING_INTERVAL); + } + + private async updateAllSavedObjects( + activeMappingObjects: Array> + ) { + if (!activeMappingObjects.length) return []; + + this.logger.debug(`updateAllSavedObjects | Updating ${activeMappingObjects.length} items`); + const updatedSessions = activeMappingObjects + .filter((so) => !so.error) + .map((sessionSavedObject) => { + const sessionInfo = this.sessionSearchMap.get(sessionSavedObject.id); + const idMapping = sessionInfo ? Object.fromEntries(sessionInfo.ids.entries()) : {}; + sessionSavedObject.attributes.idMapping = { + ...sessionSavedObject.attributes.idMapping, + ...idMapping, + }; + return sessionSavedObject; + }); + + const updateResults = await this.internalSavedObjectsClient.bulkUpdate( + updatedSessions + ); + return updateResults.saved_objects; + } public search( strategy: ISearchStrategy, @@ -85,9 +226,8 @@ export class BackgroundSessionService implements ISessionService { if (!appId) throw new Error('AppId is required'); if (!urlGeneratorId) throw new Error('UrlGeneratorId is required'); - // Get the mapping of request hash/search ID for this session - const searchMap = this.sessionSearchMap.get(sessionId) ?? new Map(); - const idMapping = Object.fromEntries(searchMap.entries()); + this.logger.debug(`save | ${sessionId}`); + const attributes = { name, created, @@ -95,9 +235,10 @@ export class BackgroundSessionService implements ISessionService { status, initialState, restoreState, - idMapping, + idMapping: {}, urlGeneratorId, appId, + sessionId, }; const session = await savedObjectsClient.create( BACKGROUND_SESSION_TYPE, @@ -105,14 +246,12 @@ export class BackgroundSessionService implements ISessionService { { id: sessionId } ); - // Clear out the entries for this session ID so they don't get saved next time - this.sessionSearchMap.delete(sessionId); - return session; }; // TODO: Throw an error if this session doesn't belong to this user public get = (sessionId: string, { savedObjectsClient }: BackgroundSessionDependencies) => { + this.logger.debug(`get | ${sessionId}`); return savedObjectsClient.get( BACKGROUND_SESSION_TYPE, sessionId @@ -136,6 +275,7 @@ export class BackgroundSessionService implements ISessionService { attributes: Partial, { savedObjectsClient }: BackgroundSessionDependencies ) => { + this.logger.debug(`update | ${sessionId}`); return savedObjectsClient.update( BACKGROUND_SESSION_TYPE, sessionId, @@ -160,6 +300,7 @@ export class BackgroundSessionService implements ISessionService { deps: BackgroundSessionDependencies ) => { if (!sessionId || !searchId) return; + this.logger.debug(`trackId | ${sessionId} | ${searchId}`); const requestHash = createRequestHash(searchRequest.params); // If there is already a saved object for this session, update it to include this request/ID. @@ -168,8 +309,12 @@ export class BackgroundSessionService implements ISessionService { const attributes = { idMapping: { [requestHash]: searchId } }; await this.update(sessionId, attributes, deps); } else { - const map = this.sessionSearchMap.get(sessionId) ?? new Map(); - map.set(requestHash, searchId); + const map = this.sessionSearchMap.get(sessionId) ?? { + insertTime: moment(), + retryCount: 0, + ids: new Map(), + }; + map.ids.set(requestHash, searchId); this.sessionSearchMap.set(sessionId, map); } }; diff --git a/x-pack/plugins/data_enhanced/server/search/session/utils.ts b/x-pack/plugins/data_enhanced/server/search/session/utils.ts index 1c314c64f9be3..beaecc5a839d3 100644 --- a/x-pack/plugins/data_enhanced/server/search/session/utils.ts +++ b/x-pack/plugins/data_enhanced/server/search/session/utils.ts @@ -5,6 +5,7 @@ */ import { createHash } from 'crypto'; +import stringify from 'json-stable-stringify'; /** * Generate the hash for this request so that, in the future, this hash can be used to look up @@ -13,5 +14,5 @@ import { createHash } from 'crypto'; */ export function createRequestHash(keys: Record) { const { preference, ...params } = keys; - return createHash(`sha256`).update(JSON.stringify(params)).digest('hex'); + return createHash(`sha256`).update(stringify(params)).digest('hex'); } diff --git a/x-pack/plugins/fleet/common/services/agent_status.ts b/x-pack/plugins/fleet/common/services/agent_status.ts index cd990d70c3612..30b52bcb28748 100644 --- a/x-pack/plugins/fleet/common/services/agent_status.ts +++ b/x-pack/plugins/fleet/common/services/agent_status.ts @@ -62,6 +62,14 @@ export function buildKueryForOfflineAgents() { }s AND not (${buildKueryForErrorAgents()})`; } -export function buildKueryForUpdatingAgents() { +export function buildKueryForUpgradingAgents() { return `${AGENT_SAVED_OBJECT_TYPE}.upgrade_started_at:*`; } + +export function buildKueryForUpdatingAgents() { + return `(${buildKueryForUpgradingAgents()}) or (${buildKueryForEnrollingAgents()}) or (${buildKueryForUnenrollingAgents()})`; +} + +export function buildKueryForInactiveAgents() { + return `${AGENT_SAVED_OBJECT_TYPE}.active:false`; +} diff --git a/x-pack/plugins/fleet/common/types/models/agent.ts b/x-pack/plugins/fleet/common/types/models/agent.ts index 872b389d248a3..59fab14f90e6e 100644 --- a/x-pack/plugins/fleet/common/types/models/agent.ts +++ b/x-pack/plugins/fleet/common/types/models/agent.ts @@ -22,6 +22,8 @@ export type AgentStatus = | 'updating' | 'degraded'; +export type SimplifiedAgentStatus = 'healthy' | 'unhealthy' | 'updating' | 'offline' | 'inactive'; + export type AgentActionType = | 'POLICY_CHANGE' | 'UNENROLL' diff --git a/x-pack/plugins/fleet/common/types/models/epm.ts b/x-pack/plugins/fleet/common/types/models/epm.ts index 66a2a58a25ac5..96868fa8cfc3b 100644 --- a/x-pack/plugins/fleet/common/types/models/epm.ts +++ b/x-pack/plugins/fleet/common/types/models/epm.ts @@ -222,6 +222,7 @@ export interface RegistryElasticsearch { 'index_template.mappings'?: object; } +export type RegistryVarType = 'integer' | 'bool' | 'password' | 'text' | 'yaml'; // EPR types this as `[]map[string]interface{}` // which means the official/possible type is Record // but we effectively only see this shape @@ -229,7 +230,7 @@ export interface RegistryVarsEntry { name: string; title?: string; description?: string; - type: string; + type: RegistryVarType; required?: boolean; show_user?: boolean; multi?: boolean; 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 da7d126c4ecd3..236fc586bf528 100644 --- a/x-pack/plugins/fleet/common/types/rest_spec/agent.ts +++ b/x-pack/plugins/fleet/common/types/rest_spec/agent.ts @@ -206,6 +206,7 @@ export interface UpdateAgentRequest { export interface GetAgentStatusRequest { query: { + kuery?: string; policyId?: string; }; } diff --git a/x-pack/plugins/fleet/public/applications/fleet/components/home_integration/tutorial_module_notice.tsx b/x-pack/plugins/fleet/public/applications/fleet/components/home_integration/tutorial_module_notice.tsx index 3430a4eb5b258..6cd701da61e26 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/components/home_integration/tutorial_module_notice.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/components/home_integration/tutorial_module_notice.tsx @@ -8,6 +8,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { EuiText, EuiLink, EuiSpacer } from '@elastic/eui'; import { TutorialModuleNoticeComponent } from 'src/plugins/home/public'; import { useGetPackages, useLink, useCapabilities } from '../../hooks'; +import { pkgKeyFromPackageInfo } from '../../services/pkg_key_from_package_info'; const TutorialModuleNotice: TutorialModuleNoticeComponent = memo(({ moduleName }) => { const { getHref } = useLink(); @@ -41,7 +42,7 @@ const TutorialModuleNotice: TutorialModuleNoticeComponent = memo(({ moduleName } availableAsIntegrationLink: ( void; + onChange: (newValue: string, submit?: boolean) => void; placeholder?: string; } @@ -40,135 +28,73 @@ export const SearchBar: React.FunctionComponent = ({ onChange, placeholder, }) => { - const { suggestions } = useSuggestions(fieldPrefix, value); - - // TODO fix type when correctly typed in EUI - const onAutocompleteClick = (suggestion: any) => { - onChange( - [value.slice(0, suggestion.start), suggestion.value, value.slice(suggestion.end, -1)].join('') - ); - }; - // TODO fix type when correctly typed in EUI - const onChangeSearch = (e: any) => { - onChange(e.value); - }; - - return ( - { - return { - ...suggestion, - // For type - onClick: () => {}, - descriptionDisplay: 'wrap', - labelWidth: '40', - }; - })} - /> - ); -}; - -export function transformSuggestionType(type: string): { iconType: string; color: string } { - switch (type) { - case 'field': - return { iconType: 'kqlField', color: 'tint4' }; - case 'value': - return { iconType: 'kqlValue', color: 'tint0' }; - case 'conjunction': - return { iconType: 'kqlSelector', color: 'tint3' }; - case 'operator': - return { iconType: 'kqlOperand', color: 'tint1' }; - default: - return { iconType: 'kqlOther', color: 'tint1' }; - } -} - -function useSuggestions(fieldPrefix: string, search: string) { const { data } = useStartServices(); + const [indexPatternFields, setIndexPatternFields] = useState(); - const debouncedSearch = useDebounce(search, DEBOUNCE_SEARCH_MS); - const [suggestions, setSuggestions] = useState([]); + const isQueryValid = useMemo(() => { + if (!value || value === '') { + return true; + } - const fetchSuggestions = async () => { try { - const res = (await data.indexPatterns.getFieldsForWildcard({ - pattern: INDEX_NAME, - })) as IFieldType[]; - if (!data || !data.autocomplete) { - throw new Error('Missing data plugin'); - } - const query = debouncedSearch || ''; - // @ts-ignore - const esSuggestions = ( - await data.autocomplete.getQuerySuggestions({ - language: 'kuery', - indexPatterns: [ - { - title: INDEX_NAME, - fields: res, - }, - ], - boolFilter: [], - query, - selectionStart: query.length, - selectionEnd: query.length, - }) - ) - .filter((suggestion) => { - if (suggestion.type === 'conjunction') { - return true; - } - if (suggestion.type === 'value') { - return true; - } - if (suggestion.type === 'operator') { - return true; - } + esKuery.fromKueryExpression(value); + return true; + } catch (e) { + return false; + } + }, [value]); - if (fieldPrefix && suggestion.text.startsWith(fieldPrefix)) { + useEffect(() => { + const fetchFields = async () => { + try { + const _fields: IFieldType[] = await data.indexPatterns.getFieldsForWildcard({ + pattern: INDEX_NAME, + }); + const fields = (_fields || []).filter((field) => { + if (fieldPrefix && field.name.startsWith(fieldPrefix)) { for (const hiddenField of HIDDEN_FIELDS) { - if (suggestion.text.startsWith(hiddenField)) { + if (field.name.startsWith(hiddenField)) { return false; } } return true; } + }); + setIndexPatternFields(fields); + } catch (err) { + setIndexPatternFields(undefined); + } + }; + fetchFields(); + }, [data.indexPatterns, fieldPrefix]); - return false; - }) - .map((suggestion: any) => ({ - label: suggestion.text, - description: suggestion.description || '', - type: transformSuggestionType(suggestion.type), - start: suggestion.start, - end: suggestion.end, - value: suggestion.text, - })); - - setSuggestions(esSuggestions); - } catch (err) { - setSuggestions([]); - } - }; - - useEffect(() => { - fetchSuggestions(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [debouncedSearch]); - - return { - suggestions, - }; -} + return ( + { + onChange(newQuery.query as string); + }} + onSubmit={(newQuery) => { + onChange(newQuery.query as string, true); + }} + /> + ); +}; diff --git a/x-pack/plugins/fleet/public/applications/fleet/constants/page_paths.ts b/x-pack/plugins/fleet/public/applications/fleet/constants/page_paths.ts index 2fce7f8f5e825..5c2194a3e37cd 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/constants/page_paths.ts +++ b/x-pack/plugins/fleet/public/applications/fleet/constants/page_paths.ts @@ -18,6 +18,7 @@ export type StaticPage = export type DynamicPage = | 'integration_details' + | 'integration_policy_edit' | 'policy_details' | 'add_integration_from_policy' | 'add_integration_to_policy' @@ -41,6 +42,7 @@ export const PAGE_ROUTING_PATHS = { integrations_all: '/integrations', integrations_installed: '/integrations/installed', integration_details: '/integrations/detail/:pkgkey/:panel?', + integration_policy_edit: '/integrations/edit-integration/:packagePolicyId', policies: '/policies', policies_list: '/policies', policy_details: '/policies/:policyId/:tabId?', @@ -69,6 +71,8 @@ export const pagePathGetters: { integrations_installed: () => '/integrations/installed', integration_details: ({ pkgkey, panel }) => `/integrations/detail/${pkgkey}${panel ? `/${panel}` : ''}`, + integration_policy_edit: ({ packagePolicyId }) => + `/integrations/edit-integration/${packagePolicyId}`, policies: () => '/policies', policies_list: () => '/policies', policy_details: ({ policyId, tabId }) => `/policies/${policyId}${tabId ? `/${tabId}` : ''}`, diff --git a/x-pack/plugins/fleet/public/applications/fleet/hooks/use_breadcrumbs.tsx b/x-pack/plugins/fleet/public/applications/fleet/hooks/use_breadcrumbs.tsx index 40654645ecd3f..4feff29896459 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/hooks/use_breadcrumbs.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/hooks/use_breadcrumbs.tsx @@ -73,6 +73,20 @@ const breadcrumbGetters: { }, { text: pkgTitle }, ], + integration_policy_edit: ({ pkgTitle, pkgkey, policyName }) => [ + BASE_BREADCRUMB, + { + href: pagePathGetters.integrations(), + text: i18n.translate('xpack.fleet.breadcrumbs.integrationPageTitle', { + defaultMessage: 'Integration', + }), + }, + { + href: pagePathGetters.integration_details({ pkgkey, panel: 'policies' }), + text: pkgTitle, + }, + { text: policyName }, + ], policies: () => [ BASE_BREADCRUMB, { diff --git a/x-pack/plugins/fleet/public/applications/fleet/hooks/use_request/agents.ts b/x-pack/plugins/fleet/public/applications/fleet/hooks/use_request/agents.ts index 7bbf621c57894..b6a3ecfde78d6 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/hooks/use_request/agents.ts +++ b/x-pack/plugins/fleet/public/applications/fleet/hooks/use_request/agents.ts @@ -62,13 +62,10 @@ export function useGetAgents(query: GetAgentsRequest['query'], options?: Request }); } -export function sendGetAgentStatus( - query: GetAgentStatusRequest['query'], - options?: RequestOptions -) { - return sendRequest({ +export function sendGetAgents(query: GetAgentsRequest['query'], options?: RequestOptions) { + return sendRequest({ method: 'get', - path: agentRouteService.getStatusPath(), + path: agentRouteService.getListPath(), query, ...options, }); @@ -83,6 +80,18 @@ export function useGetAgentStatus(query: GetAgentStatusRequest['query'], options }); } +export function sendGetAgentStatus( + query: GetAgentStatusRequest['query'], + options?: RequestOptions +) { + return sendRequest({ + method: 'get', + path: agentRouteService.getStatusPath(), + query, + ...options, + }); +} + export function sendPutAgentReassign( agentId: string, body: PutAgentReassignRequest['body'], diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/layout.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/layout.tsx index 9188f0069b8bf..cac133acd4d2d 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/layout.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/layout.tsx @@ -38,7 +38,7 @@ export const CreatePackagePolicyPageLayout: React.FunctionComponent<{ 'data-test-subj': dataTestSubj, }) => { const pageTitle = useMemo(() => { - if ((from === 'package' || from === 'edit') && packageInfo) { + if ((from === 'package' || from === 'package-edit' || from === 'edit') && packageInfo) { return ( @@ -76,7 +76,7 @@ export const CreatePackagePolicyPageLayout: React.FunctionComponent<{ ); } - return from === 'edit' ? ( + return from === 'edit' || from === 'package-edit' ? (

{ - return from === 'edit' ? ( + return from === 'edit' || from === 'package-edit' ? ( { if (multi) { @@ -59,6 +67,18 @@ export const PackagePolicyInputVarField: React.FunctionComponent<{ /> ); } + if (type === 'bool') { + return ( + onChange(e.target.checked)} + onBlur={() => setIsDirty(true)} + /> + ); + } + return ( setIsDirty(true)} /> ); - }, [isInvalid, multi, onChange, type, value]); + }, [isInvalid, multi, onChange, type, value, fieldLabel]); + + // Boolean cannot be optional by default set to false + const isOptional = type !== 'bool' && !required; return ( { ? packageInfo && ( ) : agentPolicy && ( diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_define_package_policy.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_define_package_policy.tsx index f6533a06cea27..b7de9d0afe8f5 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_define_package_policy.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_define_package_policy.tsx @@ -20,6 +20,7 @@ import { AgentPolicy, PackageInfo, PackagePolicy, NewPackagePolicy } from '../.. import { packageToPackagePolicyInputs } from '../../../services'; import { Loading } from '../../../components'; import { PackagePolicyValidationResults } from './services'; +import { pkgKeyFromPackageInfo } from '../../../services/pkg_key_from_package_info'; export const StepDefinePackagePolicy: React.FunctionComponent<{ agentPolicy: AgentPolicy; @@ -34,8 +35,8 @@ export const StepDefinePackagePolicy: React.FunctionComponent<{ // Update package policy's package and agent policy info useEffect(() => { const pkg = packagePolicy.package; - const currentPkgKey = pkg ? `${pkg.name}-${pkg.version}` : ''; - const pkgKey = `${packageInfo.name}-${packageInfo.version}`; + const currentPkgKey = pkg ? pkgKeyFromPackageInfo(pkg) : ''; + const pkgKey = pkgKeyFromPackageInfo(packageInfo); // If package has changed, create shell package policy with input&stream values based on package info if (currentPkgKey !== pkgKey) { diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_select_package.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_select_package.tsx index 8c646323c312c..3bcafaecbf8d9 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_select_package.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_select_package.tsx @@ -16,6 +16,7 @@ import { sendGetPackageInfoByKey, } from '../../../hooks'; import { PackageIcon } from '../../../components/package_icon'; +import { pkgKeyFromPackageInfo } from '../../../services/pkg_key_from_package_info'; export const StepSelectPackage: React.FunctionComponent<{ agentPolicyId: string; @@ -32,7 +33,7 @@ export const StepSelectPackage: React.FunctionComponent<{ }) => { // Selected package state const [selectedPkgKey, setSelectedPkgKey] = useState( - packageInfo ? `${packageInfo.name}-${packageInfo.version}` : undefined + packageInfo ? pkgKeyFromPackageInfo(packageInfo) : undefined ); const [selectedPkgError, setSelectedPkgError] = useState(); @@ -92,7 +93,7 @@ export const StepSelectPackage: React.FunctionComponent<{ updatePackageInfo(undefined); } }; - if (!packageInfo || selectedPkgKey !== `${packageInfo.name}-${packageInfo.version}`) { + if (!packageInfo || selectedPkgKey !== pkgKeyFromPackageInfo(packageInfo)) { fetchPackageInfo(); } }, [selectedPkgKey, packageInfo, updatePackageInfo, setIsLoadingSecondStep]); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/types.ts b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/types.ts index c6e16c2cb4d97..7eb5d95c1ab05 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/types.ts +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/types.ts @@ -4,5 +4,5 @@ * you may not use this file except in compliance with the Elastic License. */ -export type CreatePackagePolicyFrom = 'package' | 'policy' | 'edit'; +export type CreatePackagePolicyFrom = 'package' | 'package-edit' | 'policy' | 'edit'; export type PackagePolicyFormState = 'VALID' | 'INVALID' | 'CONFIRM' | 'LOADING' | 'SUBMITTED'; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx index 8f798445b2362..26f99bd88a923 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import React, { useState, useEffect, useCallback, useMemo } from 'react'; +import React, { useState, useEffect, useCallback, useMemo, memo } from 'react'; import { useRouteMatch, useHistory } from 'react-router-dom'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -45,15 +45,24 @@ import { useUIExtension } from '../../../hooks/use_ui_extension'; import { ExtensionWrapper } from '../../../components/extension_wrapper'; import { GetOnePackagePolicyResponse } from '../../../../../../common/types/rest_spec'; import { PackagePolicyEditExtensionComponentProps } from '../../../types'; +import { pkgKeyFromPackageInfo } from '../../../services/pkg_key_from_package_info'; -export const EditPackagePolicyPage: React.FunctionComponent = () => { +export const EditPackagePolicyPage = memo(() => { + const { + params: { packagePolicyId }, + } = useRouteMatch<{ policyId: string; packagePolicyId: string }>(); + + return ; +}); + +export const EditPackagePolicyForm = memo<{ + packagePolicyId: string; + from?: CreatePackagePolicyFrom; +}>(({ packagePolicyId, from = 'edit' }) => { const { notifications } = useStartServices(); const { agents: { enabled: isFleetEnabled }, } = useConfig(); - const { - params: { policyId, packagePolicyId }, - } = useRouteMatch<{ policyId: string; packagePolicyId: string }>(); const history = useHistory(); const { getHref, getPath } = useLink(); @@ -76,16 +85,31 @@ export const EditPackagePolicyPage: React.FunctionComponent = () => { GetOnePackagePolicyResponse['item'] >(); + const policyId = agentPolicy?.id ?? ''; + // Retrieve agent policy, package, and package policy info useEffect(() => { const getData = async () => { setIsLoadingData(true); setLoadingError(undefined); try { - const [{ data: agentPolicyData }, { data: packagePolicyData }] = await Promise.all([ - sendGetOneAgentPolicy(policyId), - sendGetOnePackagePolicy(packagePolicyId), - ]); + const { + data: packagePolicyData, + error: packagePolicyError, + } = await sendGetOnePackagePolicy(packagePolicyId); + + if (packagePolicyError) { + throw packagePolicyError; + } + + const { data: agentPolicyData, error: agentPolicyError } = await sendGetOneAgentPolicy( + packagePolicyData!.item.policy_id + ); + + if (agentPolicyError) { + throw agentPolicyError; + } + if (agentPolicyData?.item) { setAgentPolicy(agentPolicyData.item); } @@ -108,7 +132,8 @@ export const EditPackagePolicyPage: React.FunctionComponent = () => { const newPackagePolicy = { ...restOfPackagePolicy, inputs: inputs.map((input) => { - const { streams, ...restOfInput } = input; + // Remove `compiled_input` from all input info, we assign this after saving + const { streams, compiled_input: compiledInput, ...restOfInput } = input; return { ...restOfInput, streams: streams.map((stream) => { @@ -122,7 +147,7 @@ export const EditPackagePolicyPage: React.FunctionComponent = () => { setPackagePolicy(newPackagePolicy); if (packagePolicyData.item.package) { const { data: packageData } = await sendGetPackageInfoByKey( - `${packagePolicyData.item.package.name}-${packagePolicyData.item.package.version}` + pkgKeyFromPackageInfo(packagePolicyData.item.package) ); if (packageData?.response) { setPackageInfo(packageData.response); @@ -149,7 +174,7 @@ export const EditPackagePolicyPage: React.FunctionComponent = () => { } }; - if (isFleetEnabled) { + if (isFleetEnabled && policyId) { getAgentCount(); } }, [policyId, isFleetEnabled]); @@ -213,8 +238,32 @@ export const EditPackagePolicyPage: React.FunctionComponent = () => { [updatePackagePolicy] ); - // Cancel url - const cancelUrl = getHref('policy_details', { policyId }); + // Cancel url + Success redirect Path: + // if `from === 'edit'` then it links back to Policy Details + // if `from === 'package-edit'` then it links back to the Integration Policy List + const cancelUrl = useMemo((): string => { + if (packageInfo && policyId) { + return from === 'package-edit' + ? getHref('integration_details', { + pkgkey: pkgKeyFromPackageInfo(packageInfo!), + panel: 'policies', + }) + : getHref('policy_details', { policyId }); + } + return '/'; + }, [from, getHref, packageInfo, policyId]); + + const successRedirectPath = useMemo(() => { + if (packageInfo && policyId) { + return from === 'package-edit' + ? getPath('integration_details', { + pkgkey: pkgKeyFromPackageInfo(packageInfo!), + panel: 'policies', + }) + : getPath('policy_details', { policyId }); + } + return '/'; + }, [from, getPath, packageInfo, policyId]); // Save package policy const [formState, setFormState] = useState('INVALID'); @@ -236,7 +285,7 @@ export const EditPackagePolicyPage: React.FunctionComponent = () => { } const { error } = await savePackagePolicy(); if (!error) { - history.push(getPath('policy_details', { policyId })); + history.push(successRedirectPath); notifications.toasts.addSuccess({ title: i18n.translate('xpack.fleet.editPackagePolicy.updatedNotificationTitle', { defaultMessage: `Successfully updated '{packagePolicyName}'`, @@ -286,7 +335,7 @@ export const EditPackagePolicyPage: React.FunctionComponent = () => { }; const layoutProps = { - from: 'edit' as CreatePackagePolicyFrom, + from, cancelUrl, agentPolicy, packageInfo, @@ -362,13 +411,21 @@ export const EditPackagePolicyPage: React.FunctionComponent = () => { error={ loadingError || i18n.translate('xpack.fleet.editPackagePolicy.errorLoadingDataMessage', { - defaultMessage: 'There was an error loading this intergration information', + defaultMessage: 'There was an error loading this integration information', }) } /> ) : ( <> - + {from === 'package' || from === 'package-edit' ? ( + + ) : ( + + )} {formState === 'CONFIRM' && ( { )} ); -}; +}); -const Breadcrumb: React.FunctionComponent<{ policyName: string; policyId: string }> = ({ +const PoliciesBreadcrumb: React.FunctionComponent<{ policyName: string; policyId: string }> = ({ policyName, policyId, }) => { useBreadcrumbs('edit_integration', { policyName, policyId }); return null; }; + +const IntegrationsBreadcrumb = memo<{ + pkgTitle: string; + policyName: string; + pkgkey: string; +}>(({ pkgTitle, policyName, pkgkey }) => { + useBreadcrumbs('integration_policy_edit', { policyName, pkgTitle, pkgkey }); + return null; +}); 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 new file mode 100644 index 0000000000000..baea6d364e586 --- /dev/null +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/search_and_filter_bar.tsx @@ -0,0 +1,212 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React, { useState } from 'react'; +import { + EuiFilterButton, + EuiFilterGroup, + EuiFilterSelectItem, + EuiFlexGroup, + EuiFlexItem, + EuiPopover, +} from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { AgentPolicy } from '../../../../types'; +import { SearchBar } from '../../../../components'; +import { AGENT_SAVED_OBJECT_TYPE } from '../../../../constants'; + +const statusFilters = [ + { + status: 'healthy', + label: i18n.translate('xpack.fleet.agentList.statusHealthyFilterText', { + defaultMessage: 'Healthy', + }), + }, + { + status: 'unhealthy', + label: i18n.translate('xpack.fleet.agentList.statusUnhealthyFilterText', { + defaultMessage: 'Unhealthy', + }), + }, + { + status: 'updating', + label: i18n.translate('xpack.fleet.agentList.statusUpdatingFilterText', { + defaultMessage: 'Updating', + }), + }, + { + status: 'offline', + label: i18n.translate('xpack.fleet.agentList.statusOfflineFilterText', { + defaultMessage: 'Offline', + }), + }, + { + status: 'inactive', + label: i18n.translate('xpack.fleet.agentList.statusInactiveFilterText', { + defaultMessage: 'Inactive', + }), + }, +]; + +export const SearchAndFilterBar: React.FunctionComponent<{ + agentPolicies: AgentPolicy[]; + draftKuery: string; + onDraftKueryChange: (kuery: string) => void; + onSubmitSearch: (kuery: string) => void; + selectedAgentPolicies: string[]; + onSelectedAgentPoliciesChange: (selectedPolicies: string[]) => void; + selectedStatus: string[]; + onSelectedStatusChange: (selectedStatus: string[]) => void; + showUpgradeable: boolean; + onShowUpgradeableChange: (showUpgradeable: boolean) => void; +}> = ({ + agentPolicies, + draftKuery, + onDraftKueryChange, + onSubmitSearch, + selectedAgentPolicies, + onSelectedAgentPoliciesChange, + selectedStatus, + onSelectedStatusChange, + showUpgradeable, + onShowUpgradeableChange, +}) => { + // Policies state for filtering + const [isAgentPoliciesFilterOpen, setIsAgentPoliciesFilterOpen] = useState(false); + + // Status for filtering + const [isStatusFilterOpen, setIsStatutsFilterOpen] = useState(false); + + // Add a agent policy id to current search + const addAgentPolicyFilter = (policyId: string) => { + onSelectedAgentPoliciesChange([...selectedAgentPolicies, policyId]); + }; + + // Remove a agent policy id from current search + const removeAgentPolicyFilter = (policyId: string) => { + onSelectedAgentPoliciesChange( + selectedAgentPolicies.filter((agentPolicy) => agentPolicy !== policyId) + ); + }; + + return ( + <> + {/* Search and filter bar */} + + + + + { + onDraftKueryChange(newSearch); + if (submit) { + onSubmitSearch(newSearch); + } + }} + fieldPrefix={AGENT_SAVED_OBJECT_TYPE} + /> + + + + setIsStatutsFilterOpen(!isStatusFilterOpen)} + isSelected={isStatusFilterOpen} + hasActiveFilters={selectedStatus.length > 0} + numActiveFilters={selectedStatus.length} + disabled={agentPolicies.length === 0} + > + + + } + isOpen={isStatusFilterOpen} + closePopover={() => setIsStatutsFilterOpen(false)} + panelPaddingSize="none" + > +
+ {statusFilters.map(({ label, status }, idx) => ( + { + if (selectedStatus.includes(status)) { + onSelectedStatusChange([...selectedStatus.filter((s) => s !== status)]); + } else { + onSelectedStatusChange([...selectedStatus, status]); + } + }} + > + {label} + + ))} +
+
+ setIsAgentPoliciesFilterOpen(!isAgentPoliciesFilterOpen)} + isSelected={isAgentPoliciesFilterOpen} + hasActiveFilters={selectedAgentPolicies.length > 0} + numActiveFilters={selectedAgentPolicies.length} + numFilters={agentPolicies.length} + disabled={agentPolicies.length === 0} + > + + + } + isOpen={isAgentPoliciesFilterOpen} + closePopover={() => setIsAgentPoliciesFilterOpen(false)} + panelPaddingSize="none" + > +
+ {agentPolicies.map((agentPolicy, index) => ( + { + if (selectedAgentPolicies.includes(agentPolicy.id)) { + removeAgentPolicyFilter(agentPolicy.id); + } else { + addAgentPolicyFilter(agentPolicy.id); + } + }} + > + {agentPolicy.name} + + ))} +
+
+ { + onShowUpgradeableChange(!showUpgradeable); + }} + > + + +
+
+
+
+
+ + ); +}; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/status_badges.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/status_badges.tsx new file mode 100644 index 0000000000000..250b021c77c15 --- /dev/null +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/status_badges.tsx @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiFlexGroup, EuiHealth, EuiNotificationBadge, EuiFlexItem } from '@elastic/eui'; +import React, { memo, useMemo } from 'react'; +import { + AGENT_STATUSES, + getColorForAgentStatus, + getLabelForAgentStatus, +} from '../../services/agent_status'; +import { SimplifiedAgentStatus } from '../../../../types'; + +export const AgentStatusBadges: React.FC<{ + showInactive?: boolean; + agentStatus: { [k in SimplifiedAgentStatus]: number }; +}> = memo(({ agentStatus, showInactive }) => { + const agentStatuses = useMemo(() => { + return AGENT_STATUSES.filter((status) => (showInactive ? true : status !== 'inactive')); + }, [showInactive]); + + return ( + + {agentStatuses.map((status) => ( + + + + ))} + + ); +}); + +const AgentStatusBadge: React.FC<{ status: SimplifiedAgentStatus; count: number }> = memo( + ({ status, count }) => { + return ( + <> + + + {getLabelForAgentStatus(status)} + + + {count} + + + + + + ); + } +); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/status_bar.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/status_bar.tsx new file mode 100644 index 0000000000000..b2fa2eacbd5f2 --- /dev/null +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/status_bar.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import styled from 'styled-components'; +import { EuiColorPaletteDisplay } from '@elastic/eui'; +import React, { useMemo } from 'react'; +import { AGENT_STATUSES, getColorForAgentStatus } from '../../services/agent_status'; +import { SimplifiedAgentStatus } from '../../../../types'; + +const StyledEuiColorPaletteDisplay = styled(EuiColorPaletteDisplay)` + &.ingest-agent-status-bar { + border: none; + border-radius: 0; + &:after { + border: none; + } + } +`; + +export const AgentStatusBar: React.FC<{ + agentStatus: { [k in SimplifiedAgentStatus]: number }; +}> = ({ agentStatus }) => { + const palette = useMemo(() => { + return AGENT_STATUSES.reduce((acc, status) => { + const previousStop = acc.length > 0 ? acc[acc.length - 1].stop : 0; + acc.push({ + stop: previousStop + (agentStatus[status] || 0), + color: getColorForAgentStatus(status), + }); + return acc; + }, [] as Array<{ stop: number; color: string }>); + }, [agentStatus]); + return ( + <> + + + ); +}; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/table_header.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/table_header.tsx new file mode 100644 index 0000000000000..80ab76ffde4a0 --- /dev/null +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/components/table_header.tsx @@ -0,0 +1,68 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; +import { EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; +import { Agent, SimplifiedAgentStatus } from '../../../../types'; + +import { AgentStatusBar } from './status_bar'; +import { AgentBulkActions } from './bulk_actions'; +import {} from '@elastic/eui'; +import { AgentStatusBadges } from './status_badges'; + +export type SelectionMode = 'manual' | 'query'; + +export const AgentTableHeader: React.FunctionComponent<{ + agentStatus?: { [k in SimplifiedAgentStatus]: number }; + showInactive: boolean; + totalAgents: number; + totalInactiveAgents: number; + selectableAgents: number; + selectionMode: SelectionMode; + setSelectionMode: (mode: SelectionMode) => void; + currentQuery: string; + selectedAgents: Agent[]; + setSelectedAgents: (agents: Agent[]) => void; + refreshAgents: () => void; +}> = ({ + agentStatus, + totalAgents, + totalInactiveAgents, + selectableAgents, + selectionMode, + setSelectionMode, + currentQuery, + selectedAgents, + setSelectedAgents, + refreshAgents, + showInactive, +}) => { + return ( + <> + + + + + + {agentStatus && ( + + )} + + + + {agentStatus && } + + ); +}; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/index.tsx index 1d08a1f791976..2067a2bd91c58 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_list_page/index.tsx @@ -3,41 +3,38 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import React, { useState, useMemo, useCallback, useRef } from 'react'; +import React, { useState, useMemo, useCallback, useRef, useEffect } from 'react'; import { EuiBasicTable, EuiButton, EuiEmptyPrompt, - EuiFilterButton, - EuiFilterGroup, - EuiFilterSelectItem, EuiFlexGroup, EuiFlexItem, EuiLink, - EuiPopover, EuiSpacer, EuiText, EuiContextMenuItem, EuiIcon, EuiPortal, - EuiHorizontalRule, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage, FormattedRelative } from '@kbn/i18n/react'; import { AgentEnrollmentFlyout } from '../components'; -import { Agent, AgentPolicy } from '../../../types'; +import { Agent, AgentPolicy, SimplifiedAgentStatus } from '../../../types'; import { usePagination, useCapabilities, useGetAgentPolicies, - useGetAgents, + sendGetAgents, + sendGetAgentStatus, useUrlParams, useLink, useBreadcrumbs, useLicense, useKibanaVersion, + useStartServices, } from '../../../hooks'; -import { SearchBar, ContextMenuActions } from '../../../components'; +import { ContextMenuActions } from '../../../components'; import { AgentStatusKueryHelper, isAgentUpgradeable } from '../../../services'; import { AGENT_SAVED_OBJECT_TYPE } from '../../../constants'; import { @@ -46,37 +43,11 @@ import { AgentUnenrollAgentModal, AgentUpgradeAgentModal, } from '../components'; -import { AgentBulkActions, SelectionMode } from './components/bulk_actions'; - -const REFRESH_INTERVAL_MS = 5000; - -const statusFilters = [ - { - status: 'online', - label: i18n.translate('xpack.fleet.agentList.statusOnlineFilterText', { - defaultMessage: 'Online', - }), - }, - { - status: 'offline', - label: i18n.translate('xpack.fleet.agentList.statusOfflineFilterText', { - defaultMessage: 'Offline', - }), - }, - , - { - status: 'error', - label: i18n.translate('xpack.fleet.agentList.statusErrorFilterText', { - defaultMessage: 'Error', - }), - }, - { - status: 'updating', - label: i18n.translate('xpack.fleet.agentList.statusUpdatingFilterText', { - defaultMessage: 'Updating', - }), - }, -] as Array<{ label: string; status: string }>; +import { AgentTableHeader } from './components/table_header'; +import { SelectionMode } from './components/bulk_actions'; +import { SearchAndFilterBar } from './components/search_and_filter_bar'; + +const REFRESH_INTERVAL_MS = 10000; const RowActions = React.memo<{ agent: Agent; @@ -160,6 +131,7 @@ function safeMetadata(val: any) { } export const AgentListPage: React.FunctionComponent<{}> = () => { + const { notifications } = useStartServices(); useBreadcrumbs('fleet_agent_list'); const { getHref } = useLink(); const defaultKuery: string = (useUrlParams().urlParams.kuery as string) || ''; @@ -168,50 +140,43 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { const kibanaVersion = useKibanaVersion(); // Agent data states - const [showInactive, setShowInactive] = useState(false); const [showUpgradeable, setShowUpgradeable] = useState(false); // Table and search states + const [draftKuery, setDraftKuery] = useState(defaultKuery); const [search, setSearch] = useState(defaultKuery); const [selectionMode, setSelectionMode] = useState('manual'); const [selectedAgents, setSelectedAgents] = useState([]); const tableRef = useRef>(null); const { pagination, pageSizeOptions, setPagination } = usePagination(); + const onSubmitSearch = useCallback( + (newKuery: string) => { + setSearch(newKuery); + setPagination({ + ...pagination, + currentPage: 1, + }); + }, + [setSearch, pagination, setPagination] + ); + // Policies state for filtering - const [isAgentPoliciesFilterOpen, setIsAgentPoliciesFilterOpen] = useState(false); const [selectedAgentPolicies, setSelectedAgentPolicies] = useState([]); // Status for filtering - const [isStatusFilterOpen, setIsStatutsFilterOpen] = useState(false); const [selectedStatus, setSelectedStatus] = useState([]); const isUsingFilter = - search.trim() || - selectedAgentPolicies.length || - selectedStatus.length || - showInactive || - showUpgradeable; + search.trim() || selectedAgentPolicies.length || selectedStatus.length || showUpgradeable; const clearFilters = useCallback(() => { + setDraftKuery(''); setSearch(''); setSelectedAgentPolicies([]); setSelectedStatus([]); - setShowInactive(false); setShowUpgradeable(false); - }, [setSearch, setSelectedAgentPolicies, setSelectedStatus, setShowInactive, setShowUpgradeable]); - - // Add a agent policy id to current search - const addAgentPolicyFilter = (policyId: string) => { - setSelectedAgentPolicies([...selectedAgentPolicies, policyId]); - }; - - // Remove a agent policy id from current search - const removeAgentPolicyFilter = (policyId: string) => { - setSelectedAgentPolicies( - selectedAgentPolicies.filter((agentPolicy) => agentPolicy !== policyId) - ); - }; + }, [setSearch, setDraftKuery, setSelectedAgentPolicies, setSelectedStatus, setShowUpgradeable]); // Agent enrollment flyout state const [isEnrollmentFlyoutOpen, setIsEnrollmentFlyoutOpen] = useState(false); @@ -221,65 +186,140 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { const [agentToUnenroll, setAgentToUnenroll] = useState(undefined); const [agentToUpgrade, setAgentToUpgrade] = useState(undefined); - let kuery = search.trim(); - if (selectedAgentPolicies.length) { - if (kuery) { - kuery = `(${kuery}) and`; + // Kuery + const kuery = useMemo(() => { + let kueryBuilder = search.trim(); + if (selectedAgentPolicies.length) { + if (kueryBuilder) { + kueryBuilder = `(${kueryBuilder}) and`; + } + kueryBuilder = `${kueryBuilder} ${AGENT_SAVED_OBJECT_TYPE}.policy_id : (${selectedAgentPolicies + .map((agentPolicy) => `"${agentPolicy}"`) + .join(' or ')})`; } - kuery = `${kuery} ${AGENT_SAVED_OBJECT_TYPE}.policy_id : (${selectedAgentPolicies - .map((agentPolicy) => `"${agentPolicy}"`) - .join(' or ')})`; - } - if (selectedStatus.length) { - const kueryStatus = selectedStatus - .map((status) => { - switch (status) { - case 'online': - return AgentStatusKueryHelper.buildKueryForOnlineAgents(); - case 'offline': - return AgentStatusKueryHelper.buildKueryForOfflineAgents(); - case 'updating': - return AgentStatusKueryHelper.buildKueryForUpdatingAgents(); - case 'error': - return AgentStatusKueryHelper.buildKueryForErrorAgents(); - } + if (selectedStatus.length) { + const kueryStatus = selectedStatus + .map((status) => { + switch (status) { + case 'healthy': + return AgentStatusKueryHelper.buildKueryForOnlineAgents(); + case 'unhealthy': + return AgentStatusKueryHelper.buildKueryForErrorAgents(); + case 'offline': + return AgentStatusKueryHelper.buildKueryForOfflineAgents(); + case 'updating': + return AgentStatusKueryHelper.buildKueryForUpdatingAgents(); + case 'inactive': + return AgentStatusKueryHelper.buildKueryForInactiveAgents(); + } - return ''; - }) - .join(' or '); + return undefined; + }) + .filter((statusKuery) => statusKuery !== undefined) + .join(' or '); - if (kuery) { - kuery = `(${kuery}) and ${kueryStatus}`; - } else { - kuery = kueryStatus; + if (kueryBuilder) { + kueryBuilder = `(${kueryBuilder}) and ${kueryStatus}`; + } else { + kueryBuilder = kueryStatus; + } } - } - const agentsRequest = useGetAgents( - { - page: pagination.currentPage, - perPage: pagination.pageSize, - kuery: kuery && kuery !== '' ? kuery : undefined, - showInactive, - showUpgradeable, - }, - { - pollIntervalMs: REFRESH_INTERVAL_MS, + return kueryBuilder; + }, [selectedStatus, selectedAgentPolicies, search]); + + const showInactive = useMemo(() => { + return selectedStatus.includes('inactive'); + }, [selectedStatus]); + + const [agents, setAgents] = useState([]); + const [agentsStatus, setAgentsStatus] = useState< + { [key in SimplifiedAgentStatus]: number } | undefined + >(); + const [isLoading, setIsLoading] = useState(false); + const [totalAgents, setTotalAgents] = useState(0); + const [totalInactiveAgents, setTotalInactiveAgents] = useState(0); + + // Request to fetch agents and agent status + const currentRequestRef = useRef(0); + const fetchData = useCallback(() => { + async function fetchDataAsync() { + currentRequestRef.current++; + const currentRequest = currentRequestRef.current; + + try { + setIsLoading(true); + const [agentsRequest, agentsStatusRequest] = await Promise.all([ + sendGetAgents({ + page: pagination.currentPage, + perPage: pagination.pageSize, + kuery: kuery && kuery !== '' ? kuery : undefined, + showInactive, + showUpgradeable, + }), + sendGetAgentStatus({ + kuery: kuery && kuery !== '' ? kuery : undefined, + }), + ]); + // Return if a newer request as been triggered + if (currentRequestRef.current !== currentRequest) { + return; + } + if (agentsRequest.error) { + throw agentsRequest.error; + } + if (!agentsRequest.data) { + throw new Error('Invalid GET /agents response'); + } + if (agentsStatusRequest.error) { + throw agentsStatusRequest.error; + } + if (!agentsStatusRequest.data) { + throw new Error('Invalid GET /agents-status response'); + } + + setAgentsStatus({ + healthy: agentsStatusRequest.data.results.online, + unhealthy: agentsStatusRequest.data.results.error, + offline: agentsStatusRequest.data.results.offline, + updating: agentsStatusRequest.data.results.other, + inactive: agentsRequest.data.totalInactive, + }); + + setAgents(agentsRequest.data.list); + setTotalAgents(agentsRequest.data.total); + setTotalInactiveAgents(agentsRequest.data.totalInactive); + } catch (error) { + notifications.toasts.addError(error, { + title: i18n.translate('xpack.fleet.agentList.errorFetchingDataTitle', { + defaultMessage: 'Error fetching agents', + }), + }); + } + setIsLoading(false); } - ); + fetchDataAsync(); + }, [pagination, kuery, showInactive, showUpgradeable, notifications.toasts]); - const agents = agentsRequest.data ? agentsRequest.data.list : []; - const totalAgents = agentsRequest.data ? agentsRequest.data.total : 0; - const totalInactiveAgents = agentsRequest.data ? agentsRequest.data.totalInactive : 0; - const { isLoading } = agentsRequest; + // Send request to get agent list and status + useEffect(() => { + fetchData(); + const interval = setInterval(() => { + fetchData(); + }, REFRESH_INTERVAL_MS); + + return () => clearInterval(interval); + }, [fetchData]); const agentPoliciesRequest = useGetAgentPolicies({ page: 1, perPage: 1000, }); - // eslint-disable-next-line react-hooks/exhaustive-deps - const agentPolicies = agentPoliciesRequest.data ? agentPoliciesRequest.data.items : []; + const agentPolicies = useMemo( + () => (agentPoliciesRequest.data ? agentPoliciesRequest.data.items : []), + [agentPoliciesRequest] + ); const agentPoliciesIndexedById = useMemo(() => { return agentPolicies.reduce((acc, agentPolicy) => { acc[agentPolicy.id] = agentPolicy; @@ -287,7 +327,6 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { return acc; }, {} as { [k: string]: AgentPolicy }); }, [agentPolicies]); - const { isLoading: isAgentPoliciesLoading } = agentPoliciesRequest; const columns = [ { @@ -405,7 +444,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { return ( agentsRequest.resendRequest()} + refresh={() => fetchData()} onReassignClick={() => setAgentToReassign(agent)} onUnenrollClick={() => setAgentToUnenroll(agent)} onUpgradeClick={() => setAgentToUpgrade(agent)} @@ -452,7 +491,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { agents={[agentToReassign]} onClose={() => { setAgentToReassign(undefined); - agentsRequest.resendRequest(); + fetchData(); }} /> @@ -464,7 +503,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { agentCount={1} onClose={() => { setAgentToUnenroll(undefined); - agentsRequest.resendRequest(); + fetchData(); }} useForceUnenroll={agentToUnenroll.status === 'unenrolling'} /> @@ -478,7 +517,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { agentCount={1} onClose={() => { setAgentToUpgrade(undefined); - agentsRequest.resendRequest(); + fetchData(); }} version={kibanaVersion} /> @@ -486,134 +525,26 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { )} {/* Search and filter bar */} - - - - - { - setPagination({ - ...pagination, - currentPage: 1, - }); - setSearch(newSearch); - }} - fieldPrefix={AGENT_SAVED_OBJECT_TYPE} - /> - - - - setIsStatutsFilterOpen(!isStatusFilterOpen)} - isSelected={isStatusFilterOpen} - hasActiveFilters={selectedStatus.length > 0} - numActiveFilters={selectedStatus.length} - disabled={isAgentPoliciesLoading} - > - - - } - isOpen={isStatusFilterOpen} - closePopover={() => setIsStatutsFilterOpen(false)} - panelPaddingSize="none" - > -
- {statusFilters.map(({ label, status }, idx) => ( - { - if (selectedStatus.includes(status)) { - setSelectedStatus([...selectedStatus.filter((s) => s !== status)]); - } else { - setSelectedStatus([...selectedStatus, status]); - } - }} - > - {label} - - ))} -
-
- setIsAgentPoliciesFilterOpen(!isAgentPoliciesFilterOpen)} - isSelected={isAgentPoliciesFilterOpen} - hasActiveFilters={selectedAgentPolicies.length > 0} - numActiveFilters={selectedAgentPolicies.length} - numFilters={agentPolicies.length} - disabled={isAgentPoliciesLoading} - > - - - } - isOpen={isAgentPoliciesFilterOpen} - closePopover={() => setIsAgentPoliciesFilterOpen(false)} - panelPaddingSize="none" - > -
- {agentPolicies.map((agentPolicy, index) => ( - { - if (selectedAgentPolicies.includes(agentPolicy.id)) { - removeAgentPolicyFilter(agentPolicy.id); - } else { - addAgentPolicyFilter(agentPolicy.id); - } - }} - > - {agentPolicy.name} - - ))} -
-
- { - setShowUpgradeable(!showUpgradeable); - }} - > - - - setShowInactive(!showInactive)} - > - - -
-
-
-
-
+ - {/* Agent total and bulk actions */} - agent.active).length || 0} selectionMode={selectionMode} setSelectionMode={setSelectionMode} @@ -625,10 +556,9 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { setSelectionMode('manual'); } }} - refreshAgents={() => agentsRequest.resendRequest()} + refreshAgents={() => fetchData()} /> - - + {/* Agent list table */} @@ -638,7 +568,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { loading={isLoading} hasActions={true} noItemsMessage={ - isLoading && agentsRequest.isInitialRequest ? ( + isLoading && currentRequestRef.current === 1 ? ( - + ), Unhealthy: ( diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/list_layout.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/list_layout.tsx index bf0163fe904e6..dfa093ca8bf80 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/list_layout.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/list_layout.tsx @@ -5,122 +5,31 @@ */ import React from 'react'; -import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import styled from 'styled-components'; -import { - EuiHealth, - EuiText, - EuiFlexGroup, - EuiFlexItem, - EuiStat, - EuiI18nNumber, - EuiButton, -} from '@elastic/eui'; +import { EuiText, EuiFlexGroup, EuiFlexItem, EuiButton, EuiPortal } from '@elastic/eui'; import { Props as EuiTabProps } from '@elastic/eui/src/components/tabs/tab'; import { useRouteMatch } from 'react-router-dom'; import { PAGE_ROUTING_PATHS } from '../../../constants'; import { WithHeaderLayout } from '../../../layouts'; import { useCapabilities, useLink, useGetAgentPolicies } from '../../../hooks'; -import { useGetAgentStatus } from '../../agent_policy/details_page/hooks'; import { AgentEnrollmentFlyout } from '../components'; -import { DonutChart } from './donut_chart'; - -const REFRESH_INTERVAL_MS = 5000; - -const Divider = styled.div` - width: 0; - height: 100%; - border-left: ${(props) => props.theme.eui.euiBorderThin}; - height: 45px; -`; export const ListLayout: React.FunctionComponent<{}> = ({ children }) => { const { getHref } = useLink(); const hasWriteCapabilites = useCapabilities().write; - const agentStatusRequest = useGetAgentStatus(undefined, { - pollIntervalMs: REFRESH_INTERVAL_MS, - }); - const agentStatus = agentStatusRequest.data?.results; // Agent enrollment flyout state const [isEnrollmentFlyoutOpen, setIsEnrollmentFlyoutOpen] = React.useState(false); - const headerRightColumn = ( - - - } - description={i18n.translate('xpack.fleet.agentListStatus.totalLabel', { - defaultMessage: 'Agents', - })} - /> - - - - + const headerRightColumn = hasWriteCapabilites ? ( + - - - - } - description={i18n.translate('xpack.fleet.agentListStatus.onlineLabel', { - defaultMessage: 'Online', - })} - /> + setIsEnrollmentFlyoutOpen(true)}> + + - - } - description={i18n.translate('xpack.fleet.agentListStatus.offlineLabel', { - defaultMessage: 'Offline', - })} - /> - - - } - description={i18n.translate('xpack.fleet.agentListStatus.errorLabel', { - defaultMessage: 'Error', - })} - /> - - {hasWriteCapabilites && ( - <> - - - - - setIsEnrollmentFlyoutOpen(true)}> - - - - - )} - ); + ) : undefined; const headerLeftColumn = ( @@ -177,10 +86,12 @@ export const ListLayout: React.FunctionComponent<{}> = ({ children }) => { } > {isEnrollmentFlyoutOpen ? ( - setIsEnrollmentFlyoutOpen(false)} - /> + + setIsEnrollmentFlyoutOpen(false)} + /> + ) : null} {children} diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/services/agent_status.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/services/agent_status.tsx new file mode 100644 index 0000000000000..5e7b42798c294 --- /dev/null +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/services/agent_status.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { euiPaletteColorBlindBehindText } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { SimplifiedAgentStatus } from '../../../types'; + +const visColors = euiPaletteColorBlindBehindText(); +const colorToHexMap = { + // TODO - replace with variable once https://github.com/elastic/eui/issues/2731 is closed + default: '#d3dae6', + primary: visColors[1], + secondary: visColors[0], + accent: visColors[2], + warning: visColors[5], + danger: visColors[9], +}; + +export const AGENT_STATUSES: SimplifiedAgentStatus[] = [ + 'healthy', + 'unhealthy', + 'updating', + 'offline', + 'inactive', +]; + +export function getColorForAgentStatus(agentStatus: SimplifiedAgentStatus): string { + switch (agentStatus) { + case 'healthy': + return colorToHexMap.secondary; + case 'offline': + case 'inactive': + return colorToHexMap.default; + case 'unhealthy': + return colorToHexMap.warning; + case 'updating': + return colorToHexMap.primary; + default: + throw new Error(`Insuported Agent status ${agentStatus}`); + } +} + +export function getLabelForAgentStatus(agentStatus: SimplifiedAgentStatus): string { + switch (agentStatus) { + case 'healthy': + return i18n.translate('xpack.fleet.agentStatus.healthyLabel', { + defaultMessage: 'Healthy', + }); + case 'offline': + return i18n.translate('xpack.fleet.agentStatus.offlineLabel', { + defaultMessage: 'Offline', + }); + case 'inactive': + return i18n.translate('xpack.fleet.agentStatus.inactiveLabel', { + defaultMessage: 'Inactive', + }); + case 'unhealthy': + return i18n.translate('xpack.fleet.agentStatus.unhealthyLabel', { + defaultMessage: 'Unhealthy', + }); + case 'updating': + return i18n.translate('xpack.fleet.agentStatus.updatingLabel', { + defaultMessage: 'Updating', + }); + default: + throw new Error(`Insuported Agent status ${agentStatus}`); + } +} diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/epm/components/package_list_grid.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/epm/components/package_list_grid.tsx index b96fda2c23af1..42e4a6051d725 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/epm/components/package_list_grid.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/epm/components/package_list_grid.tsx @@ -21,6 +21,7 @@ import { Loading } from '../../../components'; import { PackageList } from '../../../types'; import { useLocalSearch, searchIdField } from '../hooks'; import { PackageCard } from './package_card'; +import { pkgKeyFromPackageInfo } from '../../../services/pkg_key_from_package_info'; interface ListProps { isLoading?: boolean; @@ -118,7 +119,7 @@ function GridColumn({ list }: GridColumnProps) { {list.length ? ( list.map((item) => ( - + )) diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/epm/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/epm/index.tsx index 8884d1f9d7a75..733aa9dfcf8aa 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/epm/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/epm/index.tsx @@ -11,6 +11,7 @@ import { useBreadcrumbs } from '../../hooks'; import { CreatePackagePolicyPage } from '../agent_policy/create_package_policy_page'; import { EPMHomePage } from './screens/home'; import { Detail } from './screens/detail'; +import { Policy } from './screens/policy'; export const EPMApp: React.FunctionComponent = () => { useBreadcrumbs('integrations'); @@ -20,6 +21,9 @@ export const EPMApp: React.FunctionComponent = () => { + + + diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/detail/index.test.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/detail/index.test.tsx index 7ed14a27c32cf..3d43725f2dc71 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/detail/index.test.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/detail/index.test.tsx @@ -10,17 +10,26 @@ import React, { lazy, memo } from 'react'; import { PAGE_ROUTING_PATHS, pagePathGetters } from '../../../../constants'; import { Route } from 'react-router-dom'; import { + GetAgentPoliciesResponse, GetFleetStatusResponse, GetInfoResponse, + GetPackagePoliciesResponse, } from '../../../../../../../common/types/rest_spec'; import { DetailViewPanelName, KibanaAssetType } from '../../../../../../../common/types/models'; -import { epmRouteService, fleetSetupRouteService } from '../../../../../../../common/services'; -import { act } from '@testing-library/react'; +import { + agentPolicyRouteService, + epmRouteService, + fleetSetupRouteService, + packagePolicyRouteService, +} from '../../../../../../../common/services'; +import { act, cleanup } from '@testing-library/react'; describe('when on integration detail', () => { - const detailPageUrlPath = pagePathGetters.integration_details({ pkgkey: 'nginx-0.3.7' }); + const pkgkey = 'nginx-0.3.7'; + const detailPageUrlPath = pagePathGetters.integration_details({ pkgkey }); let testRenderer: TestRenderer; let renderResult: ReturnType; + let mockedApi: MockedApi; const render = () => (renderResult = testRenderer.render( @@ -30,10 +39,15 @@ describe('when on integration detail', () => { beforeEach(() => { testRenderer = createTestRendererMock(); - mockApiCalls(testRenderer.startServices.http); + mockedApi = mockApiCalls(testRenderer.startServices.http); testRenderer.history.push(detailPageUrlPath); }); + afterEach(() => { + cleanup(); + window.location.hash = '#/'; + }); + describe('and a custom UI extension is NOT registered', () => { beforeEach(() => render()); @@ -137,9 +151,48 @@ describe('when on integration detail', () => { }); }); }); + + describe('and on the Policies Tab', () => { + const policiesTabURLPath = pagePathGetters.integration_details({ pkgkey, panel: 'policies' }); + beforeEach(() => { + testRenderer.history.push(policiesTabURLPath); + render(); + }); + + it('should display policies list', () => { + const table = renderResult.getByTestId('integrationPolicyTable'); + expect(table).not.toBeNull(); + }); + + it('should link to integration policy detail when an integration policy is clicked', async () => { + await mockedApi.waitForApi(); + const firstPolicy = renderResult.getByTestId('integrationNameLink') as HTMLAnchorElement; + expect(firstPolicy.href).toEqual( + 'http://localhost/mock/app/fleet#/integrations/edit-integration/e8a37031-2907-44f6-89d2-98bd493f60dc' + ); + }); + }); }); -const mockApiCalls = (http: MockedFleetStartServices['http']) => { +interface MockedApi { + /** Will return a promise that resolves when triggered APIs are complete */ + waitForApi: () => Promise; +} + +const mockApiCalls = (http: MockedFleetStartServices['http']): MockedApi => { + let inflightApiCalls = 0; + const apiDoneListeners: Array<() => void> = []; + const markApiCallAsHandled = async () => { + inflightApiCalls++; + await new Promise((r) => setTimeout(r, 1)); + inflightApiCalls--; + + // If no more pending API calls, then notify listeners + if (inflightApiCalls === 0 && apiDoneListeners.length > 0) { + apiDoneListeners.splice(0).forEach((listener) => listener()); + } + }; + // @ts-ignore const epmPackageResponse: GetInfoResponse = { response: { @@ -369,7 +422,7 @@ const mockApiCalls = (http: MockedFleetStartServices['http']) => { owner: { github: 'elastic/integrations-services' }, latestVersion: '0.3.7', removable: true, - status: 'not_installed', + status: 'installed', }, } as GetInfoResponse; @@ -388,24 +441,162 @@ On Windows, the module was tested with Nginx installed from the Chocolatey repos const agentsSetupResponse: GetFleetStatusResponse = { isReady: true, missing_requirements: [] }; + const packagePoliciesResponse: GetPackagePoliciesResponse = { + items: [ + { + id: 'e8a37031-2907-44f6-89d2-98bd493f60dc', + version: 'WzgzMiwxXQ==', + name: 'nginx-1', + description: '', + namespace: 'default', + policy_id: '521c1b70-3976-11eb-ad1c-3baa423084d9', + enabled: true, + output_id: '', + inputs: [ + { + type: 'logfile', + enabled: true, + streams: [ + { + enabled: true, + data_stream: { type: 'logs', dataset: 'nginx.access' }, + vars: { paths: { value: ['/var/log/nginx/access.log*'], type: 'text' } }, + id: 'logfile-nginx.access-e8a37031-2907-44f6-89d2-98bd493f60dc', + compiled_stream: { + paths: ['/var/log/nginx/access.log*'], + exclude_files: ['.gz$'], + processors: [{ add_locale: null }], + }, + }, + { + enabled: true, + data_stream: { type: 'logs', dataset: 'nginx.error' }, + vars: { paths: { value: ['/var/log/nginx/error.log*'], type: 'text' } }, + id: 'logfile-nginx.error-e8a37031-2907-44f6-89d2-98bd493f60dc', + compiled_stream: { + paths: ['/var/log/nginx/error.log*'], + exclude_files: ['.gz$'], + multiline: { + pattern: '^\\d{4}\\/\\d{2}\\/\\d{2} ', + negate: true, + match: 'after', + }, + processors: [{ add_locale: null }], + }, + }, + { + enabled: false, + data_stream: { type: 'logs', dataset: 'nginx.ingress_controller' }, + vars: { paths: { value: ['/var/log/nginx/ingress.log*'], type: 'text' } }, + id: 'logfile-nginx.ingress_controller-e8a37031-2907-44f6-89d2-98bd493f60dc', + }, + ], + }, + { + type: 'nginx/metrics', + enabled: true, + streams: [ + { + enabled: true, + data_stream: { type: 'metrics', dataset: 'nginx.stubstatus' }, + vars: { + period: { value: '10s', type: 'text' }, + server_status_path: { value: '/nginx_status', type: 'text' }, + }, + id: 'nginx/metrics-nginx.stubstatus-e8a37031-2907-44f6-89d2-98bd493f60dc', + compiled_stream: { + metricsets: ['stubstatus'], + hosts: ['http://127.0.0.1:80'], + period: '10s', + server_status_path: '/nginx_status', + }, + }, + ], + vars: { hosts: { value: ['http://127.0.0.1:80'], type: 'text' } }, + }, + ], + package: { name: 'nginx', title: 'Nginx', version: '0.3.7' }, + revision: 1, + created_at: '2020-12-09T13:46:31.013Z', + created_by: 'elastic', + updated_at: '2020-12-09T13:46:31.013Z', + updated_by: 'elastic', + }, + ], + total: 1, + page: 1, + perPage: 20, + }; + + const agentPoliciesResponse: GetAgentPoliciesResponse = { + items: [ + { + id: '521c1b70-3976-11eb-ad1c-3baa423084d9', + name: 'Default', + namespace: 'default', + description: 'Default agent policy created by Kibana', + status: 'active', + package_policies: [ + '4d09bd78-b0ad-4238-9fa3-d87d3c887c73', + '2babac18-eb8e-4ce4-b53b-4b7c5f507019', + 'e8a37031-2907-44f6-89d2-98bd493f60dc', + ], + is_default: true, + monitoring_enabled: ['logs', 'metrics'], + revision: 6, + updated_at: '2020-12-09T13:46:31.840Z', + updated_by: 'elastic', + agents: 0, + }, + ], + total: 1, + page: 1, + perPage: 100, + }; + http.get.mockImplementation(async (path) => { if (typeof path === 'string') { if (path === epmRouteService.getInfoPath(`nginx-0.3.7`)) { + markApiCallAsHandled(); return epmPackageResponse; } if (path === epmRouteService.getFilePath('/package/nginx/0.3.7/docs/README.md')) { + markApiCallAsHandled(); return packageReadMe; } if (path === fleetSetupRouteService.getFleetSetupPath()) { + markApiCallAsHandled(); return agentsSetupResponse; } + if (path === packagePolicyRouteService.getListPath()) { + markApiCallAsHandled(); + return packagePoliciesResponse; + } + + if (path === agentPolicyRouteService.getListPath()) { + markApiCallAsHandled(); + return agentPoliciesResponse; + } + const err = new Error(`API [GET ${path}] is not MOCKED!`); // eslint-disable-next-line no-console - console.log(err); + console.error(err); throw err; } }); + + return { + waitForApi() { + return new Promise((resolve) => { + if (inflightApiCalls > 0) { + apiDoneListeners.push(resolve); + } else { + resolve(); + } + }); + }, + }; }; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/detail/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/detail/index.tsx index 467276f0d0b8c..c70a11db004a6 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/detail/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/detail/index.tsx @@ -43,6 +43,7 @@ import { Content } from './content'; import './index.scss'; import { useUIExtension } from '../../../../hooks/use_ui_extension'; import { PLUGIN_ID } from '../../../../../../../common/constants'; +import { pkgKeyFromPackageInfo } from '../../../../services/pkg_key_from_package_info'; export const DEFAULT_PANEL: DetailViewPanelName = 'overview'; @@ -315,7 +316,7 @@ export function Detail() { isSelected: panelId === panel, 'data-test-subj': `tab-${panelId}`, href: getHref('integration_details', { - pkgkey: `${packageInfo?.name}-${packageInfo?.version}`, + pkgkey: pkgKeyFromPackageInfo(packageInfo || {}), panel: panelId, }), }; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/detail/package_policies_panel.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/detail/package_policies_panel.tsx index 8609b08c9a774..4061b86f1f740 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/detail/package_policies_panel.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/detail/package_policies_panel.tsx @@ -36,8 +36,8 @@ const IntegrationDetailsLink = memo<{ return ( diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/policy/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/policy/index.tsx new file mode 100644 index 0000000000000..fcd4821996efe --- /dev/null +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/epm/screens/policy/index.tsx @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { memo } from 'react'; +import { useRouteMatch } from 'react-router-dom'; +import { EditPackagePolicyForm } from '../../../agent_policy/edit_package_policy_page'; + +export const Policy = memo(() => { + const { + params: { packagePolicyId }, + } = useRouteMatch<{ packagePolicyId: string }>(); + + return ; +}); diff --git a/x-pack/plugins/fleet/public/applications/fleet/services/pkg_key_from_package_info.ts b/x-pack/plugins/fleet/public/applications/fleet/services/pkg_key_from_package_info.ts new file mode 100644 index 0000000000000..0e38abe6f5160 --- /dev/null +++ b/x-pack/plugins/fleet/public/applications/fleet/services/pkg_key_from_package_info.ts @@ -0,0 +1,11 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const pkgKeyFromPackageInfo = ( + packageInfo: T +): string => { + return `${packageInfo.name}-${packageInfo.version}`; +}; diff --git a/x-pack/plugins/fleet/public/applications/fleet/types/index.ts b/x-pack/plugins/fleet/public/applications/fleet/types/index.ts index dd80c1ad77b85..dadacf6006085 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/types/index.ts +++ b/x-pack/plugins/fleet/public/applications/fleet/types/index.ts @@ -12,6 +12,7 @@ export { AgentPolicy, NewAgentPolicy, AgentEvent, + SimplifiedAgentStatus, EnrollmentAPIKey, PackagePolicy, NewPackagePolicy, diff --git a/x-pack/plugins/fleet/server/errors/handlers.ts b/x-pack/plugins/fleet/server/errors/handlers.ts index 08372571240ff..222554e97eb91 100644 --- a/x-pack/plugins/fleet/server/errors/handlers.ts +++ b/x-pack/plugins/fleet/server/errors/handlers.ts @@ -12,6 +12,7 @@ import { KibanaResponseFactory, } from 'src/core/server'; import { errors as LegacyESErrors } from 'elasticsearch'; +import { ResponseError } from '@elastic/elasticsearch/lib/errors'; import { appContextService } from '../services'; import { IngestManagerError, @@ -51,6 +52,10 @@ export const isLegacyESClientError = (error: any): error is LegacyESClientError return error instanceof LegacyESErrors._Abstract; }; +export function isESClientError(error: unknown): error is ResponseError { + return error instanceof ResponseError; +} + const getHTTPResponseCode = (error: IngestManagerError): number => { if (error instanceof RegistryError) { return 502; // Bad Gateway diff --git a/x-pack/plugins/fleet/server/errors/index.ts b/x-pack/plugins/fleet/server/errors/index.ts index d6fa79a2baeba..fad4eef66215d 100644 --- a/x-pack/plugins/fleet/server/errors/index.ts +++ b/x-pack/plugins/fleet/server/errors/index.ts @@ -9,6 +9,7 @@ export { defaultIngestErrorHandler, ingestErrorToResponseOptions, isLegacyESClientError, + isESClientError, } from './handlers'; export class IngestManagerError extends Error { diff --git a/x-pack/plugins/fleet/server/mocks.ts b/x-pack/plugins/fleet/server/mocks.ts index bc3e89ef6d3ce..9e2c71ead5b74 100644 --- a/x-pack/plugins/fleet/server/mocks.ts +++ b/x-pack/plugins/fleet/server/mocks.ts @@ -15,7 +15,7 @@ export const createAppContextStartContractMock = (): FleetAppContext => { return { encryptedSavedObjectsStart: encryptedSavedObjectsMock.createStart(), savedObjects: savedObjectsServiceMock.createStartContract(), - security: securityMock.createSetup(), + security: securityMock.createStart(), logger: loggingSystemMock.create().get(), isProductionMode: true, kibanaVersion: '8.0.0', diff --git a/x-pack/plugins/fleet/server/plugin.ts b/x-pack/plugins/fleet/server/plugin.ts index 7ddd6e3ba3fe0..0b58c4aab9d0b 100644 --- a/x-pack/plugins/fleet/server/plugin.ts +++ b/x-pack/plugins/fleet/server/plugin.ts @@ -24,7 +24,7 @@ import { EncryptedSavedObjectsPluginStart, EncryptedSavedObjectsPluginSetup, } from '../../encrypted_saved_objects/server'; -import { SecurityPluginSetup } from '../../security/server'; +import { SecurityPluginSetup, SecurityPluginStart } from '../../security/server'; import { PluginSetupContract as FeaturesPluginSetup } from '../../features/server'; import { PLUGIN_ID, @@ -85,12 +85,15 @@ export interface FleetSetupDeps { usageCollection?: UsageCollectionSetup; } -export type FleetStartDeps = object; +export interface FleetStartDeps { + encryptedSavedObjects: EncryptedSavedObjectsPluginStart; + security?: SecurityPluginStart; +} export interface FleetAppContext { encryptedSavedObjectsStart: EncryptedSavedObjectsPluginStart; encryptedSavedObjectsSetup?: EncryptedSavedObjectsPluginSetup; - security?: SecurityPluginSetup; + security?: SecurityPluginStart; config$?: Observable; savedObjects: SavedObjectsServiceStart; isProductionMode: PluginInitializerContext['env']['mode']['prod']; @@ -150,7 +153,6 @@ export class FleetPlugin implements Plugin { private licensing$!: Observable; private config$: Observable; - private security: SecurityPluginSetup | undefined; private cloud: CloudSetup | undefined; private logger: Logger | undefined; @@ -171,9 +173,6 @@ export class FleetPlugin public async setup(core: CoreSetup, deps: FleetSetupDeps) { this.httpSetup = core.http; this.licensing$ = deps.licensing.license$; - if (deps.security) { - this.security = deps.security; - } this.encryptedSavedObjectsSetup = deps.encryptedSavedObjects; this.cloud = deps.cloud; @@ -226,7 +225,7 @@ export class FleetPlugin // For all the routes we enforce the user to have role superuser const routerSuperuserOnly = makeRouterEnforcingSuperuser(router); // Register rest of routes only if security is enabled - if (this.security) { + if (deps.security) { registerSetupRoutes(routerSuperuserOnly, config); registerAgentPolicyRoutes(routerSuperuserOnly); registerPackagePolicyRoutes(routerSuperuserOnly); @@ -262,16 +261,11 @@ export class FleetPlugin } } - public async start( - core: CoreStart, - plugins: { - encryptedSavedObjects: EncryptedSavedObjectsPluginStart; - } - ): Promise { + public async start(core: CoreStart, plugins: FleetStartDeps): Promise { await appContextService.start({ encryptedSavedObjectsStart: plugins.encryptedSavedObjects, encryptedSavedObjectsSetup: this.encryptedSavedObjectsSetup, - security: this.security, + security: plugins.security, config$: this.config$, savedObjects: core.savedObjects, isProductionMode: this.isProductionMode, diff --git a/x-pack/plugins/fleet/server/routes/agent/handlers.ts b/x-pack/plugins/fleet/server/routes/agent/handlers.ts index eff7d3c3c5cf3..a867196f9762f 100644 --- a/x-pack/plugins/fleet/server/routes/agent/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent/handlers.ts @@ -330,7 +330,8 @@ export const getAgentStatusForAgentPolicyHandler: RequestHandler< // TODO change path const results = await AgentService.getAgentStatusForAgentPolicy( soClient, - request.query.policyId + request.query.policyId, + request.query.kuery ); const body: GetAgentStatusResponse = { results }; diff --git a/x-pack/plugins/fleet/server/routes/setup/handlers.ts b/x-pack/plugins/fleet/server/routes/setup/handlers.ts index b2ad9591bc2ee..f87cf8026c560 100644 --- a/x-pack/plugins/fleet/server/routes/setup/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/setup/handlers.ts @@ -15,7 +15,9 @@ export const getFleetStatusHandler: RequestHandler = async (context, request, re const soClient = context.core.savedObjects.client; try { const isAdminUserSetup = (await outputService.getAdminUser(soClient)) !== null; - const isApiKeysEnabled = await appContextService.getSecurity().authc.areAPIKeysEnabled(); + const isApiKeysEnabled = await appContextService + .getSecurity() + .authc.apiKeys.areAPIKeysEnabled(); const isTLSEnabled = appContextService.getHttpSetup().getServerInfo().protocol === 'https'; const isProductionMode = appContextService.getIsProductionMode(); const isCloud = appContextService.getCloud()?.isCloudEnabled ?? false; diff --git a/x-pack/plugins/fleet/server/services/agents/status.ts b/x-pack/plugins/fleet/server/services/agents/status.ts index 35033cbe86ea5..0dfa6db7df9be 100644 --- a/x-pack/plugins/fleet/server/services/agents/status.ts +++ b/x-pack/plugins/fleet/server/services/agents/status.ts @@ -23,7 +23,8 @@ export const getAgentStatus = AgentStatusKueryHelper.getAgentStatus; export async function getAgentStatusForAgentPolicy( soClient: SavedObjectsClientContract, - agentPolicyId?: string + agentPolicyId?: string, + filterKuery?: string ) { const [all, online, error, offline] = await Promise.all( [ @@ -36,15 +37,29 @@ export async function getAgentStatusForAgentPolicy( showInactive: false, perPage: 0, page: 1, - kuery: agentPolicyId - ? kuery - ? `(${kuery}) and (${AGENT_SAVED_OBJECT_TYPE}.policy_id:"${agentPolicyId}")` - : `${AGENT_SAVED_OBJECT_TYPE}.policy_id:"${agentPolicyId}"` - : kuery, + kuery: joinKuerys( + ...[ + kuery, + filterKuery, + agentPolicyId ? `${AGENT_SAVED_OBJECT_TYPE}.policy_id:"${agentPolicyId}"` : undefined, + ] + ), }) ) ); + function joinKuerys(...kuerys: Array) { + return kuerys + .filter((kuery) => kuery !== undefined) + .reduce((acc, kuery) => { + if (acc === '') { + return `(${kuery})`; + } + + return `${acc} and (${kuery})`; + }, ''); + } + return { events: await getEventsCount(soClient, agentPolicyId), total: all.total, diff --git a/x-pack/plugins/fleet/server/services/api_keys/security.ts b/x-pack/plugins/fleet/server/services/api_keys/security.ts index 5fdf8626a9fb2..9a32da3cff46f 100644 --- a/x-pack/plugins/fleet/server/services/api_keys/security.ts +++ b/x-pack/plugins/fleet/server/services/api_keys/security.ts @@ -6,7 +6,7 @@ import type { Request } from '@hapi/hapi'; import { KibanaRequest, SavedObjectsClientContract } from '../../../../../../src/core/server'; -import { FleetAdminUserInvalidError, isLegacyESClientError } from '../../errors'; +import { FleetAdminUserInvalidError, isESClientError } from '../../errors'; import { CallESAsCurrentUser } from '../../types'; import { appContextService } from '../app_context'; import { outputService } from '../output'; @@ -37,14 +37,14 @@ export async function createAPIKey( } try { - const key = await security.authc.createAPIKey(request, { + const key = await security.authc.apiKeys.create(request, { name, role_descriptors: roleDescriptors, }); return key; } catch (err) { - if (isLegacyESClientError(err) && err.statusCode === 401) { + if (isESClientError(err) && err.statusCode === 401) { // Clear Fleet admin user cache as the user is probably not valid anymore outputService.invalidateCache(); throw new FleetAdminUserInvalidError(`Fleet Admin user is invalid: ${err.message}`); @@ -87,13 +87,13 @@ export async function invalidateAPIKey(soClient: SavedObjectsClientContract, id: } try { - const res = await security.authc.invalidateAPIKey(request, { + const res = await security.authc.apiKeys.invalidate(request, { id, }); return res; } catch (err) { - if (isLegacyESClientError(err) && err.statusCode === 401) { + if (isESClientError(err) && err.statusCode === 401) { // Clear Fleet admin user cache as the user is probably not valid anymore outputService.invalidateCache(); throw new FleetAdminUserInvalidError(`Fleet Admin user is invalid: ${err.message}`); diff --git a/x-pack/plugins/fleet/server/services/app_context.ts b/x-pack/plugins/fleet/server/services/app_context.ts index 5c4e33d50b480..bcf056c9482cb 100644 --- a/x-pack/plugins/fleet/server/services/app_context.ts +++ b/x-pack/plugins/fleet/server/services/app_context.ts @@ -11,7 +11,7 @@ import { EncryptedSavedObjectsPluginSetup, } from '../../../encrypted_saved_objects/server'; import packageJSON from '../../../../../package.json'; -import { SecurityPluginSetup } from '../../../security/server'; +import { SecurityPluginStart } from '../../../security/server'; import { FleetConfigType } from '../../common'; import { ExternalCallback, ExternalCallbacksStorage, FleetAppContext } from '../plugin'; import { CloudSetup } from '../../../cloud/server'; @@ -19,7 +19,7 @@ import { CloudSetup } from '../../../cloud/server'; class AppContextService { private encryptedSavedObjects: EncryptedSavedObjectsClient | undefined; private encryptedSavedObjectsSetup: EncryptedSavedObjectsPluginSetup | undefined; - private security: SecurityPluginSetup | undefined; + private security: SecurityPluginStart | undefined; private config$?: Observable; private configSubject$?: BehaviorSubject; private savedObjects: SavedObjectsServiceStart | undefined; diff --git a/x-pack/plugins/fleet/server/types/rest_spec/agent.ts b/x-pack/plugins/fleet/server/types/rest_spec/agent.ts index 6de94cd9c936d..3e9262c2a9124 100644 --- a/x-pack/plugins/fleet/server/types/rest_spec/agent.ts +++ b/x-pack/plugins/fleet/server/types/rest_spec/agent.ts @@ -246,5 +246,6 @@ export const UpdateAgentRequestSchema = { export const GetAgentStatusRequestSchema = { query: schema.object({ policyId: schema.maybe(schema.string()), + kuery: schema.maybe(schema.string()), }), }; diff --git a/x-pack/plugins/global_search/public/mocks.ts b/x-pack/plugins/global_search/public/mocks.ts index 97dc01e92dbfe..8b0bfec66f61d 100644 --- a/x-pack/plugins/global_search/public/mocks.ts +++ b/x-pack/plugins/global_search/public/mocks.ts @@ -20,6 +20,7 @@ const createStartMock = (): jest.Mocked => { return { find: searchMock.find, + getSearchableTypes: searchMock.getSearchableTypes, }; }; diff --git a/x-pack/plugins/global_search/public/plugin.ts b/x-pack/plugins/global_search/public/plugin.ts index 6af8ec32a581d..a861911d935b4 100644 --- a/x-pack/plugins/global_search/public/plugin.ts +++ b/x-pack/plugins/global_search/public/plugin.ts @@ -45,13 +45,14 @@ export class GlobalSearchPlugin start({ http }: CoreStart, { licensing }: GlobalSearchPluginStartDeps) { this.licenseChecker = new LicenseChecker(licensing.license$); - const { find } = this.searchService.start({ + const { find, getSearchableTypes } = this.searchService.start({ http, licenseChecker: this.licenseChecker, }); return { find, + getSearchableTypes, }; } diff --git a/x-pack/plugins/global_search/public/services/fetch_server_searchable_types.test.ts b/x-pack/plugins/global_search/public/services/fetch_server_searchable_types.test.ts new file mode 100644 index 0000000000000..002ea0cff20d8 --- /dev/null +++ b/x-pack/plugins/global_search/public/services/fetch_server_searchable_types.test.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { httpServiceMock } from '../../../../../src/core/public/mocks'; +import { fetchServerSearchableTypes } from './fetch_server_searchable_types'; + +describe('fetchServerSearchableTypes', () => { + let http: ReturnType; + + beforeEach(() => { + http = httpServiceMock.createStartContract(); + }); + + it('perform a GET request to the endpoint with valid options', () => { + http.get.mockResolvedValue({ results: [] }); + + fetchServerSearchableTypes(http); + + expect(http.get).toHaveBeenCalledTimes(1); + expect(http.get).toHaveBeenCalledWith('/internal/global_search/searchable_types'); + }); + + it('returns the results from the server', async () => { + const types = ['typeA', 'typeB']; + + http.get.mockResolvedValue({ types }); + + const results = await fetchServerSearchableTypes(http); + + expect(http.get).toHaveBeenCalledTimes(1); + expect(results).toEqual(types); + }); +}); diff --git a/x-pack/plugins/global_search/public/services/fetch_server_searchable_types.ts b/x-pack/plugins/global_search/public/services/fetch_server_searchable_types.ts new file mode 100644 index 0000000000000..c4a0724991870 --- /dev/null +++ b/x-pack/plugins/global_search/public/services/fetch_server_searchable_types.ts @@ -0,0 +1,18 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { HttpStart } from 'src/core/public'; + +interface ServerSearchableTypesResponse { + types: string[]; +} + +export const fetchServerSearchableTypes = async (http: HttpStart) => { + const { types } = await http.get( + '/internal/global_search/searchable_types' + ); + return types; +}; diff --git a/x-pack/plugins/global_search/public/services/search_service.mock.ts b/x-pack/plugins/global_search/public/services/search_service.mock.ts index eca69148288b9..0aa65e39f026c 100644 --- a/x-pack/plugins/global_search/public/services/search_service.mock.ts +++ b/x-pack/plugins/global_search/public/services/search_service.mock.ts @@ -7,17 +7,21 @@ import { SearchServiceSetup, SearchServiceStart } from './search_service'; import { of } from 'rxjs'; -const createSetupMock = (): jest.Mocked => { - return { +const createSetupMock = () => { + const mock: jest.Mocked = { registerResultProvider: jest.fn(), }; + + return mock; }; -const createStartMock = (): jest.Mocked => { - const mock = { +const createStartMock = () => { + const mock: jest.Mocked = { find: jest.fn(), + getSearchableTypes: jest.fn(), }; mock.find.mockReturnValue(of({ results: [] })); + mock.getSearchableTypes.mockResolvedValue([]); return mock; }; diff --git a/x-pack/plugins/global_search/public/services/search_service.test.mocks.ts b/x-pack/plugins/global_search/public/services/search_service.test.mocks.ts index 1caabd6a1681c..bbc513c78759e 100644 --- a/x-pack/plugins/global_search/public/services/search_service.test.mocks.ts +++ b/x-pack/plugins/global_search/public/services/search_service.test.mocks.ts @@ -9,6 +9,11 @@ jest.doMock('./fetch_server_results', () => ({ fetchServerResults: fetchServerResultsMock, })); +export const fetchServerSearchableTypesMock = jest.fn(); +jest.doMock('./fetch_server_searchable_types', () => ({ + fetchServerSearchableTypes: fetchServerSearchableTypesMock, +})); + export const getDefaultPreferenceMock = jest.fn(); jest.doMock('./utils', () => { const original = jest.requireActual('./utils'); diff --git a/x-pack/plugins/global_search/public/services/search_service.test.ts b/x-pack/plugins/global_search/public/services/search_service.test.ts index 419ad847d6c29..297a27e3c837c 100644 --- a/x-pack/plugins/global_search/public/services/search_service.test.ts +++ b/x-pack/plugins/global_search/public/services/search_service.test.ts @@ -4,7 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { fetchServerResultsMock, getDefaultPreferenceMock } from './search_service.test.mocks'; +import { + fetchServerResultsMock, + getDefaultPreferenceMock, + fetchServerSearchableTypesMock, +} from './search_service.test.mocks'; import { Observable, of } from 'rxjs'; import { take } from 'rxjs/operators'; @@ -41,10 +45,17 @@ describe('SearchService', () => { const createProvider = ( id: string, - source: Observable = of([]) + { + source = of([]), + types = [], + }: { + source?: Observable; + types?: string[] | Promise; + } = {} ): jest.Mocked => ({ id, find: jest.fn().mockImplementation((term, options, context) => source), + getSearchableTypes: jest.fn().mockReturnValue(types), }); const expectedResult = (id: string) => expect.objectContaining({ id }); @@ -85,6 +96,9 @@ describe('SearchService', () => { fetchServerResultsMock.mockClear(); fetchServerResultsMock.mockReturnValue(of()); + fetchServerSearchableTypesMock.mockClear(); + fetchServerSearchableTypesMock.mockResolvedValue([]); + getDefaultPreferenceMock.mockClear(); getDefaultPreferenceMock.mockReturnValue('default_pref'); }); @@ -189,7 +203,7 @@ describe('SearchService', () => { a: [providerResult('1')], b: [providerResult('2')], }); - registerResultProvider(createProvider('A', providerResults)); + registerResultProvider(createProvider('A', { source: providerResults })); const { find } = service.start(startDeps()); const results = find({ term: 'foobar' }, {}); @@ -229,22 +243,20 @@ describe('SearchService', () => { getTestScheduler().run(({ expectObservable, hot }) => { registerResultProvider( - createProvider( - 'A', - hot('a---d-|', { + createProvider('A', { + source: hot('a---d-|', { a: [providerResult('A1'), providerResult('A2')], d: [providerResult('A3')], - }) - ) + }), + }) ); registerResultProvider( - createProvider( - 'B', - hot('-b-c| ', { + createProvider('B', { + source: hot('-b-c| ', { b: [providerResult('B1')], c: [providerResult('B2'), providerResult('B3')], - }) - ) + }), + }) ); const { find } = service.start(startDeps()); @@ -272,13 +284,12 @@ describe('SearchService', () => { ); registerResultProvider( - createProvider( - 'A', - hot('a-b-|', { + createProvider('A', { + source: hot('a-b-|', { a: [providerResult('P1')], b: [providerResult('P2')], - }) - ) + }), + }) ); const { find } = service.start(startDeps()); @@ -302,7 +313,7 @@ describe('SearchService', () => { a: [providerResult('1')], b: [providerResult('2')], }); - registerResultProvider(createProvider('A', providerResults)); + registerResultProvider(createProvider('A', { source: providerResults })); const aborted$ = hot('----a--|', { a: undefined }); @@ -326,7 +337,7 @@ describe('SearchService', () => { b: [providerResult('2')], c: [providerResult('3')], }); - registerResultProvider(createProvider('A', providerResults)); + registerResultProvider(createProvider('A', { source: providerResults })); const { find } = service.start(startDeps()); const results = find({ term: 'foobar' }, {}); @@ -346,22 +357,20 @@ describe('SearchService', () => { getTestScheduler().run(({ expectObservable, hot }) => { registerResultProvider( - createProvider( - 'A', - hot('a---d-|', { + createProvider('A', { + source: hot('a---d-|', { a: [providerResult('A1'), providerResult('A2')], d: [providerResult('A3')], - }) - ) + }), + }) ); registerResultProvider( - createProvider( - 'B', - hot('-b-c| ', { + createProvider('B', { + source: hot('-b-c| ', { b: [providerResult('B1')], c: [providerResult('B2'), providerResult('B3')], - }) - ) + }), + }) ); const { find } = service.start(startDeps()); @@ -394,7 +403,7 @@ describe('SearchService', () => { url: { path: '/foo', prependBasePath: false }, }); - const provider = createProvider('A', of([resultA, resultB])); + const provider = createProvider('A', { source: of([resultA, resultB]) }); registerResultProvider(provider); const { find } = service.start(startDeps()); @@ -423,7 +432,7 @@ describe('SearchService', () => { a: [providerResult('1')], b: [providerResult('2')], }); - registerResultProvider(createProvider('A', providerResults)); + registerResultProvider(createProvider('A', { source: providerResults })); const { find } = service.start(startDeps()); const results = find({ term: 'foobar' }, {}); @@ -438,5 +447,91 @@ describe('SearchService', () => { }); }); }); + + describe('#getSearchableTypes()', () => { + it('returns the types registered by the provider', async () => { + const { registerResultProvider } = service.setup({ + config: createConfig(), + }); + + const provider = createProvider('A', { types: ['type-a', 'type-b'] }); + registerResultProvider(provider); + + const { getSearchableTypes } = service.start(startDeps()); + + const types = await getSearchableTypes(); + + expect(types).toEqual(['type-a', 'type-b']); + }); + + it('returns the types registered by the server', async () => { + fetchServerSearchableTypesMock.mockResolvedValue(['server-a', 'server-b']); + + service.setup({ + config: createConfig(), + }); + + const { getSearchableTypes } = service.start(startDeps()); + + const types = await getSearchableTypes(); + + expect(types).toEqual(['server-a', 'server-b']); + }); + + it('merges the types registered by the providers', async () => { + const { registerResultProvider } = service.setup({ + config: createConfig(), + }); + + const provider1 = createProvider('A', { types: ['type-a', 'type-b'] }); + registerResultProvider(provider1); + + const provider2 = createProvider('B', { types: ['type-c', 'type-d'] }); + registerResultProvider(provider2); + + const { getSearchableTypes } = service.start(startDeps()); + + const types = await getSearchableTypes(); + + expect(types.sort()).toEqual(['type-a', 'type-b', 'type-c', 'type-d']); + }); + + it('merges the types registered by the providers and the server', async () => { + fetchServerSearchableTypesMock.mockResolvedValue(['server-a', 'server-b']); + + const { registerResultProvider } = service.setup({ + config: createConfig(), + }); + + const provider1 = createProvider('A', { types: ['type-a', 'type-b'] }); + registerResultProvider(provider1); + + const { getSearchableTypes } = service.start(startDeps()); + + const types = await getSearchableTypes(); + + expect(types.sort()).toEqual(['server-a', 'server-b', 'type-a', 'type-b']); + }); + + it('removes duplicates', async () => { + fetchServerSearchableTypesMock.mockResolvedValue(['server-a', 'dupe-1']); + + const { registerResultProvider } = service.setup({ + config: createConfig(), + }); + + const provider1 = createProvider('A', { types: ['type-a', 'dupe-1', 'dupe-2'] }); + registerResultProvider(provider1); + + const provider2 = createProvider('B', { types: ['type-b', 'dupe-2'] }); + registerResultProvider(provider2); + + const { getSearchableTypes } = service.start(startDeps()); + + const types = await getSearchableTypes(); + + expect(types.sort()).toEqual(['dupe-1', 'dupe-2', 'server-a', 'type-a', 'type-b']); + }); + }); }); }); diff --git a/x-pack/plugins/global_search/public/services/search_service.ts b/x-pack/plugins/global_search/public/services/search_service.ts index 64bd2fd6c930f..015143d34886f 100644 --- a/x-pack/plugins/global_search/public/services/search_service.ts +++ b/x-pack/plugins/global_search/public/services/search_service.ts @@ -6,6 +6,7 @@ import { merge, Observable, timer, throwError } from 'rxjs'; import { map, takeUntil } from 'rxjs/operators'; +import { uniq } from 'lodash'; import { duration } from 'moment'; import { i18n } from '@kbn/i18n'; import { HttpStart } from 'src/core/public'; @@ -24,6 +25,7 @@ import { GlobalSearchClientConfigType } from '../config'; import { GlobalSearchFindOptions } from './types'; import { getDefaultPreference } from './utils'; import { fetchServerResults } from './fetch_server_results'; +import { fetchServerSearchableTypes } from './fetch_server_searchable_types'; /** @public */ export interface SearchServiceSetup { @@ -75,6 +77,11 @@ export interface SearchServiceStart { params: GlobalSearchFindParams, options: GlobalSearchFindOptions ): Observable; + + /** + * Returns all the searchable types registered by the underlying result providers. + */ + getSearchableTypes(): Promise; } interface SetupDeps { @@ -96,6 +103,7 @@ export class SearchService { private http?: HttpStart; private maxProviderResults = defaultMaxProviderResults; private licenseChecker?: ILicenseChecker; + private serverTypes?: string[]; setup({ config, maxProviderResults = defaultMaxProviderResults }: SetupDeps): SearchServiceSetup { this.config = config; @@ -118,9 +126,25 @@ export class SearchService { return { find: (params, options) => this.performFind(params, options), + getSearchableTypes: () => this.getSearchableTypes(), }; } + private async getSearchableTypes() { + const providerTypes = ( + await Promise.all( + [...this.providers.values()].map((provider) => provider.getSearchableTypes()) + ) + ).flat(); + + // only need to fetch from server once + if (!this.serverTypes) { + this.serverTypes = await fetchServerSearchableTypes(this.http!); + } + + return uniq([...providerTypes, ...this.serverTypes]); + } + private performFind(params: GlobalSearchFindParams, options: GlobalSearchFindOptions) { const licenseState = this.licenseChecker!.getState(); if (!licenseState.valid) { diff --git a/x-pack/plugins/global_search/public/types.ts b/x-pack/plugins/global_search/public/types.ts index 2707a2fded222..7235347d4aa38 100644 --- a/x-pack/plugins/global_search/public/types.ts +++ b/x-pack/plugins/global_search/public/types.ts @@ -13,7 +13,7 @@ import { import { SearchServiceSetup, SearchServiceStart } from './services'; export type GlobalSearchPluginSetup = Pick; -export type GlobalSearchPluginStart = Pick; +export type GlobalSearchPluginStart = Pick; /** * GlobalSearch result provider, to be registered using the {@link GlobalSearchPluginSetup | global search API} @@ -44,4 +44,10 @@ export interface GlobalSearchResultProvider { search: GlobalSearchProviderFindParams, options: GlobalSearchProviderFindOptions ): Observable; + + /** + * Method that should return all the possible {@link GlobalSearchProviderResult.type | type} of results that + * this provider can return. + */ + getSearchableTypes: () => string[] | Promise; } diff --git a/x-pack/plugins/global_search/server/mocks.ts b/x-pack/plugins/global_search/server/mocks.ts index e7c133edf95c8..88be7f6e861a1 100644 --- a/x-pack/plugins/global_search/server/mocks.ts +++ b/x-pack/plugins/global_search/server/mocks.ts @@ -26,12 +26,14 @@ const createStartMock = (): jest.Mocked => { return { find: searchMock.find, + getSearchableTypes: searchMock.getSearchableTypes, }; }; const createRouteHandlerContextMock = (): jest.Mocked => { const handlerContextMock = { find: jest.fn(), + getSearchableTypes: jest.fn(), }; handlerContextMock.find.mockReturnValue(of([])); diff --git a/x-pack/plugins/global_search/server/plugin.ts b/x-pack/plugins/global_search/server/plugin.ts index 87e7f96b34c0c..9d6844dde50f0 100644 --- a/x-pack/plugins/global_search/server/plugin.ts +++ b/x-pack/plugins/global_search/server/plugin.ts @@ -59,6 +59,7 @@ export class GlobalSearchPlugin core.http.registerRouteHandlerContext('globalSearch', (_, req) => { return { find: (term, options) => this.searchServiceStart!.find(term, options, req), + getSearchableTypes: () => this.searchServiceStart!.getSearchableTypes(req), }; }); @@ -75,6 +76,7 @@ export class GlobalSearchPlugin }); return { find: this.searchServiceStart.find, + getSearchableTypes: this.searchServiceStart.getSearchableTypes, }; } diff --git a/x-pack/plugins/global_search/server/routes/get_searchable_types.ts b/x-pack/plugins/global_search/server/routes/get_searchable_types.ts new file mode 100644 index 0000000000000..f9cc69e4a28ae --- /dev/null +++ b/x-pack/plugins/global_search/server/routes/get_searchable_types.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { IRouter } from 'src/core/server'; + +export const registerInternalSearchableTypesRoute = (router: IRouter) => { + router.get( + { + path: '/internal/global_search/searchable_types', + validate: false, + }, + async (ctx, req, res) => { + const types = await ctx.globalSearch!.getSearchableTypes(); + return res.ok({ + body: { + types, + }, + }); + } + ); +}; diff --git a/x-pack/plugins/global_search/server/routes/index.test.ts b/x-pack/plugins/global_search/server/routes/index.test.ts index 64675bc13cb1c..1111f01d13055 100644 --- a/x-pack/plugins/global_search/server/routes/index.test.ts +++ b/x-pack/plugins/global_search/server/routes/index.test.ts @@ -14,7 +14,6 @@ describe('registerRoutes', () => { registerRoutes(router); expect(router.post).toHaveBeenCalledTimes(1); - expect(router.post).toHaveBeenCalledWith( expect.objectContaining({ path: '/internal/global_search/find', @@ -22,7 +21,14 @@ describe('registerRoutes', () => { expect.any(Function) ); - expect(router.get).toHaveBeenCalledTimes(0); + expect(router.get).toHaveBeenCalledTimes(1); + expect(router.get).toHaveBeenCalledWith( + expect.objectContaining({ + path: '/internal/global_search/searchable_types', + }), + expect.any(Function) + ); + expect(router.delete).toHaveBeenCalledTimes(0); expect(router.put).toHaveBeenCalledTimes(0); }); diff --git a/x-pack/plugins/global_search/server/routes/index.ts b/x-pack/plugins/global_search/server/routes/index.ts index 7840b95614993..0eeb443b72b53 100644 --- a/x-pack/plugins/global_search/server/routes/index.ts +++ b/x-pack/plugins/global_search/server/routes/index.ts @@ -6,7 +6,9 @@ import { IRouter } from 'src/core/server'; import { registerInternalFindRoute } from './find'; +import { registerInternalSearchableTypesRoute } from './get_searchable_types'; export const registerRoutes = (router: IRouter) => { registerInternalFindRoute(router); + registerInternalSearchableTypesRoute(router); }; diff --git a/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts b/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts new file mode 100644 index 0000000000000..b3b6862599d6d --- /dev/null +++ b/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import supertest from 'supertest'; +import { UnwrapPromise } from '@kbn/utility-types'; +import { setupServer } from '../../../../../../src/core/server/test_utils'; +import { globalSearchPluginMock } from '../../mocks'; +import { registerInternalSearchableTypesRoute } from '../get_searchable_types'; + +type SetupServerReturn = UnwrapPromise>; +const pluginId = Symbol('globalSearch'); + +describe('GET /internal/global_search/searchable_types', () => { + let server: SetupServerReturn['server']; + let httpSetup: SetupServerReturn['httpSetup']; + let globalSearchHandlerContext: ReturnType< + typeof globalSearchPluginMock.createRouteHandlerContext + >; + + beforeEach(async () => { + ({ server, httpSetup } = await setupServer(pluginId)); + + globalSearchHandlerContext = globalSearchPluginMock.createRouteHandlerContext(); + httpSetup.registerRouteHandlerContext( + pluginId, + 'globalSearch', + () => globalSearchHandlerContext + ); + + const router = httpSetup.createRouter('/'); + + registerInternalSearchableTypesRoute(router); + + await server.start(); + }); + + afterEach(async () => { + await server.stop(); + }); + + it('calls the handler context with correct parameters', async () => { + await supertest(httpSetup.server.listener) + .post('/internal/global_search/searchable_types') + .expect(200); + + expect(globalSearchHandlerContext.getSearchableTypes).toHaveBeenCalledTimes(1); + }); + + it('returns the types returned from the service', async () => { + globalSearchHandlerContext.getSearchableTypes.mockResolvedValue(['type-a', 'type-b']); + + const response = await supertest(httpSetup.server.listener) + .post('/internal/global_search/searchable_types') + .expect(200); + + expect(response.body).toEqual({ + types: ['type-a', 'type-b'], + }); + }); + + it('returns the default error when the observable throws any other error', async () => { + globalSearchHandlerContext.getSearchableTypes.mockRejectedValue(new Error()); + + const response = await supertest(httpSetup.server.listener) + .post('/internal/global_search/searchable_types') + .expect(200); + + expect(response.body).toEqual( + expect.objectContaining({ + message: 'An internal server error occurred.', + statusCode: 500, + }) + ); + }); +}); diff --git a/x-pack/plugins/global_search/server/services/search_service.mock.ts b/x-pack/plugins/global_search/server/services/search_service.mock.ts index eca69148288b9..0aa65e39f026c 100644 --- a/x-pack/plugins/global_search/server/services/search_service.mock.ts +++ b/x-pack/plugins/global_search/server/services/search_service.mock.ts @@ -7,17 +7,21 @@ import { SearchServiceSetup, SearchServiceStart } from './search_service'; import { of } from 'rxjs'; -const createSetupMock = (): jest.Mocked => { - return { +const createSetupMock = () => { + const mock: jest.Mocked = { registerResultProvider: jest.fn(), }; + + return mock; }; -const createStartMock = (): jest.Mocked => { - const mock = { +const createStartMock = () => { + const mock: jest.Mocked = { find: jest.fn(), + getSearchableTypes: jest.fn(), }; mock.find.mockReturnValue(of({ results: [] })); + mock.getSearchableTypes.mockResolvedValue([]); return mock; }; diff --git a/x-pack/plugins/global_search/server/services/search_service.test.ts b/x-pack/plugins/global_search/server/services/search_service.test.ts index c8d656a524e94..b3e4981b35392 100644 --- a/x-pack/plugins/global_search/server/services/search_service.test.ts +++ b/x-pack/plugins/global_search/server/services/search_service.test.ts @@ -36,10 +36,17 @@ describe('SearchService', () => { const createProvider = ( id: string, - source: Observable = of([]) + { + source = of([]), + types = [], + }: { + source?: Observable; + types?: string[] | Promise; + } = {} ): jest.Mocked => ({ id, find: jest.fn().mockImplementation((term, options, context) => source), + getSearchableTypes: jest.fn().mockReturnValue(types), }); const expectedResult = (id: string) => expect.objectContaining({ id }); @@ -122,7 +129,7 @@ describe('SearchService', () => { a: [result('1')], b: [result('2')], }); - registerResultProvider(createProvider('A', providerResults)); + registerResultProvider(createProvider('A', { source: providerResults })); const { find } = service.start({ core: coreStart, licenseChecker }); const results = find({ term: 'foobar' }, {}, request); @@ -142,22 +149,20 @@ describe('SearchService', () => { getTestScheduler().run(({ expectObservable, hot }) => { registerResultProvider( - createProvider( - 'A', - hot('a---d-|', { + createProvider('A', { + source: hot('a---d-|', { a: [result('A1'), result('A2')], d: [result('A3')], - }) - ) + }), + }) ); registerResultProvider( - createProvider( - 'B', - hot('-b-c| ', { + createProvider('B', { + source: hot('-b-c| ', { b: [result('B1')], c: [result('B2'), result('B3')], - }) - ) + }), + }) ); const { find } = service.start({ core: coreStart, licenseChecker }); @@ -183,7 +188,7 @@ describe('SearchService', () => { a: [result('1')], b: [result('2')], }); - registerResultProvider(createProvider('A', providerResults)); + registerResultProvider(createProvider('A', { source: providerResults })); const aborted$ = hot('----a--|', { a: undefined }); @@ -208,7 +213,7 @@ describe('SearchService', () => { b: [result('2')], c: [result('3')], }); - registerResultProvider(createProvider('A', providerResults)); + registerResultProvider(createProvider('A', { source: providerResults })); const { find } = service.start({ core: coreStart, licenseChecker }); const results = find({ term: 'foobar' }, {}, request); @@ -229,22 +234,20 @@ describe('SearchService', () => { getTestScheduler().run(({ expectObservable, hot }) => { registerResultProvider( - createProvider( - 'A', - hot('a---d-|', { + createProvider('A', { + source: hot('a---d-|', { a: [result('A1'), result('A2')], d: [result('A3')], - }) - ) + }), + }) ); registerResultProvider( - createProvider( - 'B', - hot('-b-c| ', { + createProvider('B', { + source: hot('-b-c| ', { b: [result('B1')], c: [result('B2'), result('B3')], - }) - ) + }), + }) ); const { find } = service.start({ core: coreStart, licenseChecker }); @@ -278,7 +281,7 @@ describe('SearchService', () => { url: { path: '/foo', prependBasePath: false }, }); - const provider = createProvider('A', of([resultA, resultB])); + const provider = createProvider('A', { source: of([resultA, resultB]) }); registerResultProvider(provider); const { find } = service.start({ core: coreStart, licenseChecker }); @@ -308,7 +311,7 @@ describe('SearchService', () => { a: [result('1')], b: [result('2')], }); - registerResultProvider(createProvider('A', providerResults)); + registerResultProvider(createProvider('A', { source: providerResults })); const { find } = service.start({ core: coreStart, licenseChecker }); const results = find({ term: 'foobar' }, {}, request); @@ -323,5 +326,77 @@ describe('SearchService', () => { }); }); }); + + describe('#getSearchableTypes()', () => { + it('returns the types registered by the provider', async () => { + const { registerResultProvider } = service.setup({ + config: createConfig(), + basePath, + }); + + const provider = createProvider('A', { types: ['type-a', 'type-b'] }); + registerResultProvider(provider); + + const { getSearchableTypes } = service.start({ core: coreStart, licenseChecker }); + + const types = await getSearchableTypes(request); + + expect(types).toEqual(['type-a', 'type-b']); + }); + + it('supports promises', async () => { + const { registerResultProvider } = service.setup({ + config: createConfig(), + basePath, + }); + + const provider = createProvider('A', { types: Promise.resolve(['type-a', 'type-b']) }); + registerResultProvider(provider); + + const { getSearchableTypes } = service.start({ core: coreStart, licenseChecker }); + + const types = await getSearchableTypes(request); + + expect(types).toEqual(['type-a', 'type-b']); + }); + + it('merges the types registered by the providers', async () => { + const { registerResultProvider } = service.setup({ + config: createConfig(), + basePath, + }); + + const provider1 = createProvider('A', { types: ['type-a', 'type-b'] }); + registerResultProvider(provider1); + + const provider2 = createProvider('B', { types: ['type-c', 'type-d'] }); + registerResultProvider(provider2); + + const { getSearchableTypes } = service.start({ core: coreStart, licenseChecker }); + + const types = await getSearchableTypes(request); + + expect(types.sort()).toEqual(['type-a', 'type-b', 'type-c', 'type-d']); + }); + + it('removes duplicates', async () => { + const { registerResultProvider } = service.setup({ + config: createConfig(), + basePath, + }); + + const provider1 = createProvider('A', { types: ['type-a', 'dupe'] }); + registerResultProvider(provider1); + + const provider2 = createProvider('B', { types: ['type-b', 'dupe'] }); + registerResultProvider(provider2); + + const { getSearchableTypes } = service.start({ core: coreStart, licenseChecker }); + + const types = await getSearchableTypes(request); + + expect(types.sort()).toEqual(['dupe', 'type-a', 'type-b']); + }); + }); }); }); diff --git a/x-pack/plugins/global_search/server/services/search_service.ts b/x-pack/plugins/global_search/server/services/search_service.ts index 9ea62abac704c..88250820861a6 100644 --- a/x-pack/plugins/global_search/server/services/search_service.ts +++ b/x-pack/plugins/global_search/server/services/search_service.ts @@ -6,6 +6,7 @@ import { Observable, timer, merge, throwError } from 'rxjs'; import { map, takeUntil } from 'rxjs/operators'; +import { uniq } from 'lodash'; import { i18n } from '@kbn/i18n'; import { KibanaRequest, CoreStart, IBasePath } from 'src/core/server'; import { @@ -71,6 +72,11 @@ export interface SearchServiceStart { options: GlobalSearchFindOptions, request: KibanaRequest ): Observable; + + /** + * Returns all the searchable types registered by the underlying result providers. + */ + getSearchableTypes(request: KibanaRequest): Promise; } interface SetupDeps { @@ -119,9 +125,20 @@ export class SearchService { this.contextFactory = getContextFactory(core); return { find: (params, options, request) => this.performFind(params, options, request), + getSearchableTypes: (request) => this.getSearchableTypes(request), }; } + private async getSearchableTypes(request: KibanaRequest) { + const context = this.contextFactory!(request); + const allTypes = ( + await Promise.all( + [...this.providers.values()].map((provider) => provider.getSearchableTypes(context)) + ) + ).flat(); + return uniq(allTypes); + } + private performFind( params: GlobalSearchFindParams, options: GlobalSearchFindOptions, diff --git a/x-pack/plugins/global_search/server/types.ts b/x-pack/plugins/global_search/server/types.ts index 0878a965ea8c3..48c40fdb66e13 100644 --- a/x-pack/plugins/global_search/server/types.ts +++ b/x-pack/plugins/global_search/server/types.ts @@ -22,7 +22,7 @@ import { import { SearchServiceSetup, SearchServiceStart } from './services'; export type GlobalSearchPluginSetup = Pick; -export type GlobalSearchPluginStart = Pick; +export type GlobalSearchPluginStart = Pick; /** * globalSearch route handler context. @@ -37,6 +37,10 @@ export interface RouteHandlerGlobalSearchContext { params: GlobalSearchFindParams, options: GlobalSearchFindOptions ): Observable; + /** + * See {@link SearchServiceStart.getSearchableTypes | the getSearchableTypes API} + */ + getSearchableTypes: () => Promise; } /** @@ -114,4 +118,10 @@ export interface GlobalSearchResultProvider { options: GlobalSearchProviderFindOptions, context: GlobalSearchProviderContext ): Observable; + + /** + * Method that should return all the possible {@link GlobalSearchProviderResult.type | type} of results that + * this provider can return. + */ + getSearchableTypes: (context: GlobalSearchProviderContext) => string[] | Promise; } diff --git a/x-pack/plugins/global_search_bar/public/components/search_bar.test.tsx b/x-pack/plugins/global_search_bar/public/components/search_bar.test.tsx index 5ba00c293d213..1ed011d3cc3b1 100644 --- a/x-pack/plugins/global_search_bar/public/components/search_bar.test.tsx +++ b/x-pack/plugins/global_search_bar/public/components/search_bar.test.tsx @@ -11,8 +11,8 @@ import { of, BehaviorSubject } from 'rxjs'; import { filter, map } from 'rxjs/operators'; import { mountWithIntl } from '@kbn/test/jest'; import { applicationServiceMock } from '../../../../../src/core/public/mocks'; -import { GlobalSearchBatchedResults, GlobalSearchResult } from '../../../global_search/public'; import { globalSearchPluginMock } from '../../../global_search/public/mocks'; +import { GlobalSearchBatchedResults, GlobalSearchResult } from '../../../global_search/public'; import { SearchBar } from './search_bar'; type Result = { id: string; type: string } | string; @@ -86,7 +86,7 @@ describe('SearchBar', () => { component = mountWithIntl( { it('supports keyboard shortcuts', () => { mountWithIntl( { component = mountWithIntl( void; taggingApi?: SavedObjectTaggingPluginStart; @@ -43,16 +45,19 @@ interface Props { darkMode: boolean; } -const clearField = (field: HTMLInputElement) => { +const isMac = navigator.platform.toLowerCase().indexOf('mac') >= 0; + +const setFieldValue = (field: HTMLInputElement, value: string) => { const nativeInputValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value'); const nativeInputValueSetter = nativeInputValue ? nativeInputValue.set : undefined; if (nativeInputValueSetter) { - nativeInputValueSetter.call(field, ''); + nativeInputValueSetter.call(field, value); } - field.dispatchEvent(new Event('change')); }; +const clearField = (field: HTMLInputElement) => setFieldValue(field, ''); + const cleanMeta = (str: string) => (str.charAt(0).toUpperCase() + str.slice(1)).replace(/-/g, ' '); const blurEvent = new FocusEvent('blur'); @@ -92,6 +97,19 @@ const resultToOption = (result: GlobalSearchResult): EuiSelectableTemplateSitewi return option; }; +const suggestionToOption = (suggestion: SearchSuggestion): EuiSelectableTemplateSitewideOption => { + const { key, label, description, icon, suggestedSearch } = suggestion; + return { + key, + label, + type: '__suggestion__', + icon: { type: icon }, + suggestion: suggestedSearch, + meta: [{ text: description }], + 'data-test-subj': `nav-search-option`, + }; +}; + export function SearchBar({ globalSearch, taggingApi, @@ -105,16 +123,34 @@ export function SearchBar({ const [searchRef, setSearchRef] = useState(null); const [buttonRef, setButtonRef] = useState(null); const searchSubscription = useRef(null); - const [options, _setOptions] = useState([] as EuiSelectableTemplateSitewideOption[]); - const isMac = navigator.platform.toLowerCase().indexOf('mac') >= 0; + const [options, _setOptions] = useState([]); + const [searchableTypes, setSearchableTypes] = useState([]); + + useEffect(() => { + const fetch = async () => { + const types = await globalSearch.getSearchableTypes(); + setSearchableTypes(types); + }; + fetch(); + }, [globalSearch]); + + const loadSuggestions = useCallback( + (searchTerm: string) => { + return getSuggestions({ + searchTerm, + searchableTypes, + tagCache: taggingApi?.cache, + }); + }, + [taggingApi, searchableTypes] + ); const setOptions = useCallback( - (_options: GlobalSearchResult[]) => { + (_options: GlobalSearchResult[], suggestions: SearchSuggestion[]) => { if (!isMounted()) { return; } - - _setOptions(_options.map(resultToOption)); + _setOptions([...suggestions.map(suggestionToOption), ..._options.map(resultToOption)]); }, [isMounted, _setOptions] ); @@ -127,7 +163,9 @@ export function SearchBar({ searchSubscription.current = null; } - let arr: GlobalSearchResult[] = []; + const suggestions = loadSuggestions(searchValue); + + let aggregatedResults: GlobalSearchResult[] = []; if (searchValue.length !== 0) { trackUiMetric(METRIC_TYPE.COUNT, 'search_request'); } @@ -145,20 +183,20 @@ export function SearchBar({ tags: tagIds, }; - searchSubscription.current = globalSearch(searchParams, {}).subscribe({ + searchSubscription.current = globalSearch.find(searchParams, {}).subscribe({ next: ({ results }) => { if (searchValue.length > 0) { - arr = [...results, ...arr].sort(sortByScore); - setOptions(arr); + aggregatedResults = [...results, ...aggregatedResults].sort(sortByScore); + setOptions(aggregatedResults, suggestions); return; } // if searchbar is empty, filter to only applications and sort alphabetically results = results.filter(({ type }: GlobalSearchResult) => type === 'application'); - arr = [...results, ...arr].sort(sortByTitle); + aggregatedResults = [...results, ...aggregatedResults].sort(sortByTitle); - setOptions(arr); + setOptions(aggregatedResults, suggestions); }, error: () => { // Not doing anything on error right now because it'll either just show the previous @@ -169,7 +207,7 @@ export function SearchBar({ }); }, 350, - [searchValue] + [searchValue, loadSuggestions] ); const onKeyDown = (event: KeyboardEvent) => { @@ -191,7 +229,15 @@ export function SearchBar({ } // @ts-ignore - ts error is "union type is too complex to express" - const { url, type } = selected; + const { url, type, suggestion } = selected; + + // if the type is a suggestion, we change the query on the input and trigger a new search + // by setting the searchValue (only setting the field value does not trigger a search) + if (type === '__suggestion__') { + setFieldValue(searchRef!, suggestion); + setSearchValue(suggestion); + return; + } // errors in tracking should not prevent selection behavior try { diff --git a/x-pack/plugins/global_search_bar/public/plugin.tsx b/x-pack/plugins/global_search_bar/public/plugin.tsx index 0d17bf4612737..80111e7746a75 100644 --- a/x-pack/plugins/global_search_bar/public/plugin.tsx +++ b/x-pack/plugins/global_search_bar/public/plugin.tsx @@ -70,7 +70,7 @@ export class GlobalSearchBarPlugin implements Plugin<{}, {}> { ReactDOM.render( = {}): Tag => ({ + id: 'tag-id', + name: 'some-tag', + description: 'Some tag', + color: '#FF00CC', + ...parts, +}); + +describe('getSuggestions', () => { + let tagCache: ReturnType; + const searchableTypes = ['application', 'dashboard', 'maps']; + + beforeEach(() => { + tagCache = taggingApiMock.createCache(); + + tagCache.getState.mockReturnValue([ + createTag({ + id: 'basic', + name: 'normal', + }), + createTag({ + id: 'caps', + name: 'BAR', + }), + createTag({ + id: 'whitespace', + name: 'white space', + }), + ]); + }); + + describe('tag suggestion', () => { + it('returns a suggestion when matching the name of a tag', () => { + const suggestions = getSuggestions({ + searchTerm: 'normal', + tagCache, + searchableTypes: [], + }); + + expect(suggestions).toHaveLength(1); + expect(suggestions[0]).toEqual( + expect.objectContaining({ + label: 'tag: normal', + suggestedSearch: 'tag:normal', + }) + ); + }); + it('ignores leading or trailing spaces a suggestion when matching the name of a tag', () => { + const suggestions = getSuggestions({ + searchTerm: ' normal ', + tagCache, + searchableTypes: [], + }); + + expect(suggestions).toHaveLength(1); + expect(suggestions[0]).toEqual( + expect.objectContaining({ + label: 'tag: normal', + suggestedSearch: 'tag:normal', + }) + ); + }); + it('does not return suggestions when partially matching', () => { + const suggestions = getSuggestions({ + searchTerm: 'norm', + tagCache, + searchableTypes: [], + }); + + expect(suggestions).toHaveLength(0); + }); + it('ignores the case when matching the tag', () => { + const suggestions = getSuggestions({ + searchTerm: 'baR', + tagCache, + searchableTypes: [], + }); + + expect(suggestions).toHaveLength(1); + expect(suggestions[0]).toEqual( + expect.objectContaining({ + label: 'tag: BAR', + suggestedSearch: 'tag:BAR', + }) + ); + }); + it('escapes the name in the query when containing whitespaces', () => { + const suggestions = getSuggestions({ + searchTerm: 'white space', + tagCache, + searchableTypes: [], + }); + + expect(suggestions).toHaveLength(1); + expect(suggestions[0]).toEqual( + expect.objectContaining({ + label: 'tag: white space', + suggestedSearch: 'tag:"white space"', + }) + ); + }); + }); + + describe('type suggestion', () => { + it('returns a suggestion when matching a searchable type', () => { + const suggestions = getSuggestions({ + searchTerm: 'application', + tagCache, + searchableTypes, + }); + + expect(suggestions).toHaveLength(1); + expect(suggestions[0]).toEqual( + expect.objectContaining({ + label: 'type: application', + suggestedSearch: 'type:application', + }) + ); + }); + it('ignores leading or trailing spaces in the search term', () => { + const suggestions = getSuggestions({ + searchTerm: ' application ', + tagCache, + searchableTypes, + }); + + expect(suggestions).toHaveLength(1); + expect(suggestions[0]).toEqual( + expect.objectContaining({ + label: 'type: application', + suggestedSearch: 'type:application', + }) + ); + }); + it('does not return suggestions when partially matching', () => { + const suggestions = getSuggestions({ + searchTerm: 'appl', + tagCache, + searchableTypes, + }); + + expect(suggestions).toHaveLength(0); + }); + it('ignores the case when matching the type', () => { + const suggestions = getSuggestions({ + searchTerm: 'DASHboard', + tagCache, + searchableTypes, + }); + + expect(suggestions).toHaveLength(1); + expect(suggestions[0]).toEqual( + expect.objectContaining({ + label: 'type: dashboard', + suggestedSearch: 'type:dashboard', + }) + ); + }); + }); +}); diff --git a/x-pack/plugins/global_search_bar/public/suggestions/get_suggestions.ts b/x-pack/plugins/global_search_bar/public/suggestions/get_suggestions.ts new file mode 100644 index 0000000000000..c097e365045af --- /dev/null +++ b/x-pack/plugins/global_search_bar/public/suggestions/get_suggestions.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; +import { ITagsCache } from '../../../../../src/plugins/saved_objects_tagging_oss/public'; + +interface GetSuggestionOptions { + searchTerm: string; + searchableTypes: string[]; + tagCache?: ITagsCache; +} + +export interface SearchSuggestion { + key: string; + label: string; + description: string; + icon: string; + suggestedSearch: string; +} + +export const getSuggestions = ({ + searchTerm, + searchableTypes, + tagCache, +}: GetSuggestionOptions): SearchSuggestion[] => { + const results: SearchSuggestion[] = []; + const suggestionTerm = searchTerm.trim(); + + const matchingType = findIgnoreCase(searchableTypes, suggestionTerm); + if (matchingType) { + const suggestedSearch = escapeIfWhiteSpaces(matchingType); + results.push({ + key: '__type__suggestion__', + label: `type: ${matchingType}`, + icon: 'filter', + description: i18n.translate('xpack.globalSearchBar.suggestions.filterByTypeLabel', { + defaultMessage: 'Filter by type', + }), + suggestedSearch: `type:${suggestedSearch}`, + }); + } + + if (tagCache && searchTerm) { + const matchingTag = tagCache + .getState() + .find((tag) => equalsIgnoreCase(tag.name, suggestionTerm)); + if (matchingTag) { + const suggestedSearch = escapeIfWhiteSpaces(matchingTag.name); + results.push({ + key: '__tag__suggestion__', + label: `tag: ${matchingTag.name}`, + icon: 'tag', + description: i18n.translate('xpack.globalSearchBar.suggestions.filterByTagLabel', { + defaultMessage: 'Filter by tag name', + }), + suggestedSearch: `tag:${suggestedSearch}`, + }); + } + } + + return results; +}; + +const findIgnoreCase = (array: string[], target: string) => { + for (const item of array) { + if (equalsIgnoreCase(item, target)) { + return item; + } + } + return undefined; +}; + +const equalsIgnoreCase = (a: string, b: string) => a.toLowerCase() === b.toLowerCase(); + +const escapeIfWhiteSpaces = (term: string) => { + if (/\s/g.test(term)) { + return `"${term}"`; + } + return term; +}; diff --git a/x-pack/plugins/global_search_bar/public/suggestions/index.ts b/x-pack/plugins/global_search_bar/public/suggestions/index.ts new file mode 100644 index 0000000000000..aa1402a93692b --- /dev/null +++ b/x-pack/plugins/global_search_bar/public/suggestions/index.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { getSuggestions, SearchSuggestion } from './get_suggestions'; diff --git a/x-pack/plugins/global_search_providers/public/providers/application.test.ts b/x-pack/plugins/global_search_providers/public/providers/application.test.ts index 7beed42de4c4f..dadcf626ace4a 100644 --- a/x-pack/plugins/global_search_providers/public/providers/application.test.ts +++ b/x-pack/plugins/global_search_providers/public/providers/application.test.ts @@ -71,205 +71,228 @@ describe('applicationResultProvider', () => { expect(provider.id).toBe('application'); }); - it('calls `getAppResults` with the term and the list of apps', async () => { - application.applications$ = of( - createAppMap([ - createApp({ id: 'app1', title: 'App 1' }), - createApp({ id: 'app2', title: 'App 2' }), - createApp({ id: 'app3', title: 'App 3' }), - ]) - ); - const provider = createApplicationResultProvider(Promise.resolve(application)); - - await provider.find({ term: 'term' }, defaultOption).toPromise(); - - expect(getAppResultsMock).toHaveBeenCalledTimes(1); - expect(getAppResultsMock).toHaveBeenCalledWith('term', [ - expectApp('app1'), - expectApp('app2'), - expectApp('app3'), - ]); - }); - - it('calls `getAppResults` when filtering by type with `application` included', async () => { - application.applications$ = of( - createAppMap([ - createApp({ id: 'app1', title: 'App 1' }), - createApp({ id: 'app2', title: 'App 2' }), - ]) - ); - const provider = createApplicationResultProvider(Promise.resolve(application)); - - await provider - .find({ term: 'term', types: ['dashboard', 'application'] }, defaultOption) - .toPromise(); + describe('#find', () => { + it('calls `getAppResults` with the term and the list of apps', async () => { + application.applications$ = of( + createAppMap([ + createApp({ id: 'app1', title: 'App 1' }), + createApp({ id: 'app2', title: 'App 2' }), + createApp({ id: 'app3', title: 'App 3' }), + ]) + ); + const provider = createApplicationResultProvider(Promise.resolve(application)); + + await provider.find({ term: 'term' }, defaultOption).toPromise(); + + expect(getAppResultsMock).toHaveBeenCalledTimes(1); + expect(getAppResultsMock).toHaveBeenCalledWith('term', [ + expectApp('app1'), + expectApp('app2'), + expectApp('app3'), + ]); + }); - expect(getAppResultsMock).toHaveBeenCalledTimes(1); - expect(getAppResultsMock).toHaveBeenCalledWith('term', [expectApp('app1'), expectApp('app2')]); - }); + it('calls `getAppResults` when filtering by type with `application` included', async () => { + application.applications$ = of( + createAppMap([ + createApp({ id: 'app1', title: 'App 1' }), + createApp({ id: 'app2', title: 'App 2' }), + ]) + ); + const provider = createApplicationResultProvider(Promise.resolve(application)); + + await provider + .find({ term: 'term', types: ['dashboard', 'application'] }, defaultOption) + .toPromise(); + + expect(getAppResultsMock).toHaveBeenCalledTimes(1); + expect(getAppResultsMock).toHaveBeenCalledWith('term', [ + expectApp('app1'), + expectApp('app2'), + ]); + }); - it('does not call `getAppResults` and return no results when filtering by type with `application` not included', async () => { - application.applications$ = of( - createAppMap([ - createApp({ id: 'app1', title: 'App 1' }), - createApp({ id: 'app2', title: 'App 2' }), - createApp({ id: 'app3', title: 'App 3' }), - ]) - ); - const provider = createApplicationResultProvider(Promise.resolve(application)); + it('does not call `getAppResults` and return no results when filtering by type with `application` not included', async () => { + application.applications$ = of( + createAppMap([ + createApp({ id: 'app1', title: 'App 1' }), + createApp({ id: 'app2', title: 'App 2' }), + createApp({ id: 'app3', title: 'App 3' }), + ]) + ); + const provider = createApplicationResultProvider(Promise.resolve(application)); + + const results = await provider + .find({ term: 'term', types: ['dashboard', 'map'] }, defaultOption) + .toPromise(); + + expect(getAppResultsMock).not.toHaveBeenCalled(); + expect(results).toEqual([]); + }); - const results = await provider - .find({ term: 'term', types: ['dashboard', 'map'] }, defaultOption) - .toPromise(); + it('does not call `getAppResults` and returns no results when filtering by tag', async () => { + application.applications$ = of( + createAppMap([ + createApp({ id: 'app1', title: 'App 1' }), + createApp({ id: 'app2', title: 'App 2' }), + createApp({ id: 'app3', title: 'App 3' }), + ]) + ); + const provider = createApplicationResultProvider(Promise.resolve(application)); + + const results = await provider + .find({ term: 'term', tags: ['some-tag-id'] }, defaultOption) + .toPromise(); + + expect(getAppResultsMock).not.toHaveBeenCalled(); + expect(results).toEqual([]); + }); - expect(getAppResultsMock).not.toHaveBeenCalled(); - expect(results).toEqual([]); - }); + it('ignores inaccessible apps', async () => { + application.applications$ = of( + createAppMap([ + createApp({ id: 'app1', title: 'App 1' }), + createApp({ id: 'disabled', title: 'disabled', status: AppStatus.inaccessible }), + ]) + ); + const provider = createApplicationResultProvider(Promise.resolve(application)); + await provider.find({ term: 'term' }, defaultOption).toPromise(); + + expect(getAppResultsMock).toHaveBeenCalledWith('term', [expectApp('app1')]); + }); - it('does not call `getAppResults` and returns no results when filtering by tag', async () => { - application.applications$ = of( - createAppMap([ - createApp({ id: 'app1', title: 'App 1' }), - createApp({ id: 'app2', title: 'App 2' }), - createApp({ id: 'app3', title: 'App 3' }), - ]) - ); - const provider = createApplicationResultProvider(Promise.resolve(application)); + it('ignores apps with non-visible navlink', async () => { + application.applications$ = of( + createAppMap([ + createApp({ id: 'app1', title: 'App 1', navLinkStatus: AppNavLinkStatus.visible }), + createApp({ + id: 'disabled', + title: 'disabled', + navLinkStatus: AppNavLinkStatus.disabled, + }), + createApp({ id: 'hidden', title: 'hidden', navLinkStatus: AppNavLinkStatus.hidden }), + ]) + ); + const provider = createApplicationResultProvider(Promise.resolve(application)); + await provider.find({ term: 'term' }, defaultOption).toPromise(); + + expect(getAppResultsMock).toHaveBeenCalledWith('term', [expectApp('app1')]); + }); - const results = await provider - .find({ term: 'term', tags: ['some-tag-id'] }, defaultOption) - .toPromise(); + it('ignores chromeless apps', async () => { + application.applications$ = of( + createAppMap([ + createApp({ id: 'app1', title: 'App 1' }), + createApp({ id: 'chromeless', title: 'chromeless', chromeless: true }), + ]) + ); - expect(getAppResultsMock).not.toHaveBeenCalled(); - expect(results).toEqual([]); - }); + const provider = createApplicationResultProvider(Promise.resolve(application)); + await provider.find({ term: 'term' }, defaultOption).toPromise(); - it('ignores inaccessible apps', async () => { - application.applications$ = of( - createAppMap([ - createApp({ id: 'app1', title: 'App 1' }), - createApp({ id: 'disabled', title: 'disabled', status: AppStatus.inaccessible }), - ]) - ); - const provider = createApplicationResultProvider(Promise.resolve(application)); - await provider.find({ term: 'term' }, defaultOption).toPromise(); + expect(getAppResultsMock).toHaveBeenCalledWith('term', [expectApp('app1')]); + }); - expect(getAppResultsMock).toHaveBeenCalledWith('term', [expectApp('app1')]); - }); + it('sorts the results returned by `getAppResults`', async () => { + getAppResultsMock.mockReturnValue([ + createResult({ id: 'r60', score: 60 }), + createResult({ id: 'r100', score: 100 }), + createResult({ id: 'r50', score: 50 }), + createResult({ id: 'r75', score: 75 }), + ]); + + const provider = createApplicationResultProvider(Promise.resolve(application)); + const results = await provider.find({ term: 'term' }, defaultOption).toPromise(); + + expect(results).toEqual([ + expectResult('r100'), + expectResult('r75'), + expectResult('r60'), + expectResult('r50'), + ]); + }); - it('ignores apps with non-visible navlink', async () => { - application.applications$ = of( - createAppMap([ - createApp({ id: 'app1', title: 'App 1', navLinkStatus: AppNavLinkStatus.visible }), - createApp({ id: 'disabled', title: 'disabled', navLinkStatus: AppNavLinkStatus.disabled }), - createApp({ id: 'hidden', title: 'hidden', navLinkStatus: AppNavLinkStatus.hidden }), - ]) - ); - const provider = createApplicationResultProvider(Promise.resolve(application)); - await provider.find({ term: 'term' }, defaultOption).toPromise(); + it('only returns the highest `maxResults` results', async () => { + getAppResultsMock.mockReturnValue([ + createResult({ id: 'r60', score: 60 }), + createResult({ id: 'r100', score: 100 }), + createResult({ id: 'r50', score: 50 }), + createResult({ id: 'r75', score: 75 }), + ]); - expect(getAppResultsMock).toHaveBeenCalledWith('term', [expectApp('app1')]); - }); + const provider = createApplicationResultProvider(Promise.resolve(application)); - it('ignores chromeless apps', async () => { - application.applications$ = of( - createAppMap([ - createApp({ id: 'app1', title: 'App 1' }), - createApp({ id: 'chromeless', title: 'chromeless', chromeless: true }), - ]) - ); + const options = { + ...defaultOption, + maxResults: 2, + }; + const results = await provider.find({ term: 'term' }, options).toPromise(); - const provider = createApplicationResultProvider(Promise.resolve(application)); - await provider.find({ term: 'term' }, defaultOption).toPromise(); + expect(results).toEqual([expectResult('r100'), expectResult('r75')]); + }); - expect(getAppResultsMock).toHaveBeenCalledWith('term', [expectApp('app1')]); - }); + it('only emits once, even if `application$` emits multiple times', () => { + getTestScheduler().run(({ hot, expectObservable }) => { + const appMap = createAppMap([createApp({ id: 'app1', title: 'App 1' })]); - it('sorts the results returned by `getAppResults`', async () => { - getAppResultsMock.mockReturnValue([ - createResult({ id: 'r60', score: 60 }), - createResult({ id: 'r100', score: 100 }), - createResult({ id: 'r50', score: 50 }), - createResult({ id: 'r75', score: 75 }), - ]); + application.applications$ = hot('--a---b', { a: appMap, b: appMap }); - const provider = createApplicationResultProvider(Promise.resolve(application)); - const results = await provider.find({ term: 'term' }, defaultOption).toPromise(); - - expect(results).toEqual([ - expectResult('r100'), - expectResult('r75'), - expectResult('r60'), - expectResult('r50'), - ]); - }); + // test scheduler doesnt play well with promises. need to workaround by passing + // an observable instead. Behavior with promise is asserted in previous tests of the suite + const applicationPromise = (hot('a', { + a: application, + }) as unknown) as Promise; - it('only returns the highest `maxResults` results', async () => { - getAppResultsMock.mockReturnValue([ - createResult({ id: 'r60', score: 60 }), - createResult({ id: 'r100', score: 100 }), - createResult({ id: 'r50', score: 50 }), - createResult({ id: 'r75', score: 75 }), - ]); + const provider = createApplicationResultProvider(applicationPromise); - const provider = createApplicationResultProvider(Promise.resolve(application)); + const options = { + ...defaultOption, + aborted$: hot('|'), + }; - const options = { - ...defaultOption, - maxResults: 2, - }; - const results = await provider.find({ term: 'term' }, options).toPromise(); + const resultObs = provider.find({ term: 'term' }, options); - expect(results).toEqual([expectResult('r100'), expectResult('r75')]); - }); + expectObservable(resultObs).toBe('--(a|)', { a: [] }); + }); + }); - it('only emits once, even if `application$` emits multiple times', () => { - getTestScheduler().run(({ hot, expectObservable }) => { - const appMap = createAppMap([createApp({ id: 'app1', title: 'App 1' })]); + it('only emits results until `aborted$` emits', () => { + getTestScheduler().run(({ hot, expectObservable }) => { + const appMap = createAppMap([createApp({ id: 'app1', title: 'App 1' })]); - application.applications$ = hot('--a---b', { a: appMap, b: appMap }); + application.applications$ = hot('---a', { a: appMap, b: appMap }); - // test scheduler doesnt play well with promises. need to workaround by passing - // an observable instead. Behavior with promise is asserted in previous tests of the suite - const applicationPromise = (hot('a', { - a: application, - }) as unknown) as Promise; + // test scheduler doesnt play well with promises. need to workaround by passing + // an observable instead. Behavior with promise is asserted in previous tests of the suite + const applicationPromise = (hot('a', { + a: application, + }) as unknown) as Promise; - const provider = createApplicationResultProvider(applicationPromise); + const provider = createApplicationResultProvider(applicationPromise); - const options = { - ...defaultOption, - aborted$: hot('|'), - }; + const options = { + ...defaultOption, + aborted$: hot('-(a|)', { a: undefined }), + }; - const resultObs = provider.find({ term: 'term' }, options); + const resultObs = provider.find({ term: 'term' }, options); - expectObservable(resultObs).toBe('--(a|)', { a: [] }); + expectObservable(resultObs).toBe('-|'); + }); }); }); - it('only emits results until `aborted$` emits', () => { - getTestScheduler().run(({ hot, expectObservable }) => { - const appMap = createAppMap([createApp({ id: 'app1', title: 'App 1' })]); - - application.applications$ = hot('---a', { a: appMap, b: appMap }); - - // test scheduler doesnt play well with promises. need to workaround by passing - // an observable instead. Behavior with promise is asserted in previous tests of the suite - const applicationPromise = (hot('a', { - a: application, - }) as unknown) as Promise; - - const provider = createApplicationResultProvider(applicationPromise); - - const options = { - ...defaultOption, - aborted$: hot('-(a|)', { a: undefined }), - }; - - const resultObs = provider.find({ term: 'term' }, options); - - expectObservable(resultObs).toBe('-|'); + describe('#getSearchableTypes', () => { + it('returns only the `application` type', async () => { + application.applications$ = of( + createAppMap([ + createApp({ id: 'app1', title: 'App 1' }), + createApp({ id: 'app2', title: 'App 2' }), + ]) + ); + const provider = createApplicationResultProvider(Promise.resolve(application)); + + expect(await provider.getSearchableTypes()).toEqual(['application']); }); }); }); diff --git a/x-pack/plugins/global_search_providers/public/providers/application.ts b/x-pack/plugins/global_search_providers/public/providers/application.ts index fd6eb0dc1878b..5b4c58161c0ae 100644 --- a/x-pack/plugins/global_search_providers/public/providers/application.ts +++ b/x-pack/plugins/global_search_providers/public/providers/application.ts @@ -10,6 +10,8 @@ import { ApplicationStart } from 'src/core/public'; import { GlobalSearchResultProvider } from '../../../global_search/public'; import { getAppResults } from './get_app_results'; +const applicationType = 'application'; + export const createApplicationResultProvider = ( applicationPromise: Promise ): GlobalSearchResultProvider => { @@ -27,7 +29,7 @@ export const createApplicationResultProvider = ( return { id: 'application', find: ({ term, types, tags }, { aborted$, maxResults }) => { - if (tags || (types && !types.includes('application'))) { + if (tags || (types && !types.includes(applicationType))) { return of([]); } return searchableApps$.pipe( @@ -39,5 +41,6 @@ export const createApplicationResultProvider = ( }) ); }, + getSearchableTypes: () => [applicationType], }; }; diff --git a/x-pack/plugins/global_search_providers/server/providers/saved_objects/provider.test.ts b/x-pack/plugins/global_search_providers/server/providers/saved_objects/provider.test.ts index da9276278dbbf..5d24b33f2619e 100644 --- a/x-pack/plugins/global_search_providers/server/providers/saved_objects/provider.test.ts +++ b/x-pack/plugins/global_search_providers/server/providers/saved_objects/provider.test.ts @@ -115,117 +115,127 @@ describe('savedObjectsResultProvider', () => { expect(provider.id).toBe('savedObjects'); }); - it('calls `savedObjectClient.find` with the correct parameters', async () => { - await provider.find({ term: 'term' }, defaultOption, context).toPromise(); - - expect(context.core.savedObjects.client.find).toHaveBeenCalledTimes(1); - expect(context.core.savedObjects.client.find).toHaveBeenCalledWith({ - page: 1, - perPage: defaultOption.maxResults, - search: 'term*', - preference: 'pref', - searchFields: ['title', 'description'], - type: ['typeA', 'typeB'], + describe('#find()', () => { + it('calls `savedObjectClient.find` with the correct parameters', async () => { + await provider.find({ term: 'term' }, defaultOption, context).toPromise(); + + expect(context.core.savedObjects.client.find).toHaveBeenCalledTimes(1); + expect(context.core.savedObjects.client.find).toHaveBeenCalledWith({ + page: 1, + perPage: defaultOption.maxResults, + search: 'term*', + preference: 'pref', + searchFields: ['title', 'description'], + type: ['typeA', 'typeB'], + }); }); - }); - it('filters searchable types depending on the `types` parameter', async () => { - await provider.find({ term: 'term', types: ['typeA'] }, defaultOption, context).toPromise(); - - expect(context.core.savedObjects.client.find).toHaveBeenCalledTimes(1); - expect(context.core.savedObjects.client.find).toHaveBeenCalledWith({ - page: 1, - perPage: defaultOption.maxResults, - search: 'term*', - preference: 'pref', - searchFields: ['title'], - type: ['typeA'], + it('filters searchable types depending on the `types` parameter', async () => { + await provider.find({ term: 'term', types: ['typeA'] }, defaultOption, context).toPromise(); + + expect(context.core.savedObjects.client.find).toHaveBeenCalledTimes(1); + expect(context.core.savedObjects.client.find).toHaveBeenCalledWith({ + page: 1, + perPage: defaultOption.maxResults, + search: 'term*', + preference: 'pref', + searchFields: ['title'], + type: ['typeA'], + }); }); - }); - it('ignore the case for the `types` parameter', async () => { - await provider.find({ term: 'term', types: ['TyPEa'] }, defaultOption, context).toPromise(); - - expect(context.core.savedObjects.client.find).toHaveBeenCalledTimes(1); - expect(context.core.savedObjects.client.find).toHaveBeenCalledWith({ - page: 1, - perPage: defaultOption.maxResults, - search: 'term*', - preference: 'pref', - searchFields: ['title'], - type: ['typeA'], + it('ignore the case for the `types` parameter', async () => { + await provider.find({ term: 'term', types: ['TyPEa'] }, defaultOption, context).toPromise(); + + expect(context.core.savedObjects.client.find).toHaveBeenCalledTimes(1); + expect(context.core.savedObjects.client.find).toHaveBeenCalledWith({ + page: 1, + perPage: defaultOption.maxResults, + search: 'term*', + preference: 'pref', + searchFields: ['title'], + type: ['typeA'], + }); }); - }); - it('calls `savedObjectClient.find` with the correct references when the `tags` option is set', async () => { - await provider - .find({ term: 'term', tags: ['tag-id-1', 'tag-id-2'] }, defaultOption, context) - .toPromise(); - - expect(context.core.savedObjects.client.find).toHaveBeenCalledTimes(1); - expect(context.core.savedObjects.client.find).toHaveBeenCalledWith({ - page: 1, - perPage: defaultOption.maxResults, - search: 'term*', - preference: 'pref', - searchFields: ['title', 'description'], - hasReference: [ - { type: 'tag', id: 'tag-id-1' }, - { type: 'tag', id: 'tag-id-2' }, - ], - type: ['typeA', 'typeB'], + it('calls `savedObjectClient.find` with the correct references when the `tags` option is set', async () => { + await provider + .find({ term: 'term', tags: ['tag-id-1', 'tag-id-2'] }, defaultOption, context) + .toPromise(); + + expect(context.core.savedObjects.client.find).toHaveBeenCalledTimes(1); + expect(context.core.savedObjects.client.find).toHaveBeenCalledWith({ + page: 1, + perPage: defaultOption.maxResults, + search: 'term*', + preference: 'pref', + searchFields: ['title', 'description'], + hasReference: [ + { type: 'tag', id: 'tag-id-1' }, + { type: 'tag', id: 'tag-id-2' }, + ], + type: ['typeA', 'typeB'], + }); }); - }); - it('does not call `savedObjectClient.find` if all params are empty', async () => { - const results = await provider.find({}, defaultOption, context).pipe(toArray()).toPromise(); + it('does not call `savedObjectClient.find` if all params are empty', async () => { + const results = await provider.find({}, defaultOption, context).pipe(toArray()).toPromise(); - expect(context.core.savedObjects.client.find).not.toHaveBeenCalled(); - expect(results).toEqual([[]]); - }); + expect(context.core.savedObjects.client.find).not.toHaveBeenCalled(); + expect(results).toEqual([[]]); + }); - it('converts the saved objects to results', async () => { - context.core.savedObjects.client.find.mockResolvedValue( - createFindResponse([ - createObject({ id: 'resultA', type: 'typeA', score: 50 }, { title: 'titleA' }), - createObject({ id: 'resultB', type: 'typeB', score: 78 }, { description: 'titleB' }), - ]) - ); + it('converts the saved objects to results', async () => { + context.core.savedObjects.client.find.mockResolvedValue( + createFindResponse([ + createObject({ id: 'resultA', type: 'typeA', score: 50 }, { title: 'titleA' }), + createObject({ id: 'resultB', type: 'typeB', score: 78 }, { description: 'titleB' }), + ]) + ); - const results = await provider.find({ term: 'term' }, defaultOption, context).toPromise(); - expect(results).toEqual([ - { - id: 'resultA', - title: 'titleA', - type: 'typeA', - url: '/type-a/resultA', - score: 50, - }, - { - id: 'resultB', - title: 'titleB', - type: 'typeB', - url: '/type-b/resultB', - score: 78, - }, - ]); - }); + const results = await provider.find({ term: 'term' }, defaultOption, context).toPromise(); + expect(results).toEqual([ + { + id: 'resultA', + title: 'titleA', + type: 'typeA', + url: '/type-a/resultA', + score: 50, + }, + { + id: 'resultB', + title: 'titleB', + type: 'typeB', + url: '/type-b/resultB', + score: 78, + }, + ]); + }); - it('only emits results until `aborted$` emits', () => { - getTestScheduler().run(({ hot, expectObservable }) => { - // test scheduler doesnt play well with promises. need to workaround by passing - // an observable instead. Behavior with promise is asserted in previous tests of the suite - context.core.savedObjects.client.find.mockReturnValue( - hot('---a', { a: createFindResponse([]) }) as any - ); + it('only emits results until `aborted$` emits', () => { + getTestScheduler().run(({ hot, expectObservable }) => { + // test scheduler doesnt play well with promises. need to workaround by passing + // an observable instead. Behavior with promise is asserted in previous tests of the suite + context.core.savedObjects.client.find.mockReturnValue( + hot('---a', { a: createFindResponse([]) }) as any + ); + + const resultObs = provider.find( + { term: 'term' }, + { ...defaultOption, aborted$: hot('-(a|)', { a: undefined }) }, + context + ); + + expectObservable(resultObs).toBe('-|'); + }); + }); + }); - const resultObs = provider.find( - { term: 'term' }, - { ...defaultOption, aborted$: hot('-(a|)', { a: undefined }) }, - context - ); + describe('#getSearchableTypes', () => { + it('returns the searchable saved object types', async () => { + const types = await provider.getSearchableTypes(context); - expectObservable(resultObs).toBe('-|'); + expect(types.sort()).toEqual(['typeA', 'typeB']); }); }); }); diff --git a/x-pack/plugins/global_search_providers/server/providers/saved_objects/provider.ts b/x-pack/plugins/global_search_providers/server/providers/saved_objects/provider.ts index 3e2c42e7896fd..489e8f71c2d53 100644 --- a/x-pack/plugins/global_search_providers/server/providers/saved_objects/provider.ts +++ b/x-pack/plugins/global_search_providers/server/providers/saved_objects/provider.ts @@ -6,7 +6,7 @@ import { from, combineLatest, of } from 'rxjs'; import { map, takeUntil, first } from 'rxjs/operators'; -import { SavedObjectsFindOptionsReference } from 'src/core/server'; +import { SavedObjectsFindOptionsReference, ISavedObjectTypeRegistry } from 'src/core/server'; import { GlobalSearchResultProvider } from '../../../../global_search/server'; import { mapToResults } from './map_object_to_result'; @@ -23,10 +23,7 @@ export const createSavedObjectsResultProvider = (): GlobalSearchResultProvider = savedObjects: { client, typeRegistry }, } = core; - const searchableTypes = typeRegistry - .getVisibleTypes() - .filter(types ? (type) => includeIgnoreCase(types, type.name) : () => true) - .filter((type) => type.management?.defaultSearchField && type.management?.getInAppUrl); + const searchableTypes = getSearchableTypes(typeRegistry, types); const searchFields = uniq( searchableTypes.map((type) => type.management!.defaultSearchField!) @@ -51,9 +48,21 @@ export const createSavedObjectsResultProvider = (): GlobalSearchResultProvider = map(([res, cap]) => mapToResults(res.saved_objects, typeRegistry, cap)) ); }, + getSearchableTypes: ({ core }) => { + const { + savedObjects: { typeRegistry }, + } = core; + return getSearchableTypes(typeRegistry).map((type) => type.name); + }, }; }; +const getSearchableTypes = (typeRegistry: ISavedObjectTypeRegistry, types?: string[]) => + typeRegistry + .getVisibleTypes() + .filter(types ? (type) => includeIgnoreCase(types, type.name) : () => true) + .filter((type) => type.management?.defaultSearchField && type.management?.getInAppUrl); + const uniq = (values: T[]): T[] => [...new Set(values)]; const includeIgnoreCase = (list: string[], item: string) => diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/components/edit_policy.test.tsx b/x-pack/plugins/index_lifecycle_management/__jest__/components/edit_policy.test.tsx index 65952e81ae0ff..32964ab2ce84d 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/components/edit_policy.test.tsx +++ b/x-pack/plugins/index_lifecycle_management/__jest__/components/edit_policy.test.tsx @@ -324,7 +324,7 @@ describe('edit policy', () => { }); }); describe('hot phase', () => { - test('should show errors when trying to save with no max size and no max age', async () => { + test('should show errors when trying to save with no max size, no max age and no max docs', async () => { const rendered = mountWithIntl(component); expect(findTestSubject(rendered, 'rolloverSettingsRequired').exists()).toBeFalsy(); await setPolicyName(rendered, 'mypolicy'); @@ -338,6 +338,11 @@ describe('edit policy', () => { maxAgeInput.simulate('change', { target: { value: '' } }); }); waitForFormLibValidation(rendered); + const maxDocsInput = findTestSubject(rendered, 'hot-selectedMaxDocuments'); + await act(async () => { + maxDocsInput.simulate('change', { target: { value: '' } }); + }); + waitForFormLibValidation(rendered); await save(rendered); expect(findTestSubject(rendered, 'rolloverSettingsRequired').exists()).toBeTruthy(); }); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/hot_phase/hot_phase.tsx b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/hot_phase/hot_phase.tsx index e86bbd9e747bc..5ce4fae596e8e 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/hot_phase/hot_phase.tsx +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/hot_phase/hot_phase.tsx @@ -24,7 +24,7 @@ import { useFormData, UseField, SelectField, NumericField } from '../../../../.. import { i18nTexts } from '../../../i18n_texts'; -import { ROLLOVER_EMPTY_VALIDATION, useConfigurationIssues } from '../../../form'; +import { ROLLOVER_EMPTY_VALIDATION } from '../../../form'; import { useEditPolicyContext } from '../../../edit_policy_context'; @@ -51,8 +51,6 @@ export const HotPhase: FunctionComponent = () => { const isRolloverEnabled = get(formData, useRolloverPath); const [showEmptyRolloverFieldsError, setShowEmptyRolloverFieldsError] = useState(false); - const { isUsingSearchableSnapshotInHotPhase } = useConfigurationIssues(); - return ( <> { {(field) => { const showErrorCallout = field.errors.some( - (e) => e.validationType === ROLLOVER_EMPTY_VALIDATION + (e) => e.code === ROLLOVER_EMPTY_VALIDATION ); if (showErrorCallout !== showEmptyRolloverFieldsError) { setShowEmptyRolloverFieldsError(showErrorCallout); @@ -236,8 +234,8 @@ export const HotPhase: FunctionComponent = () => { {isRolloverEnabled && ( <> + {} {license.canUseSearchableSnapshot() && } - {!isUsingSearchableSnapshotInHotPhase && } )} diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/schema.ts b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/schema.ts index fa9def6864be0..6485122771a46 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/schema.ts +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/schema.ts @@ -8,6 +8,9 @@ import { i18n } from '@kbn/i18n'; import { FormSchema, fieldValidators } from '../../../../shared_imports'; import { defaultSetPriority, defaultPhaseIndexPriority } from '../../../constants'; +import { ROLLOVER_FORM_PATHS } from '../constants'; + +const rolloverFormPaths = Object.values(ROLLOVER_FORM_PATHS); import { FormInternal } from '../types'; @@ -127,6 +130,7 @@ export const schema: FormSchema = { validator: ifExistsNumberGreaterThanZero, }, ], + fieldsToValidateOnChange: rolloverFormPaths, }, max_docs: { label: i18n.translate('xpack.indexLifecycleMgmt.hotPhase.maximumDocumentsLabel', { @@ -141,6 +145,7 @@ export const schema: FormSchema = { }, ], serializer: serializers.stringToNumber, + fieldsToValidateOnChange: rolloverFormPaths, }, max_size: { label: i18n.translate('xpack.indexLifecycleMgmt.hotPhase.maximumIndexSizeLabel', { @@ -154,6 +159,7 @@ export const schema: FormSchema = { validator: ifExistsNumberGreaterThanZero, }, ], + fieldsToValidateOnChange: rolloverFormPaths, }, }, forcemerge: { diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/validations.ts b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/validations.ts index f2e26a552efc9..a5d7d68d21915 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/validations.ts +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/validations.ts @@ -56,33 +56,31 @@ export const ROLLOVER_EMPTY_VALIDATION = 'ROLLOVER_EMPTY_VALIDATION'; * This validator checks that and updates form values by setting errors states imperatively to * indicate this error state. */ -export const rolloverThresholdsValidator: ValidationFunc = ({ form }) => { +export const rolloverThresholdsValidator: ValidationFunc = ({ form, path }) => { const fields = form.getFields(); if ( !( - fields[ROLLOVER_FORM_PATHS.maxAge].value || - fields[ROLLOVER_FORM_PATHS.maxDocs].value || - fields[ROLLOVER_FORM_PATHS.maxSize].value + fields[ROLLOVER_FORM_PATHS.maxAge]?.value || + fields[ROLLOVER_FORM_PATHS.maxDocs]?.value || + fields[ROLLOVER_FORM_PATHS.maxSize]?.value ) ) { - fields[ROLLOVER_FORM_PATHS.maxAge].setErrors([ - { - validationType: ROLLOVER_EMPTY_VALIDATION, + if (path === ROLLOVER_FORM_PATHS.maxAge) { + return { + code: ROLLOVER_EMPTY_VALIDATION, message: i18nTexts.editPolicy.errors.maximumAgeRequiredMessage, - }, - ]); - fields[ROLLOVER_FORM_PATHS.maxDocs].setErrors([ - { - validationType: ROLLOVER_EMPTY_VALIDATION, + }; + } else if (path === ROLLOVER_FORM_PATHS.maxDocs) { + return { + code: ROLLOVER_EMPTY_VALIDATION, message: i18nTexts.editPolicy.errors.maximumDocumentsRequiredMessage, - }, - ]); - fields[ROLLOVER_FORM_PATHS.maxSize].setErrors([ - { - validationType: ROLLOVER_EMPTY_VALIDATION, + }; + } else { + return { + code: ROLLOVER_EMPTY_VALIDATION, message: i18nTexts.editPolicy.errors.maximumSizeRequiredMessage, - }, - ]); + }; + } } else { fields[ROLLOVER_FORM_PATHS.maxAge].clearErrors(ROLLOVER_EMPTY_VALIDATION); fields[ROLLOVER_FORM_PATHS.maxDocs].clearErrors(ROLLOVER_EMPTY_VALIDATION); diff --git a/x-pack/plugins/infra/public/apps/common_providers.tsx b/x-pack/plugins/infra/public/apps/common_providers.tsx index fc82f4bf6cb00..e66c54745ca51 100644 --- a/x-pack/plugins/infra/public/apps/common_providers.tsx +++ b/x-pack/plugins/infra/public/apps/common_providers.tsx @@ -5,7 +5,7 @@ */ import { ApolloClient } from 'apollo-client'; -import { CoreStart } from 'kibana/public'; +import { AppMountParameters, CoreStart } from 'kibana/public'; import React, { useMemo } from 'react'; import { useUiSetting$ } from '../../../../../src/plugins/kibana_react/public'; import { EuiThemeProvider } from '../../../observability/public'; @@ -13,20 +13,24 @@ import { TriggersAndActionsUIPublicPluginStart } from '../../../triggers_actions import { createKibanaContextForPlugin } from '../hooks/use_kibana'; import { InfraClientStartDeps } from '../types'; import { ApolloClientContext } from '../utils/apollo_context'; +import { HeaderActionMenuProvider } from '../utils/header_action_menu_provider'; import { NavigationWarningPromptProvider } from '../utils/navigation_warning_prompt'; import { TriggersActionsProvider } from '../utils/triggers_actions_context'; export const CommonInfraProviders: React.FC<{ apolloClient: ApolloClient<{}>; triggersActionsUI: TriggersAndActionsUIPublicPluginStart; -}> = ({ apolloClient, children, triggersActionsUI }) => { + setHeaderActionMenu: AppMountParameters['setHeaderActionMenu']; +}> = ({ apolloClient, children, triggersActionsUI, setHeaderActionMenu }) => { const [darkMode] = useUiSetting$('theme:darkMode'); return ( - {children} + + {children} + diff --git a/x-pack/plugins/infra/public/apps/logs_app.tsx b/x-pack/plugins/infra/public/apps/logs_app.tsx index b6b171fcb4727..666ea02693873 100644 --- a/x-pack/plugins/infra/public/apps/logs_app.tsx +++ b/x-pack/plugins/infra/public/apps/logs_app.tsx @@ -23,14 +23,20 @@ import { prepareMountElement } from './common_styles'; export const renderApp = ( core: CoreStart, plugins: InfraClientStartDeps, - { element, history }: AppMountParameters + { element, history, setHeaderActionMenu }: AppMountParameters ) => { const apolloClient = createApolloClient(core.http.fetch); prepareMountElement(element); ReactDOM.render( - , + , element ); @@ -44,7 +50,8 @@ const LogsApp: React.FC<{ core: CoreStart; history: History; plugins: InfraClientStartDeps; -}> = ({ apolloClient, core, history, plugins }) => { + setHeaderActionMenu: AppMountParameters['setHeaderActionMenu']; +}> = ({ apolloClient, core, history, plugins, setHeaderActionMenu }) => { const uiCapabilities = core.application.capabilities; return ( @@ -52,6 +59,7 @@ const LogsApp: React.FC<{ diff --git a/x-pack/plugins/infra/public/apps/metrics_app.tsx b/x-pack/plugins/infra/public/apps/metrics_app.tsx index d91c64de933e6..37ef29a2b0cd1 100644 --- a/x-pack/plugins/infra/public/apps/metrics_app.tsx +++ b/x-pack/plugins/infra/public/apps/metrics_app.tsx @@ -25,14 +25,20 @@ import { prepareMountElement } from './common_styles'; export const renderApp = ( core: CoreStart, plugins: InfraClientStartDeps, - { element, history }: AppMountParameters + { element, history, setHeaderActionMenu }: AppMountParameters ) => { const apolloClient = createApolloClient(core.http.fetch); prepareMountElement(element); ReactDOM.render( - , + , element ); @@ -46,7 +52,8 @@ const MetricsApp: React.FC<{ core: CoreStart; history: History; plugins: InfraClientStartDeps; -}> = ({ apolloClient, core, history, plugins }) => { + setHeaderActionMenu: AppMountParameters['setHeaderActionMenu']; +}> = ({ apolloClient, core, history, plugins, setHeaderActionMenu }) => { const uiCapabilities = core.application.capabilities; return ( @@ -54,6 +61,7 @@ const MetricsApp: React.FC<{ diff --git a/x-pack/plugins/infra/public/components/navigation/app_navigation.tsx b/x-pack/plugins/infra/public/components/navigation/app_navigation.tsx index eae39c9d1b253..9da892ec92ec1 100644 --- a/x-pack/plugins/infra/public/components/navigation/app_navigation.tsx +++ b/x-pack/plugins/infra/public/components/navigation/app_navigation.tsx @@ -24,8 +24,7 @@ export const AppNavigation = ({ 'aria-label': label, children }: AppNavigationPr const Nav = euiStyled.nav` background: ${(props) => props.theme.eui.euiColorEmptyShade}; border-bottom: ${(props) => props.theme.eui.euiBorderThin}; - padding: ${(props) => - `${props.theme.eui.euiSize} ${props.theme.eui.euiSizeL} ${props.theme.eui.euiSize} ${props.theme.eui.euiSizeL}`}; + padding: ${(props) => `${props.theme.eui.euiSizeS} ${props.theme.eui.euiSizeL}`}; .euiTabs { padding-left: 3px; margin-left: -3px; 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 10189c0d8076c..d091f55956923 100644 --- a/x-pack/plugins/infra/public/pages/logs/page_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/page_content.tsx @@ -6,7 +6,7 @@ import { EuiFlexGroup, EuiFlexItem, EuiButtonEmpty } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import React from 'react'; +import React, { useContext } from 'react'; import { Route, Switch } from 'react-router-dom'; import useMount from 'react-use/lib/useMount'; @@ -24,9 +24,12 @@ import { LogEntryCategoriesPage } from './log_entry_categories'; import { LogEntryRatePage } from './log_entry_rate'; import { LogsSettingsPage } from './settings'; import { StreamPage } from './stream'; +import { HeaderMenuPortal } from '../../../../observability/public'; +import { HeaderActionMenuContext } from '../../utils/header_action_menu_provider'; export const LogsPageContent: React.FunctionComponent = () => { const uiCapabilities = useKibana().services.application?.capabilities; + const { setHeaderActionMenu } = useContext(HeaderActionMenuContext); const { initialize } = useLogSourceContext(); @@ -66,6 +69,28 @@ export const LogsPageContent: React.FunctionComponent = () => { + {setHeaderActionMenu && ( + + + + + + + + {ADD_DATA_LABEL} + + + + + )} +
{ - - - - - - {ADD_DATA_LABEL} - - diff --git a/x-pack/plugins/infra/public/pages/metrics/index.tsx b/x-pack/plugins/infra/public/pages/metrics/index.tsx index 022c62b6bb06b..222278dde3314 100644 --- a/x-pack/plugins/infra/public/pages/metrics/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/index.tsx @@ -40,6 +40,8 @@ import { SourceConfigurationFields } from '../../graphql/types'; import { AlertPrefillProvider } from '../../alerting/use_alert_prefill'; import { InfraMLCapabilitiesProvider } from '../../containers/ml/infra_ml_capabilities'; import { AnomalyDetectionFlyout } from './inventory_view/components/ml/anomaly_detection/anomoly_detection_flyout'; +import { HeaderMenuPortal } from '../../../../observability/public'; +import { HeaderActionMenuContext } from '../../utils/header_action_menu_provider'; const ADD_DATA_LABEL = i18n.translate('xpack.infra.metricsHeaderAddDataButtonLabel', { defaultMessage: 'Add data', @@ -47,6 +49,7 @@ const ADD_DATA_LABEL = i18n.translate('xpack.infra.metricsHeaderAddDataButtonLab export const InfrastructurePage = ({ match }: RouteComponentProps) => { const uiCapabilities = useKibana().services.application?.capabilities; + const { setHeaderActionMenu } = useContext(HeaderActionMenuContext); const kibana = useKibana(); @@ -72,6 +75,32 @@ export const InfrastructurePage = ({ match }: RouteComponentProps) => { })} /> + {setHeaderActionMenu && ( + + + + + + + + + + + + {ADD_DATA_LABEL} + + + + + )} +
{ ]} /> - - - - - - - - - - - {ADD_DATA_LABEL} - - - diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx index 6ee3c9f1fae80..83ba3726dacb9 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx @@ -4,10 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useMemo, useState } from 'react'; +import React, { useMemo, useState, useCallback } from 'react'; import { debounce } from 'lodash'; import { i18n } from '@kbn/i18n'; -import { EuiSearchBar, EuiSpacer, EuiEmptyPrompt, EuiButton } from '@elastic/eui'; +import { + EuiSearchBar, + EuiSpacer, + EuiEmptyPrompt, + EuiButton, + EuiText, + EuiIconTip, + Query, +} from '@elastic/eui'; import { useProcessList, SortBy, @@ -20,6 +28,7 @@ import { ProcessesTable } from './processes_table'; import { parseSearchString } from './parse_search_string'; const TabComponent = ({ currentTime, node, nodeType, options }: TabProps) => { + const [searchBarState, setSearchBarState] = useState(Query.MATCH_ALL); const [searchFilter, setSearchFilter] = useState(''); const [sortBy, setSortBy] = useState({ name: 'cpu', @@ -45,14 +54,23 @@ const TabComponent = ({ currentTime, node, nodeType, options }: TabProps) => { ); const debouncedSearchOnChange = useMemo( - () => - debounce<(props: { queryText: string }) => void>( - ({ queryText }) => setSearchFilter(queryText), - 500 - ), + () => debounce<(queryText: string) => void>((queryText) => setSearchFilter(queryText), 500), [setSearchFilter] ); + const searchBarOnChange = useCallback( + ({ query, queryText }) => { + setSearchBarState(query); + debouncedSearchOnChange(queryText); + }, + [setSearchBarState, debouncedSearchOnChange] + ); + + const clearSearchBar = useCallback(() => { + setSearchBarState(Query.MATCH_ALL); + setSearchFilter(''); + }, [setSearchBarState, setSearchFilter]); + return ( @@ -61,8 +79,34 @@ const TabComponent = ({ currentTime, node, nodeType, options }: TabProps) => { processSummary={(!error ? response?.summary : null) ?? { total: 0 }} /> + +

+ {i18n.translate('xpack.infra.metrics.nodeDetails.processesHeader', { + defaultMessage: 'Top processes', + })}{' '} + +

+
+ { processList={response?.processList ?? []} sortBy={sortBy} setSortBy={setSortBy} + clearSearchBar={clearSearchBar} /> ) : ( {i18n.translate('xpack.infra.metrics.nodeDetails.processListError', { - defaultMessage: 'Unable to show process data', + defaultMessage: 'Unable to load process data', })}

} diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/processes_table.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/processes_table.tsx index 1952ba947761c..3e4b066afa157 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/processes_table.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/processes_table.tsx @@ -7,6 +7,7 @@ import React, { useMemo, useState, useCallback } from 'react'; import { omit } from 'lodash'; import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; import { EuiTable, EuiTableHeader, @@ -15,6 +16,9 @@ import { EuiTableRowCell, EuiLoadingChart, EuiEmptyPrompt, + EuiText, + EuiLink, + EuiButton, SortableProperties, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, @@ -34,6 +38,7 @@ interface TableProps { isLoading: boolean; sortBy: SortBy; setSortBy: (s: SortBy) => void; + clearSearchBar: () => void; } function useSortableProperties( @@ -66,6 +71,7 @@ export const ProcessesTable = ({ isLoading, sortBy, setSortBy, + clearSearchBar, }: TableProps) => { const { updateSortableProperties } = useSortableProperties( [ @@ -102,13 +108,42 @@ export const ProcessesTable = ({ if (currentItems.length === 0) return ( + {i18n.translate('xpack.infra.metrics.nodeDetails.noProcesses', { - defaultMessage: 'No processes matched these search terms', + defaultMessage: 'No processes found', })} - + + } + body={ + + + + + ), + }} + /> + + } + actions={ + + {i18n.translate('xpack.infra.metrics.nodeDetails.noProcessesClearFilters', { + defaultMessage: 'Clear filters', + })} + } /> ); diff --git a/x-pack/plugins/infra/public/utils/header_action_menu_provider.tsx b/x-pack/plugins/infra/public/utils/header_action_menu_provider.tsx new file mode 100644 index 0000000000000..141b3bcc9a162 --- /dev/null +++ b/x-pack/plugins/infra/public/utils/header_action_menu_provider.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { AppMountParameters } from 'kibana/public'; + +interface ContextProps { + setHeaderActionMenu?: AppMountParameters['setHeaderActionMenu']; +} + +export const HeaderActionMenuContext = React.createContext({}); + +export const HeaderActionMenuProvider: React.FC> = ({ + setHeaderActionMenu, + children, +}) => { + return ( + + {children} + + ); +}; diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.scss b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.scss index a1a072be77f81..0f512e535c9d1 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.scss +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.scss @@ -114,8 +114,12 @@ right: 0; } -.lnsLayerPanel__paletteColor { - height: $euiSizeXS; +.lnsLayerPanel__palette { + border-radius: 0 0 ($euiBorderRadius - 1px) ($euiBorderRadius - 1px); + + &::after { + border: none; + } } .lnsLayerPanel__dimensionLink { diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/palette_indicator.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/palette_indicator.tsx index 7e65fe7025932..b27451236e3b4 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/palette_indicator.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/palette_indicator.tsx @@ -5,23 +5,18 @@ */ import React from 'react'; -import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { EuiColorPaletteDisplay } from '@elastic/eui'; import { AccessorConfig } from '../../../types'; export function PaletteIndicator({ accessorConfig }: { accessorConfig: AccessorConfig }) { if (accessorConfig.triggerIcon !== 'colorBy' || !accessorConfig.palette) return null; return ( - - {accessorConfig.palette.map((color) => ( - - ))} - +
+ +
); } diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filter_popover.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filter_popover.test.tsx index 2fb2bef7f9787..8bceac180f0eb 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filter_popover.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filter_popover.test.tsx @@ -5,7 +5,7 @@ */ import React, { MouseEventHandler } from 'react'; -import { shallow } from 'enzyme'; +import { shallow, mount } from 'enzyme'; import { act } from 'react-dom/test-utils'; import { EuiPopover, EuiLink } from '@elastic/eui'; import { createMockedIndexPattern } from '../../../mocks'; @@ -28,8 +28,7 @@ const defaultProps = { Button: ({ onClick }: { onClick: MouseEventHandler }) => ( trigger ), - isOpenByCreation: true, - setIsOpenByCreation: jest.fn(), + initiallyOpen: true, }; describe('filter popover', () => { @@ -39,16 +38,14 @@ describe('filter popover', () => { }, })); it('should be open if is open by creation', () => { - const setIsOpenByCreation = jest.fn(); - const instance = shallow( - - ); + const instance = mount(); + instance.update(); expect(instance.find(EuiPopover).prop('isOpen')).toEqual(true); act(() => { instance.find(EuiPopover).prop('closePopover')!(); }); instance.update(); - expect(setIsOpenByCreation).toHaveBeenCalledWith(false); + expect(instance.find(EuiPopover).prop('isOpen')).toEqual(false); }); it('should call setFilter when modifying QueryInput', () => { const setFilter = jest.fn(); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filter_popover.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filter_popover.tsx index ca84c072be5ce..df01b8e4b4afc 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filter_popover.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filter_popover.tsx @@ -5,7 +5,7 @@ */ import './filter_popover.scss'; -import React, { MouseEventHandler, useState } from 'react'; +import React, { MouseEventHandler, useEffect, useState } from 'react'; import useDebounce from 'react-use/lib/useDebounce'; import { EuiPopover, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; @@ -19,23 +19,24 @@ export const FilterPopover = ({ setFilter, indexPattern, Button, - isOpenByCreation, - setIsOpenByCreation, + initiallyOpen, }: { filter: FilterValue; setFilter: Function; indexPattern: IndexPattern; Button: React.FunctionComponent<{ onClick: MouseEventHandler }>; - isOpenByCreation: boolean; - setIsOpenByCreation: Function; + initiallyOpen: boolean; }) => { const [isPopoverOpen, setIsPopoverOpen] = useState(false); const inputRef = React.useRef(); + // set popover open on start to work around EUI bug + useEffect(() => { + setIsPopoverOpen(initiallyOpen); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + const closePopover = () => { - if (isOpenByCreation) { - setIsOpenByCreation(false); - } if (isPopoverOpen) { setIsPopoverOpen(false); } @@ -59,15 +60,12 @@ export const FilterPopover = ({ data-test-subj="indexPattern-filters-existingFilterContainer" anchorClassName="eui-fullWidth" panelClassName="lnsIndexPatternDimensionEditor__filtersEditor" - isOpen={isOpenByCreation || isPopoverOpen} + isOpen={isPopoverOpen} ownFocus closePopover={() => closePopover()} button={ -
-
- - + + + + + + +
+ +
+
+ + + +
+
+ +
+
+ -
-
+ -
- - - - - - + + ); } ); + +const SchemaInformation = ({ + closePopover, + setActivePopover, + isOpen, +}: { + closePopover: () => void; + setActivePopover: (value: 'schemaInfo' | null) => void; + isOpen: boolean; +}) => { + const colorMap = useColors(); + const sourceAndSchema = useSelector(selectors.resolverTreeSourceAndSchema); + const setAsActivePopover = useCallback(() => setActivePopover('schemaInfo'), [setActivePopover]); + + const schemaInfoButtonTitle = i18n.translate( + 'xpack.securitySolution.resolver.graphControls.schemaInfoButtonTitle', + { + defaultMessage: 'Schema Information', + } + ); + + const unknownSchemaValue = i18n.translate( + 'xpack.securitySolution.resolver.graphControls.unknownSchemaValue', + { + defaultMessage: 'Unknown', + } + ); + + return ( + + } + isOpen={isOpen} + closePopover={closePopover} + anchorPosition="leftCenter" + > + + {i18n.translate('xpack.securitySolution.resolver.graphControls.schemaInfoTitle', { + defaultMessage: 'process tree', + })} + + +
+ + <> + + {i18n.translate('xpack.securitySolution.resolver.graphControls.schemaSource', { + defaultMessage: 'source', + })} + + + {sourceAndSchema?.dataSource ?? unknownSchemaValue} + + + {i18n.translate('xpack.securitySolution.resolver.graphControls.schemaID', { + defaultMessage: 'id', + })} + + + {sourceAndSchema?.schema.id ?? unknownSchemaValue} + + + {i18n.translate('xpack.securitySolution.resolver.graphControls.schemaEdge', { + defaultMessage: 'edge', + })} + + + {sourceAndSchema?.schema.parent ?? unknownSchemaValue} + + + +
+
+ ); +}; + +// This component defines the cube legend that allows users to identify the meaning of the cubes +// Should be updated to be dynamic if and when non process based resolvers are possible +const NodeLegend = ({ + closePopover, + setActivePopover, + isOpen, +}: { + closePopover: () => void; + setActivePopover: (value: 'nodeLegend') => void; + isOpen: boolean; +}) => { + const setAsActivePopover = useCallback(() => setActivePopover('nodeLegend'), [setActivePopover]); + const colorMap = useColors(); + + const nodeLegendButtonTitle = i18n.translate( + 'xpack.securitySolution.resolver.graphControls.nodeLegendButtonTitle', + { + defaultMessage: 'Node Legend', + } + ); + + return ( + + } + isOpen={isOpen} + closePopover={closePopover} + anchorPosition="leftCenter" + > + + {i18n.translate('xpack.securitySolution.resolver.graphControls.nodeLegend', { + defaultMessage: 'legend', + })} + +
+ + <> + + + + + + {i18n.translate( + 'xpack.securitySolution.resolver.graphControls.runningProcessCube', + { + defaultMessage: 'Running Process', + } + )} + + + + + + + + {i18n.translate( + 'xpack.securitySolution.resolver.graphControls.terminatedProcessCube', + { + defaultMessage: 'Terminated Process', + } + )} + + + + + + + + {i18n.translate( + 'xpack.securitySolution.resolver.graphControls.currentlyLoadingCube', + { + defaultMessage: 'Loading Process', + } + )} + + + + + + + + {i18n.translate('xpack.securitySolution.resolver.graphControls.errorCube', { + defaultMessage: 'Error', + })} + + + + +
+
+ ); +}; diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/cube_for_process.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/cube_for_process.tsx index cc5f39e985d9e..99c57757fbb6a 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/cube_for_process.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/cube_for_process.tsx @@ -17,40 +17,44 @@ interface StyledSVGCube { } import { useCubeAssets } from '../use_cube_assets'; import { useSymbolIDs } from '../use_symbol_ids'; +import { NodeDataStatus } from '../../types'; /** * Icon representing a process node. */ export const CubeForProcess = memo(function ({ className, - running, + size = '2.15em', + state, isOrigin, 'data-test-subj': dataTestSubj, }: { 'data-test-subj'?: string; /** - * True if the process represented by the node is still running. + * The state of the process's node data (for endpoint the process's lifecycle events) */ - running: boolean; + state: NodeDataStatus; + /** The css size (px, em, etc...) for the width and height of the svg cube. Defaults to 2.15em */ + size?: string; isOrigin?: boolean; className?: string; }) { - const { cubeSymbol, strokeColor } = useCubeAssets(!running, false); + const { cubeSymbol, strokeColor } = useCubeAssets(state, false); const { processCubeActiveBacking } = useSymbolIDs(); return ( {i18n.translate('xpack.securitySolution.resolver.node_icon', { - defaultMessage: '{running, select, true {Running Process} false {Terminated Process}}', - values: { running }, + defaultMessage: `{state, select, running {Running Process} terminated {Terminated Process} loading {Loading Process} error {Error Process}}`, + values: { state }, })} {isOrigin && ( diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/event_detail.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/event_detail.tsx index 4936cf0cbb80e..003182bd5f1b7 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/event_detail.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/event_detail.tsx @@ -29,6 +29,7 @@ import { useLinkProps } from '../use_link_props'; import { SafeResolverEvent } from '../../../../common/endpoint/types'; import { deepObjectEntries } from './deep_object_entries'; import { useFormattedDate } from './use_formatted_date'; +import * as nodeDataModel from '../../models/node_data'; const eventDetailRequestError = i18n.translate( 'xpack.securitySolution.resolver.panel.eventDetail.requestError', @@ -39,23 +40,24 @@ const eventDetailRequestError = i18n.translate( export const EventDetail = memo(function EventDetail({ nodeID, - eventID, eventCategory: eventType, }: { nodeID: string; - eventID: string; /** The event type to show in the breadcrumbs */ eventCategory: string; }) { const isEventLoading = useSelector(selectors.isCurrentRelatedEventLoading); - const isProcessTreeLoading = useSelector(selectors.isTreeLoading); + const isTreeLoading = useSelector(selectors.isTreeLoading); + const processEvent = useSelector((state: ResolverState) => + nodeDataModel.firstEvent(selectors.nodeDataForID(state)(nodeID)) + ); + const nodeStatus = useSelector((state: ResolverState) => selectors.nodeDataStatus(state)(nodeID)); - const isLoading = isEventLoading || isProcessTreeLoading; + const isNodeDataLoading = nodeStatus === 'loading'; + const isLoading = isEventLoading || isTreeLoading || isNodeDataLoading; const event = useSelector(selectors.currentRelatedEventData); - const processEvent = useSelector((state: ResolverState) => - selectors.processEventForID(state)(nodeID) - ); + return isLoading ? ( @@ -90,7 +92,7 @@ const EventDetailContents = memo(function ({ * Event type to use in the breadcrumbs */ eventType: string; - processEvent: SafeResolverEvent | null; + processEvent: SafeResolverEvent | undefined; }) { const timestamp = eventModel.timestampSafeVersion(event); const formattedDate = diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/index.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/index.tsx index f6fbd280e7ed5..c6e81f691e2fe 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/index.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/index.tsx @@ -37,7 +37,6 @@ export const PanelRouter = memo(function () { return ( ); diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/node_detail.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/node_detail.tsx index 27a7723d7d656..fedf1ae2499ae 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/node_detail.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/node_detail.tsx @@ -20,6 +20,7 @@ import { GeneratedText } from '../generated_text'; import { CopyablePanelField } from './copyable_panel_field'; import { Breadcrumbs } from './breadcrumbs'; import { processPath, processPID } from '../../models/process_event'; +import * as nodeDataModel from '../../models/node_data'; import { CubeForProcess } from './cube_for_process'; import { SafeResolverEvent } from '../../../../common/endpoint/types'; import { useCubeAssets } from '../use_cube_assets'; @@ -28,28 +29,35 @@ import { PanelLoading } from './panel_loading'; import { StyledPanel } from '../styles'; import { useLinkProps } from '../use_link_props'; import { useFormattedDate } from './use_formatted_date'; +import { PanelContentError } from './panel_content_error'; const StyledCubeForProcess = styled(CubeForProcess)` position: relative; top: 0.75em; `; +const nodeDetailError = i18n.translate('xpack.securitySolution.resolver.panel.nodeDetail.Error', { + defaultMessage: 'Node details were unable to be retrieved', +}); + export const NodeDetail = memo(function ({ nodeID }: { nodeID: string }) { const processEvent = useSelector((state: ResolverState) => - selectors.processEventForID(state)(nodeID) + nodeDataModel.firstEvent(selectors.nodeDataForID(state)(nodeID)) ); - return ( - <> - {processEvent === null ? ( - - - - ) : ( - - - - )} - + const nodeStatus = useSelector((state: ResolverState) => selectors.nodeDataStatus(state)(nodeID)); + + return nodeStatus === 'loading' ? ( + + + + ) : processEvent ? ( + + + + ) : ( + + + ); }); @@ -65,9 +73,7 @@ const NodeDetailView = memo(function ({ nodeID: string; }) { const processName = eventModel.processNameSafeVersion(processEvent); - const isProcessTerminated = useSelector((state: ResolverState) => - selectors.isProcessTerminated(state)(nodeID) - ); + const nodeState = useSelector((state: ResolverState) => selectors.nodeDataStatus(state)(nodeID)); const relatedEventTotal = useSelector((state: ResolverState) => { return selectors.relatedEventTotalCount(state)(nodeID); }); @@ -171,7 +177,7 @@ const NodeDetailView = memo(function ({ }, ]; }, [processName, nodesLinkNavProps]); - const { descriptionText } = useCubeAssets(isProcessTerminated, false); + const { descriptionText } = useCubeAssets(nodeState, false); const nodeDetailNavProps = useLinkProps({ panelView: 'nodeEvents', @@ -187,7 +193,7 @@ const NodeDetailView = memo(function ({ {processName} diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/node_events.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/node_events.tsx index d0601fad43f57..6f0c336ab3df4 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/node_events.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/node_events.tsx @@ -13,21 +13,21 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { useSelector } from 'react-redux'; import { Breadcrumbs } from './breadcrumbs'; import * as event from '../../../../common/endpoint/models/event'; -import { ResolverNodeStats } from '../../../../common/endpoint/types'; +import { EventStats } from '../../../../common/endpoint/types'; import * as selectors from '../../store/selectors'; import { ResolverState } from '../../types'; import { StyledPanel } from '../styles'; import { PanelLoading } from './panel_loading'; import { useLinkProps } from '../use_link_props'; +import * as nodeDataModel from '../../models/node_data'; export function NodeEvents({ nodeID }: { nodeID: string }) { const processEvent = useSelector((state: ResolverState) => - selectors.processEventForID(state)(nodeID) + nodeDataModel.firstEvent(selectors.nodeDataForID(state)(nodeID)) ); - const relatedEventsStats = useSelector((state: ResolverState) => - selectors.relatedEventsStats(state)(nodeID) - ); - if (processEvent === null || relatedEventsStats === undefined) { + const nodeStats = useSelector((state: ResolverState) => selectors.nodeStats(state)(nodeID)); + + if (processEvent === undefined || nodeStats === undefined) { return ( @@ -39,10 +39,10 @@ export function NodeEvents({ nodeID }: { nodeID: string }) { - + ); } @@ -64,7 +64,7 @@ const EventCategoryLinks = memo(function ({ relatedStats, }: { nodeID: string; - relatedStats: ResolverNodeStats; + relatedStats: EventStats; }) { interface EventCountsTableView { eventType: string; @@ -72,7 +72,7 @@ const EventCategoryLinks = memo(function ({ } const rows = useMemo(() => { - return Object.entries(relatedStats.events.byCategory).map( + return Object.entries(relatedStats.byCategory).map( ([eventType, count]): EventCountsTableView => { return { eventType, @@ -80,7 +80,7 @@ const EventCategoryLinks = memo(function ({ }; } ); - }, [relatedStats.events.byCategory]); + }, [relatedStats.byCategory]); const columns = useMemo>>( () => [ diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/node_events_of_type.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/node_events_of_type.tsx index c9648c6f562e5..fbfba38295ea4 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/node_events_of_type.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/node_events_of_type.tsx @@ -42,9 +42,7 @@ export const NodeEventsInCategory = memo(function ({ nodeID: string; eventCategory: string; }) { - const processEvent = useSelector((state: ResolverState) => - selectors.processEventForID(state)(nodeID) - ); + const node = useSelector((state: ResolverState) => selectors.graphNodeForID(state)(nodeID)); const eventCount = useSelector((state: ResolverState) => selectors.totalRelatedEventCountForNode(state)(nodeID) ); @@ -57,13 +55,13 @@ export const NodeEventsInCategory = memo(function ({ const hasError = useSelector(selectors.hadErrorLoadingNodeEventsInCategory); return ( <> - {isLoading || processEvent === null ? ( + {isLoading ? ( ) : ( - {hasError ? ( + {hasError || !node ? ( { useCallback((state: ResolverState) => { const { processNodePositions } = selectors.layout(state); const view: ProcessTableView[] = []; - for (const processEvent of processNodePositions.keys()) { - const name = eventModel.processNameSafeVersion(processEvent); - const nodeID = eventModel.entityIDSafeVersion(processEvent); + for (const treeNode of processNodePositions.keys()) { + const name = nodeModel.nodeName(treeNode); + const nodeID = nodeModel.nodeID(treeNode); if (nodeID !== undefined) { view.push({ name, - timestamp: eventModel.timestampAsDateSafeVersion(processEvent), + timestamp: nodeModel.timestampAsDate(treeNode), nodeID, }); } @@ -119,7 +119,8 @@ export const NodeList = memo(() => { const children = useSelector(selectors.hasMoreChildren); const ancestors = useSelector(selectors.hasMoreAncestors); - const showWarning = children === true || ancestors === true; + const generations = useSelector(selectors.hasMoreGenerations); + const showWarning = children === true || ancestors === true || generations === true; const rowProps = useMemo(() => ({ 'data-test-subj': 'resolver:node-list:item' }), []); return ( @@ -141,9 +142,7 @@ function NodeDetailLink({ name, nodeID }: { name?: string; nodeID: string }) { const isOrigin = useSelector((state: ResolverState) => { return selectors.originID(state) === nodeID; }); - const isTerminated = useSelector((state: ResolverState) => - nodeID === undefined ? false : selectors.isProcessTerminated(state)(nodeID) - ); + const nodeState = useSelector((state: ResolverState) => selectors.nodeDataStatus(state)(nodeID)); const { descriptionText } = useColors(); const linkProps = useLinkProps({ panelView: 'nodeDetail', panelParameters: { nodeID } }); const dispatch: (action: ResolverAction) => void = useDispatch(); @@ -162,7 +161,12 @@ function NodeDetailLink({ name, nodeID }: { name?: string; nodeID: string }) { [timestamp, linkProps, dispatch, nodeID] ); return ( - + {name === undefined ? ( {i18n.translate( @@ -175,7 +179,7 @@ function NodeDetailLink({ name, nodeID }: { name?: string; nodeID: string }) { ) : ( diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/panel_states.test.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/panel_states.test.tsx index 39a5130ecaf68..6f20063d10d0a 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/panel_states.test.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/panel_states.test.tsx @@ -23,6 +23,8 @@ describe('Resolver: panel loading and resolution states', () => { nodeID: 'origin', eventCategory: 'registry', eventID: firstRelatedEventID, + eventTimestamp: '0', + winlogRecordID: '0', }, panelView: 'eventDetail', }); @@ -129,7 +131,7 @@ describe('Resolver: panel loading and resolution states', () => { }); describe('when navigating to the event categories panel', () => { - let resumeRequest: (pausableRequest: ['entities']) => void; + let resumeRequest: (pausableRequest: ['eventsWithEntityIDAndCategory']) => void; beforeEach(() => { const { metadata: { databaseDocumentID }, @@ -140,7 +142,7 @@ describe('Resolver: panel loading and resolution states', () => { resumeRequest = resume; memoryHistory = createMemoryHistory(); - pause(['entities']); + pause(['eventsWithEntityIDAndCategory']); simulator = new Simulator({ dataAccessLayer, @@ -170,7 +172,7 @@ describe('Resolver: panel loading and resolution states', () => { }); it('should successfully load the events in category panel', async () => { - await resumeRequest(['entities']); + await resumeRequest(['eventsWithEntityIDAndCategory']); await expect( simulator.map(() => ({ resolverPanelLoading: simulator.testSubject('resolver:panel:loading').length, @@ -186,7 +188,7 @@ describe('Resolver: panel loading and resolution states', () => { }); describe('when navigating to the node detail panel', () => { - let resumeRequest: (pausableRequest: ['entities']) => void; + let resumeRequest: (pausableRequest: ['nodeData']) => void; beforeEach(() => { const { metadata: { databaseDocumentID }, @@ -197,7 +199,7 @@ describe('Resolver: panel loading and resolution states', () => { resumeRequest = resume; memoryHistory = createMemoryHistory(); - pause(['entities']); + pause(['nodeData']); simulator = new Simulator({ dataAccessLayer, @@ -226,7 +228,7 @@ describe('Resolver: panel loading and resolution states', () => { }); it('should successfully load the events in category panel', async () => { - await resumeRequest(['entities']); + await resumeRequest(['nodeData']); await expect( simulator.map(() => ({ resolverPanelLoading: simulator.testSubject('resolver:panel:loading').length, diff --git a/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx b/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx index 7a3657fe93514..ab6083c796b3a 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx @@ -9,12 +9,13 @@ import styled from 'styled-components'; import { htmlIdGenerator, EuiButton, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { useSelector } from 'react-redux'; import { FormattedMessage } from '@kbn/i18n/react'; +import { i18n } from '@kbn/i18n'; import { NodeSubMenu } from './styles'; import { applyMatrix3 } from '../models/vector2'; import { Vector2, Matrix3, ResolverState } from '../types'; -import { SafeResolverEvent } from '../../../common/endpoint/types'; +import { ResolverNode } from '../../../common/endpoint/types'; import { useResolverDispatch } from './use_resolver_dispatch'; -import * as eventModel from '../../../common/endpoint/models/event'; +import * as nodeModel from '../../../common/endpoint/models/node'; import * as selectors from '../store/selectors'; import { fontSize } from './font_size'; import { useCubeAssets } from './use_cube_assets'; @@ -65,9 +66,50 @@ const StyledDescriptionText = styled.div` z-index: 45; `; -const StyledOuterGroup = styled.g` +interface StyledEuiButtonContent { + readonly isShowingIcon: boolean; +} + +const StyledEuiButtonContent = styled.span` + padding: ${(props) => (props.isShowingIcon ? '0px' : '0 12px')}; +`; + +const StyledOuterGroup = styled.g<{ isNodeLoading: boolean }>` fill: none; pointer-events: visiblePainted; + // The below will apply the loading css to the element that references the cube + // when the nodeData is loading for the current node + ${(props) => + props.isNodeLoading && + ` + & .cube { + animation-name: pulse; + /** + * his is a multiple of .6 so it can match up with the EUI button's loading spinner + * which is (0.6s). Using .6 here makes it a bit too fast. + */ + animation-duration: 1.8s; + animation-delay: 0; + animation-direction: normal; + animation-iteration-count: infinite; + animation-timing-function: linear; + } + + /** + * Animation loading state of the cube. + */ + @keyframes pulse { + 0% { + opacity: 1; + } + 50% { + opacity: 0.35; + } + 100% { + opacity: 1; + } + } + `} `; /** @@ -77,9 +119,9 @@ const UnstyledProcessEventDot = React.memo( ({ className, position, - event, + node, + nodeID, projectionMatrix, - isProcessTerminated, timeAtRender, }: { /** @@ -87,21 +129,21 @@ const UnstyledProcessEventDot = React.memo( */ className?: string; /** - * The positon of the process node, in 'world' coordinates. + * The positon of the graph node, in 'world' coordinates. */ position: Vector2; /** - * An event which contains details about the process node. + * An event which contains details about the graph node. */ - event: SafeResolverEvent; + node: ResolverNode; /** - * projectionMatrix which can be used to convert `position` to screen coordinates. + * The unique identifier for the node based on a datasource id */ - projectionMatrix: Matrix3; + nodeID: string; /** - * Whether or not to show the process as terminated. + * projectionMatrix which can be used to convert `position` to screen coordinates. */ - isProcessTerminated: boolean; + projectionMatrix: Matrix3; /** * The time (unix epoch) at render. @@ -125,14 +167,7 @@ const UnstyledProcessEventDot = React.memo( const ariaActiveDescendant = useSelector(selectors.ariaActiveDescendant); const selectedNode = useSelector(selectors.selectedNode); const originID = useSelector(selectors.originID); - const nodeID: string | undefined = eventModel.entityIDSafeVersion(event); - if (nodeID === undefined) { - // NB: this component should be taking nodeID as a `string` instead of handling this logic here - throw new Error('Tried to render a node with no ID'); - } - const relatedEventStats = useSelector((state: ResolverState) => - selectors.relatedEventsStats(state)(nodeID) - ); + const nodeStats = useSelector((state: ResolverState) => selectors.nodeStats(state)(nodeID)); // define a standard way of giving HTML IDs to nodes based on their entity_id/nodeID. // this is used to link nodes via aria attributes @@ -218,6 +253,11 @@ const UnstyledProcessEventDot = React.memo( | null; } = React.createRef(); const colorMap = useColors(); + + const nodeState = useSelector((state: ResolverState) => + selectors.nodeDataStatus(state)(nodeID) + ); + const isNodeLoading = nodeState === 'loading'; const { backingFill, cubeSymbol, @@ -226,7 +266,7 @@ const UnstyledProcessEventDot = React.memo( labelButtonFill, strokeColor, } = useCubeAssets( - isProcessTerminated, + nodeState, /** * There is no definition for 'trigger process' yet. return false. */ false @@ -257,19 +297,29 @@ const UnstyledProcessEventDot = React.memo( if (animationTarget.current?.beginElement) { animationTarget.current.beginElement(); } - dispatch({ - type: 'userSelectedResolverNode', - payload: nodeID, - }); - processDetailNavProps.onClick(clickEvent); + + if (nodeState === 'error') { + dispatch({ + type: 'userReloadedResolverNode', + payload: nodeID, + }); + } else { + dispatch({ + type: 'userSelectedResolverNode', + payload: nodeID, + }); + processDetailNavProps.onClick(clickEvent); + } }, - [animationTarget, dispatch, nodeID, processDetailNavProps] + [animationTarget, dispatch, nodeID, processDetailNavProps, nodeState] ); const grandTotal: number | null = useSelector((state: ResolverState) => - selectors.relatedEventTotalForProcess(state)(event) + selectors.statsTotalForNode(state)(node) ); + const nodeName = nodeModel.nodeName(node); + /* eslint-disable jsx-a11y/click-events-have-key-events */ /** * Key event handling (e.g. 'Enter'/'Space') is provisioned by the `EuiKeyboardAccessible` component @@ -315,7 +365,7 @@ const UnstyledProcessEventDot = React.memo( zIndex: 30, }} > - + - + - {eventModel.processNameSafeVersion(event)} + {i18n.translate('xpack.securitySolution.resolver.node_button_name', { + defaultMessage: `{nodeState, select, error {Reload {nodeName}} other {{nodeName}}}`, + values: { + nodeState, + nodeName, + }, + })} - + 0 && ( )} diff --git a/x-pack/plugins/security_solution/public/resolver/view/resolver_loading_state.test.tsx b/x-pack/plugins/security_solution/public/resolver/view/resolver_loading_state.test.tsx index d8d8de640d786..fa1686e7ea4b6 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/resolver_loading_state.test.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/resolver_loading_state.test.tsx @@ -35,12 +35,12 @@ describe('Resolver: data loading and resolution states', () => { simulator.map(() => ({ resolverGraphLoading: simulator.testSubject('resolver:graph:loading').length, resolverGraphError: simulator.testSubject('resolver:graph:error').length, - resolverGraph: simulator.testSubject('resolver:graph').length, + resolverTree: simulator.testSubject('resolver:graph').length, })) ).toYieldEqualTo({ resolverGraphLoading: 1, resolverGraphError: 0, - resolverGraph: 0, + resolverTree: 0, }); }); }); @@ -66,12 +66,12 @@ describe('Resolver: data loading and resolution states', () => { simulator.map(() => ({ resolverGraphLoading: simulator.testSubject('resolver:graph:loading').length, resolverGraphError: simulator.testSubject('resolver:graph:error').length, - resolverGraph: simulator.testSubject('resolver:graph').length, + resolverTree: simulator.testSubject('resolver:graph').length, })) ).toYieldEqualTo({ resolverGraphLoading: 1, resolverGraphError: 0, - resolverGraph: 0, + resolverTree: 0, }); }); }); @@ -96,12 +96,12 @@ describe('Resolver: data loading and resolution states', () => { simulator.map(() => ({ resolverGraphLoading: simulator.testSubject('resolver:graph:loading').length, resolverGraphError: simulator.testSubject('resolver:graph:error').length, - resolverGraph: simulator.testSubject('resolver:graph').length, + resolverTree: simulator.testSubject('resolver:graph').length, })) ).toYieldEqualTo({ resolverGraphLoading: 0, resolverGraphError: 1, - resolverGraph: 0, + resolverTree: 0, }); }); }); @@ -126,13 +126,13 @@ describe('Resolver: data loading and resolution states', () => { simulator.map(() => ({ resolverGraphLoading: simulator.testSubject('resolver:graph:loading').length, resolverGraphError: simulator.testSubject('resolver:graph:error').length, - resolverGraph: simulator.testSubject('resolver:graph').length, + resolverTree: simulator.testSubject('resolver:graph').length, resolverGraphNodes: simulator.testSubject('resolver:node').length, })) ).toYieldEqualTo({ resolverGraphLoading: 0, resolverGraphError: 0, - resolverGraph: 1, + resolverTree: 1, resolverGraphNodes: 0, }); }); @@ -158,13 +158,13 @@ describe('Resolver: data loading and resolution states', () => { simulator.map(() => ({ resolverGraphLoading: simulator.testSubject('resolver:graph:loading').length, resolverGraphError: simulator.testSubject('resolver:graph:error').length, - resolverGraph: simulator.testSubject('resolver:graph').length, + resolverTree: simulator.testSubject('resolver:graph').length, resolverGraphNodes: simulator.testSubject('resolver:node').length, })) ).toYieldEqualTo({ resolverGraphLoading: 0, resolverGraphError: 0, - resolverGraph: 1, + resolverTree: 1, resolverGraphNodes: 3, }); }); diff --git a/x-pack/plugins/security_solution/public/resolver/view/resolver_without_providers.tsx b/x-pack/plugins/security_solution/public/resolver/view/resolver_without_providers.tsx index ed969b913a72e..65b72cf4bfa77 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/resolver_without_providers.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/resolver_without_providers.tsx @@ -19,7 +19,7 @@ import { useCamera } from './use_camera'; import { SymbolDefinitions } from './symbol_definitions'; import { useStateSyncingActions } from './use_state_syncing_actions'; import { StyledMapContainer, GraphContainer } from './styles'; -import { entityIDSafeVersion } from '../../../common/endpoint/models/event'; +import * as nodeModel from '../../../common/endpoint/models/node'; import { SideEffectContext } from './side_effect_context'; import { ResolverProps, ResolverState } from '../types'; import { PanelRouter } from './panels'; @@ -54,7 +54,7 @@ export const ResolverWithoutProviders = React.memo( } = useSelector((state: ResolverState) => selectors.visibleNodesAndEdgeLines(state)(timeAtRender) ); - const terminatedProcesses = useSelector(selectors.terminatedProcesses); + const { projectionMatrix, ref: cameraRef, onMouseDown } = useCamera(); const ref = useCallback( @@ -113,15 +113,18 @@ export const ResolverWithoutProviders = React.memo( /> ) )} - {[...processNodePositions].map(([processEvent, position]) => { - const processEntityId = entityIDSafeVersion(processEvent); + {[...processNodePositions].map(([treeNode, position]) => { + const nodeID = nodeModel.nodeID(treeNode); + if (nodeID === undefined) { + throw new Error('Tried to render a node without an ID'); + } return ( ); diff --git a/x-pack/plugins/security_solution/public/resolver/view/submenu.tsx b/x-pack/plugins/security_solution/public/resolver/view/submenu.tsx index 6312991ddb743..e24c4b5664e42 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/submenu.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/submenu.tsx @@ -8,7 +8,7 @@ import { i18n } from '@kbn/i18n'; import React, { useMemo } from 'react'; import { FormattedMessage } from 'react-intl'; import { EuiI18nNumber } from '@elastic/eui'; -import { ResolverNodeStats } from '../../../common/endpoint/types'; +import { EventStats } from '../../../common/endpoint/types'; import { useRelatedEventByCategoryNavigation } from './use_related_event_by_category_navigation'; import { useColors } from './use_colors'; @@ -67,7 +67,7 @@ export const NodeSubMenuComponents = React.memo( ({ className, nodeID, - relatedEventStats, + nodeStats, }: { className?: string; // eslint-disable-next-line react/no-unused-prop-types @@ -76,18 +76,18 @@ export const NodeSubMenuComponents = React.memo( * Receive the projection matrix, so we can see when the camera position changed, so we can force the submenu to reposition itself. */ nodeID: string; - relatedEventStats: ResolverNodeStats | undefined; + nodeStats: EventStats | undefined; }) => { // The last projection matrix that was used to position the popover const relatedEventCallbacks = useRelatedEventByCategoryNavigation({ nodeID, - categories: relatedEventStats?.events?.byCategory, + categories: nodeStats?.byCategory, }); const relatedEventOptions = useMemo(() => { - if (relatedEventStats === undefined) { + if (nodeStats === undefined) { return []; } else { - return Object.entries(relatedEventStats.events.byCategory).map(([category, total]) => { + return Object.entries(nodeStats.byCategory).map(([category, total]) => { const [mantissa, scale, hasRemainder] = compactNotationParts(total || 0); const prefix = ( { diff --git a/x-pack/plugins/security_solution/public/resolver/view/symbol_definitions.tsx b/x-pack/plugins/security_solution/public/resolver/view/symbol_definitions.tsx index edf551c6cbeb9..b06cce11661e8 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/symbol_definitions.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/symbol_definitions.tsx @@ -8,10 +8,59 @@ import React, { memo } from 'react'; import styled from 'styled-components'; +import { i18n } from '@kbn/i18n'; import { useUiSetting } from '../../../../../../src/plugins/kibana_react/public'; import { useSymbolIDs } from './use_symbol_ids'; import { usePaintServerIDs } from './use_paint_server_ids'; +const loadingProcessTitle = i18n.translate( + 'xpack.securitySolution.resolver.symbolDefinitions.loadingProcess', + { + defaultMessage: 'Loading Process', + } +); + +const errorProcessTitle = i18n.translate( + 'xpack.securitySolution.resolver.symbolDefinitions.errorProcess', + { + defaultMessage: 'Error Process', + } +); + +const runningProcessTitle = i18n.translate( + 'xpack.securitySolution.resolver.symbolDefinitions.runningProcess', + { + defaultMessage: 'Running Process', + } +); + +const triggerProcessTitle = i18n.translate( + 'xpack.securitySolution.resolver.symbolDefinitions.triggerProcess', + { + defaultMessage: 'Trigger Process', + } +); + +const terminatedProcessTitle = i18n.translate( + 'xpack.securitySolution.resolver.symbolDefinitions.terminatedProcess', + { + defaultMessage: 'Terminated Process', + } +); + +const terminatedTriggerProcessTitle = i18n.translate( + 'xpack.securitySolution.resolver.symbolDefinitions.terminatedTriggerProcess', + { + defaultMessage: 'Terminated Trigger Process', + } +); + +const hoveredProcessBackgroundTitle = i18n.translate( + 'xpack.securitySolution.resolver.symbolDefinitions.hoveredProcessBackground', + { + defaultMessage: 'Hovered Process Background', + } +); /** * PaintServers: Where color palettes, gradients, patterns and other similar concerns * are exposed to the component @@ -20,6 +69,17 @@ const PaintServers = memo(({ isDarkMode }: { isDarkMode: boolean }) => { const paintServerIDs = usePaintServerIDs(); return ( <> + + + + { paintOrder="normal" /> + + {loadingProcessTitle} + + + + {errorProcessTitle} + + + + + + + - {'Running Process'} + {runningProcessTitle} { /> - {'resolver_dark process running'} + {triggerProcessTitle} { /> - {'Terminated Process'} + {terminatedProcessTitle} { - {'Terminated Trigger Process'} + {terminatedTriggerProcessTitle} {isDarkMode && ( { - {'resolver active backing'} + {hoveredProcessBackgroundTitle} { /** Enzyme full DOM wrapper for the element the camera is attached to. */ @@ -247,43 +248,48 @@ describe('useCamera on an unpainted element', () => { expect(simulator.mock.requestAnimationFrame).not.toHaveBeenCalled(); }); describe('when the camera begins animation', () => { - let process: SafeResolverEvent; + let node: ResolverNode; beforeEach(async () => { - const events: SafeResolverEvent[] = []; - const numberOfEvents: number = 10; + const nodes: ResolverNode[] = []; + const numberOfNodes: number = 10; - for (let index = 0; index < numberOfEvents; index++) { - const uniquePpid = index === 0 ? undefined : index - 1; - events.push( - mockProcessEvent({ - endgame: { - unique_pid: index, - unique_ppid: uniquePpid, - event_type_full: 'process_event', - event_subtype_full: 'creation_event', - }, + for (let index = 0; index < numberOfNodes; index++) { + const parentID = index === 0 ? undefined : String(index - 1); + nodes.push( + mockResolverNode({ + id: String(index), + name: '', + parentID, + timestamp: 0, + stats: { total: 0, byCategory: {} }, }) ); } - const tree = mockResolverTree({ events }); + const tree = mockResolverTree({ nodes }); if (tree !== null) { + const { schema, dataSource } = endpointSourceSchema(); const serverResponseAction: ResolverAction = { type: 'serverReturnedResolverData', - payload: { result: tree, parameters: mockTreeFetcherParameters() }, + payload: { + result: tree, + dataSource, + schema, + parameters: mockTreeFetcherParameters(), + }, }; store.dispatch(serverResponseAction); } else { throw new Error('failed to create tree'); } - const processes: SafeResolverEvent[] = [ + const resolverNodes: ResolverNode[] = [ ...selectors.layout(store.getState()).processNodePositions.keys(), ]; - process = processes[processes.length - 1]; + node = resolverNodes[resolverNodes.length - 1]; if (!process) { throw new Error('missing the process to bring into view'); } simulator.controls.time = 0; - const nodeID = entityIDSafeVersion(process); + const nodeID = nodeModel.nodeID(node); if (!nodeID) { throw new Error('could not find nodeID for process'); } diff --git a/x-pack/plugins/security_solution/public/resolver/view/use_colors.ts b/x-pack/plugins/security_solution/public/resolver/view/use_colors.ts index 7daf181a7b2bb..90ce5dc22d177 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/use_colors.ts +++ b/x-pack/plugins/security_solution/public/resolver/view/use_colors.ts @@ -15,6 +15,7 @@ type ResolverColorNames = | 'full' | 'graphControls' | 'graphControlsBackground' + | 'graphControlsBorderColor' | 'linkColor' | 'resolverBackground' | 'resolverEdge' @@ -38,6 +39,7 @@ export function useColors(): ColorMap { full: theme.euiColorFullShade, graphControls: theme.euiColorDarkestShade, graphControlsBackground: theme.euiColorEmptyShade, + graphControlsBorderColor: theme.euiColorLightShade, processBackingFill: `${theme.euiColorPrimary}${isDarkMode ? '1F' : '0F'}`, // Add opacity 0F = 6% , 1F = 12% resolverBackground: theme.euiColorEmptyShade, resolverEdge: isDarkMode ? theme.euiColorLightShade : theme.euiColorLightestShade, diff --git a/x-pack/plugins/security_solution/public/resolver/view/use_cube_assets.ts b/x-pack/plugins/security_solution/public/resolver/view/use_cube_assets.ts index c743ebc43f2be..94f08c5f3fee3 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/use_cube_assets.ts +++ b/x-pack/plugins/security_solution/public/resolver/view/use_cube_assets.ts @@ -10,7 +10,7 @@ import { ButtonColor } from '@elastic/eui'; import euiThemeAmsterdamDark from '@elastic/eui/dist/eui_theme_amsterdam_dark.json'; import euiThemeAmsterdamLight from '@elastic/eui/dist/eui_theme_amsterdam_light.json'; import { useMemo } from 'react'; -import { ResolverProcessType } from '../types'; +import { ResolverProcessType, NodeDataStatus } from '../types'; import { useUiSetting } from '../../../../../../src/plugins/kibana_react/public'; import { useSymbolIDs } from './use_symbol_ids'; import { useColors } from './use_colors'; @@ -19,7 +19,7 @@ import { useColors } from './use_colors'; * Provides colors and HTML IDs used to render the 'cube' graphic that accompanies nodes. */ export function useCubeAssets( - isProcessTerminated: boolean, + cubeType: NodeDataStatus, isProcessTrigger: boolean ): NodeStyleConfig { const SymbolIds = useSymbolIDs(); @@ -40,6 +40,28 @@ export function useCubeAssets( labelButtonFill: 'primary', strokeColor: theme.euiColorPrimary, }, + loadingCube: { + backingFill: colorMap.processBackingFill, + cubeSymbol: `#${SymbolIds.loadingCube}`, + descriptionFill: colorMap.descriptionText, + descriptionText: i18n.translate('xpack.securitySolution.endpoint.resolver.loadingProcess', { + defaultMessage: 'Loading Process', + }), + isLabelFilled: false, + labelButtonFill: 'primary', + strokeColor: theme.euiColorPrimary, + }, + errorCube: { + backingFill: colorMap.processBackingFill, + cubeSymbol: `#${SymbolIds.errorCube}`, + descriptionFill: colorMap.descriptionText, + descriptionText: i18n.translate('xpack.securitySolution.endpoint.resolver.errorProcess', { + defaultMessage: 'Error Process', + }), + isLabelFilled: false, + labelButtonFill: 'primary', + strokeColor: theme.euiColorPrimary, + }, runningTriggerCube: { backingFill: colorMap.triggerBackingFill, cubeSymbol: `#${SymbolIds.runningTriggerCube}`, @@ -83,16 +105,22 @@ export function useCubeAssets( [SymbolIds, colorMap, theme] ); - if (isProcessTerminated) { + if (cubeType === 'terminated') { if (isProcessTrigger) { return nodeAssets.terminatedTriggerCube; } else { return nodeAssets[processTypeToCube.processTerminated]; } - } else if (isProcessTrigger) { - return nodeAssets[processTypeToCube.processCausedAlert]; + } else if (cubeType === 'running') { + if (isProcessTrigger) { + return nodeAssets[processTypeToCube.processCausedAlert]; + } else { + return nodeAssets[processTypeToCube.processRan]; + } + } else if (cubeType === 'error') { + return nodeAssets[processTypeToCube.processError]; } else { - return nodeAssets[processTypeToCube.processRan]; + return nodeAssets[processTypeToCube.processLoading]; } } @@ -102,6 +130,8 @@ const processTypeToCube: Record = { processTerminated: 'terminatedProcessCube', unknownProcessEvent: 'runningProcessCube', processCausedAlert: 'runningTriggerCube', + processLoading: 'loadingCube', + processError: 'errorCube', unknownEvent: 'runningProcessCube', }; interface NodeStyleMap { @@ -109,6 +139,8 @@ interface NodeStyleMap { runningTriggerCube: NodeStyleConfig; terminatedProcessCube: NodeStyleConfig; terminatedTriggerCube: NodeStyleConfig; + loadingCube: NodeStyleConfig; + errorCube: NodeStyleConfig; } interface NodeStyleConfig { backingFill: string; diff --git a/x-pack/plugins/security_solution/public/resolver/view/use_paint_server_ids.ts b/x-pack/plugins/security_solution/public/resolver/view/use_paint_server_ids.ts index 0336a29bb0721..10fbd58a9deb3 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/use_paint_server_ids.ts +++ b/x-pack/plugins/security_solution/public/resolver/view/use_paint_server_ids.ts @@ -23,6 +23,8 @@ export function usePaintServerIDs() { runningTriggerCube: `${prefix}-psRunningTriggerCube`, terminatedProcessCube: `${prefix}-psTerminatedProcessCube`, terminatedTriggerCube: `${prefix}-psTerminatedTriggerCube`, + loadingCube: `${prefix}-psLoadingCube`, + errorCube: `${prefix}-psErrorCube`, }; }, [resolverComponentInstanceID]); } diff --git a/x-pack/plugins/security_solution/public/resolver/view/use_symbol_ids.ts b/x-pack/plugins/security_solution/public/resolver/view/use_symbol_ids.ts index 0e1fd5737a3ce..da00d4c0dbf43 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/use_symbol_ids.ts +++ b/x-pack/plugins/security_solution/public/resolver/view/use_symbol_ids.ts @@ -25,6 +25,8 @@ export function useSymbolIDs() { terminatedProcessCube: `${prefix}-terminatedCube`, terminatedTriggerCube: `${prefix}-terminatedTriggerCube`, processCubeActiveBacking: `${prefix}-activeBacking`, + loadingCube: `${prefix}-loadingCube`, + errorCube: `${prefix}-errorCube`, }; }, [resolverComponentInstanceID]); } diff --git a/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx index 5b558df8388e4..b53c11868998f 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx @@ -72,7 +72,7 @@ const NavigationComponent: React.FC = ({ timelineFullScreen, toggleFullScreen, }) => ( - + {i18n.CLOSE_ANALYZER} diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.test.ts b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.test.ts index 5a1540b970300..6c76da44c8557 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.test.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.test.ts @@ -312,10 +312,12 @@ describe('helpers', () => { selectedEventIds: {}, show: false, showCheckboxes: false, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, + sort: [ + { + columnId: '@timestamp', + sortDirection: 'desc', + }, + ], status: TimelineStatus.draft, title: '', timelineType: TimelineType.default, @@ -411,10 +413,12 @@ describe('helpers', () => { selectedEventIds: {}, show: false, showCheckboxes: false, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, + sort: [ + { + columnId: '@timestamp', + sortDirection: 'desc', + }, + ], status: TimelineStatus.draft, title: '', timelineType: TimelineType.template, @@ -510,10 +514,12 @@ describe('helpers', () => { selectedEventIds: {}, show: false, showCheckboxes: false, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, + sort: [ + { + columnId: '@timestamp', + sortDirection: 'desc', + }, + ], status: TimelineStatus.draft, title: '', timelineType: TimelineType.default, @@ -607,10 +613,12 @@ describe('helpers', () => { selectedEventIds: {}, show: false, showCheckboxes: false, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, + sort: [ + { + columnId: '@timestamp', + sortDirection: 'desc', + }, + ], status: TimelineStatus.draft, title: '', timelineType: TimelineType.default, @@ -745,10 +753,12 @@ describe('helpers', () => { selectedEventIds: {}, show: false, showCheckboxes: false, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, + sort: [ + { + columnId: '@timestamp', + sortDirection: 'desc', + }, + ], status: TimelineStatus.draft, id: 'savedObject-1', }); @@ -912,10 +922,12 @@ describe('helpers', () => { selectedEventIds: {}, show: false, showCheckboxes: false, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, + sort: [ + { + columnId: '@timestamp', + sortDirection: 'desc', + }, + ], status: TimelineStatus.draft, id: 'savedObject-1', }); @@ -1007,10 +1019,12 @@ describe('helpers', () => { selectedEventIds: {}, show: false, showCheckboxes: false, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, + sort: [ + { + columnId: '@timestamp', + sortDirection: 'desc', + }, + ], status: TimelineStatus.immutable, title: 'Awesome Timeline', timelineType: TimelineType.template, @@ -1106,10 +1120,12 @@ describe('helpers', () => { selectedEventIds: {}, show: false, showCheckboxes: false, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, + sort: [ + { + columnId: '@timestamp', + sortDirection: 'desc', + }, + ], status: TimelineStatus.active, title: 'Awesome Timeline', timelineType: TimelineType.default, diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.ts b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.ts index 1ee529cc77a91..76eb9196e8c5c 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.ts @@ -108,21 +108,20 @@ const parseString = (params: string) => { } }; -const setTimelineColumn = (col: ColumnHeaderResult) => { - const timelineCols: ColumnHeaderOptions = { - ...col, - columnHeaderType: defaultColumnHeaderType, - id: col.id != null ? col.id : 'unknown', - placeholder: col.placeholder != null ? col.placeholder : undefined, - category: col.category != null ? col.category : undefined, - description: col.description != null ? col.description : undefined, - example: col.example != null ? col.example : undefined, - type: col.type != null ? col.type : undefined, - aggregatable: col.aggregatable != null ? col.aggregatable : undefined, - width: col.id === '@timestamp' ? DEFAULT_DATE_COLUMN_MIN_WIDTH : DEFAULT_COLUMN_MIN_WIDTH, - }; - return timelineCols; -}; +const setTimelineColumn = (col: ColumnHeaderResult) => + Object.entries(col).reduce( + (acc, [key, value]) => { + if (key !== 'id' && value != null) { + return { ...acc, [key]: value }; + } + return acc; + }, + { + columnHeaderType: defaultColumnHeaderType, + id: col.id != null ? col.id : 'unknown', + width: col.id === '@timestamp' ? DEFAULT_DATE_COLUMN_MIN_WIDTH : DEFAULT_COLUMN_MIN_WIDTH, + } + ); const setTimelineFilters = (filter: FilterTimelineResult) => ({ $state: { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/__snapshots__/index.test.tsx.snap index 7772bcede76fc..36e0652c3032a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/__snapshots__/index.test.tsx.snap @@ -2,7 +2,7 @@ exports[`ColumnHeaders rendering renders correctly against snapshot 1`] = ` diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/actions/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/actions/index.tsx index c4c4e0e0c7065..8ec8827ccbed6 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/actions/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/actions/index.tsx @@ -18,7 +18,7 @@ interface Props { header: ColumnHeaderOptions; isLoading: boolean; onColumnRemoved: OnColumnRemoved; - sort: Sort; + sort: Sort[]; } /** Given a `header`, returns the `SortDirection` applicable to it */ @@ -53,7 +53,7 @@ CloseButton.displayName = 'CloseButton'; export const Actions = React.memo(({ header, onColumnRemoved, sort, isLoading }) => { return ( <> - {sort.columnId === header.id && isLoading ? ( + {sort.some((i) => i.columnId === header.id) && isLoading ? ( diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/column_header.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/column_header.tsx index 8bf9b6ceb346a..543ffe2798947 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/column_header.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/column_header.tsx @@ -26,7 +26,7 @@ interface ColumneHeaderProps { header: ColumnHeaderOptions; isDragging: boolean; onFilterChange?: OnFilterChange; - sort: Sort; + sort: Sort[]; timelineId: string; } @@ -131,6 +131,6 @@ export const ColumnHeader = React.memo( prevProps.timelineId === nextProps.timelineId && prevProps.isDragging === nextProps.isDragging && prevProps.onFilterChange === nextProps.onFilterChange && - prevProps.sort === nextProps.sort && + deepEqual(prevProps.sort, nextProps.sort) && deepEqual(prevProps.header, nextProps.header) ); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/__snapshots__/index.test.tsx.snap index 517f537b9a01b..fa9a4e78d88f2 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/__snapshots__/index.test.tsx.snap @@ -14,10 +14,12 @@ exports[`Header renders correctly against snapshot 1`] = ` isResizing={false} onClick={[Function]} sort={ - Object { - "columnId": "@timestamp", - "sortDirection": "desc", - } + Array [ + Object { + "columnId": "@timestamp", + "sortDirection": "desc", + }, + ] } > diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/header_content.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/header_content.tsx index 19d0220cd3462..656cf234ea662 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/header_content.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/header_content.tsx @@ -14,15 +14,14 @@ import { EventsHeading, EventsHeadingTitleButton, EventsHeadingTitleSpan } from import { Sort } from '../../sort'; import { SortIndicator } from '../../sort/sort_indicator'; import { HeaderToolTipContent } from '../header_tooltip_content'; -import { getSortDirection } from './helpers'; - +import { getSortDirection, getSortIndex } from './helpers'; interface HeaderContentProps { children: React.ReactNode; header: ColumnHeaderOptions; isLoading: boolean; isResizing: boolean; onClick: () => void; - sort: Sort; + sort: Sort[]; } const HeaderContentComponent: React.FC = ({ @@ -33,7 +32,7 @@ const HeaderContentComponent: React.FC = ({ onClick, sort, }) => ( - + {header.aggregatable ? ( = ({ ) : ( diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/helpers.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/helpers.ts index 609f690903bf2..b2ad186ce1b1e 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/helpers.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/helpers.ts @@ -11,7 +11,7 @@ import { Sort, SortDirection } from '../../sort'; interface GetNewSortDirectionOnClickParams { clickedHeader: ColumnHeaderOptions; - currentSort: Sort; + currentSort: Sort[]; } /** Given a `header`, returns the `SortDirection` applicable to it */ @@ -19,7 +19,10 @@ export const getNewSortDirectionOnClick = ({ clickedHeader, currentSort, }: GetNewSortDirectionOnClickParams): Direction => - clickedHeader.id === currentSort.columnId ? getNextSortDirection(currentSort) : Direction.desc; + currentSort.reduce( + (acc, item) => (clickedHeader.id === item.columnId ? getNextSortDirection(item) : acc), + Direction.desc + ); /** Given a current sort direction, it returns the next sort direction */ export const getNextSortDirection = (currentSort: Sort): Direction => { @@ -37,8 +40,14 @@ export const getNextSortDirection = (currentSort: Sort): Direction => { interface GetSortDirectionParams { header: ColumnHeaderOptions; - sort: Sort; + sort: Sort[]; } export const getSortDirection = ({ header, sort }: GetSortDirectionParams): SortDirection => - header.id === sort.columnId ? sort.sortDirection : 'none'; + sort.reduce( + (acc, item) => (header.id === item.columnId ? item.sortDirection : acc), + 'none' + ); + +export const getSortIndex = ({ header, sort }: GetSortDirectionParams): number => + sort.findIndex((s) => s.columnId === header.id); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/index.test.tsx index 3ef9beb89309e..58d40c94ac338 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/index.test.tsx @@ -32,10 +32,12 @@ const filteredColumnHeader: ColumnHeaderType = 'text-filter'; describe('Header', () => { const columnHeader = defaultHeaders[0]; - const sort: Sort = { - columnId: columnHeader.id, - sortDirection: Direction.desc, - }; + const sort: Sort[] = [ + { + columnId: columnHeader.id, + sortDirection: Direction.desc, + }, + ]; const timelineId = 'fakeId'; test('renders correctly against snapshot', () => { @@ -119,10 +121,12 @@ describe('Header', () => { expect(mockDispatch).toBeCalledWith( timelineActions.updateSort({ id: timelineId, - sort: { - columnId: columnHeader.id, - sortDirection: Direction.asc, // (because the previous state was Direction.desc) - }, + sort: [ + { + columnId: columnHeader.id, + sortDirection: Direction.asc, // (because the previous state was Direction.desc) + }, + ], }) ); }); @@ -158,7 +162,7 @@ describe('Header', () => { ); - wrapper.find('[data-test-subj="header"]').first().simulate('click'); + wrapper.find(`[data-test-subj="header-${columnHeader.id}"]`).first().simulate('click'); expect(mockOnColumnSorted).not.toHaveBeenCalled(); }); @@ -180,14 +184,16 @@ describe('Header', () => { describe('getSortDirection', () => { test('it returns the sort direction when the header id matches the sort column id', () => { - expect(getSortDirection({ header: columnHeader, sort })).toEqual(sort.sortDirection); + expect(getSortDirection({ header: columnHeader, sort })).toEqual(sort[0].sortDirection); }); test('it returns "none" when sort direction when the header id does NOT match the sort column id', () => { - const nonMatching: Sort = { - columnId: 'differentSocks', - sortDirection: Direction.desc, - }; + const nonMatching: Sort[] = [ + { + columnId: 'differentSocks', + sortDirection: Direction.desc, + }, + ]; expect(getSortDirection({ header: columnHeader, sort: nonMatching })).toEqual('none'); }); @@ -221,10 +227,12 @@ describe('Header', () => { describe('getNewSortDirectionOnClick', () => { test('it returns the expected new sort direction when the header id matches the sort column id', () => { - const sortMatches: Sort = { - columnId: columnHeader.id, - sortDirection: Direction.desc, - }; + const sortMatches: Sort[] = [ + { + columnId: columnHeader.id, + sortDirection: Direction.desc, + }, + ]; expect( getNewSortDirectionOnClick({ @@ -235,10 +243,12 @@ describe('Header', () => { }); test('it returns the expected new sort direction when the header id does NOT match the sort column id', () => { - const sortDoesNotMatch: Sort = { - columnId: 'someOtherColumn', - sortDirection: 'none', - }; + const sortDoesNotMatch: Sort[] = [ + { + columnId: 'someOtherColumn', + sortDirection: 'none', + }, + ]; expect( getNewSortDirectionOnClick({ diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/index.tsx index 15d75cc9a4384..192a9c6b0973b 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header/index.tsx @@ -21,7 +21,7 @@ import { useManageTimeline } from '../../../../manage_timeline'; interface Props { header: ColumnHeaderOptions; onFilterChange?: OnFilterChange; - sort: Sort; + sort: Sort[]; timelineId: string; } @@ -33,22 +33,39 @@ export const HeaderComponent: React.FC = ({ }) => { const dispatch = useDispatch(); - const onClick = useCallback( - () => - dispatch( - timelineActions.updateSort({ - id: timelineId, - sort: { - columnId: header.id, - sortDirection: getNewSortDirectionOnClick({ - clickedHeader: header, - currentSort: sort, - }), - }, - }) - ), - [dispatch, header, timelineId, sort] - ); + const onColumnSort = useCallback(() => { + const columnId = header.id; + const sortDirection = getNewSortDirectionOnClick({ + clickedHeader: header, + currentSort: sort, + }); + const headerIndex = sort.findIndex((col) => col.columnId === columnId); + let newSort = []; + if (headerIndex === -1) { + newSort = [ + ...sort, + { + columnId, + sortDirection, + }, + ]; + } else { + newSort = [ + ...sort.slice(0, headerIndex), + { + columnId, + sortDirection, + }, + ...sort.slice(headerIndex + 1), + ]; + } + dispatch( + timelineActions.updateSort({ + id: timelineId, + sort: newSort, + }) + ); + }, [dispatch, header, sort, timelineId]); const onColumnRemoved = useCallback( (columnId) => dispatch(timelineActions.removeColumn({ id: timelineId, columnId })), @@ -68,7 +85,7 @@ export const HeaderComponent: React.FC = ({ header={header} isLoading={isLoading} isResizing={false} - onClick={onClick} + onClick={onColumnSort} sort={sort} > { + const original = jest.requireActual('react-redux'); + + return { + ...original, + useDispatch: () => mockDispatch, + }; +}); +const timelineId = 'test'; describe('ColumnHeaders', () => { const mount = useMountAppended(); describe('rendering', () => { - const sort: Sort = { - columnId: 'fooColumn', - sortDirection: Direction.desc, - }; + const sort: Sort[] = [ + { + columnId: '@timestamp', + sortDirection: Direction.desc, + }, + ]; test('renders correctly against snapshot', () => { const wrapper = shallow( @@ -39,7 +54,7 @@ describe('ColumnHeaders', () => { showEventsSelect={false} showSelectAllCheckbox={false} sort={sort} - timelineId={'test'} + timelineId={timelineId} /> ); @@ -58,7 +73,7 @@ describe('ColumnHeaders', () => { showEventsSelect={false} showSelectAllCheckbox={false} sort={sort} - timelineId={'test'} + timelineId={timelineId} /> ); @@ -78,7 +93,7 @@ describe('ColumnHeaders', () => { showEventsSelect={false} showSelectAllCheckbox={false} sort={sort} - timelineId={'test'} + timelineId={timelineId} /> ); @@ -88,4 +103,145 @@ describe('ColumnHeaders', () => { }); }); }); + + describe('#onColumnsSorted', () => { + let mockSort: Sort[] = [ + { + columnId: '@timestamp', + sortDirection: Direction.desc, + }, + { + columnId: 'host.name', + sortDirection: Direction.asc, + }, + ]; + let mockDefaultHeaders = cloneDeep( + defaultHeaders.map((h) => (h.id === 'message' ? h : { ...h, aggregatable: true })) + ); + + beforeEach(() => { + mockDefaultHeaders = cloneDeep( + defaultHeaders.map((h) => (h.id === 'message' ? h : { ...h, aggregatable: true })) + ); + mockSort = [ + { + columnId: '@timestamp', + sortDirection: Direction.desc, + }, + { + columnId: 'host.name', + sortDirection: Direction.asc, + }, + ]; + }); + + test('Add column `event.category` as desc sorting', () => { + const wrapper = mount( + + + + ); + + wrapper + .find('[data-test-subj="header-event.category"] [data-test-subj="header-sort-button"]') + .first() + .simulate('click'); + expect(mockDispatch).toHaveBeenCalledWith( + timelineActions.updateSort({ + id: timelineId, + sort: [ + { + columnId: '@timestamp', + sortDirection: Direction.desc, + }, + { + columnId: 'host.name', + sortDirection: Direction.asc, + }, + { columnId: 'event.category', sortDirection: Direction.desc }, + ], + }) + ); + }); + + test('Change order of column `@timestamp` from desc to asc without changing index position', () => { + const wrapper = mount( + + + + ); + + wrapper + .find('[data-test-subj="header-@timestamp"] [data-test-subj="header-sort-button"]') + .first() + .simulate('click'); + expect(mockDispatch).toHaveBeenCalledWith( + timelineActions.updateSort({ + id: timelineId, + sort: [ + { + columnId: '@timestamp', + sortDirection: Direction.asc, + }, + { columnId: 'host.name', sortDirection: Direction.asc }, + ], + }) + ); + }); + + test('Change order of column `host.name` from asc to desc without changing index position', () => { + const wrapper = mount( + + + + ); + + wrapper + .find('[data-test-subj="header-host.name"] [data-test-subj="header-sort-button"]') + .first() + .simulate('click'); + expect(mockDispatch).toHaveBeenCalledWith( + timelineActions.updateSort({ + id: timelineId, + sort: [ + { + columnId: '@timestamp', + sortDirection: Direction.desc, + }, + { columnId: 'host.name', sortDirection: Direction.desc }, + ], + }) + ); + }); + }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/index.tsx index aeab6a774ca41..66856f3bd6284 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/index.tsx @@ -4,10 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiButtonIcon, EuiCheckbox, EuiToolTip } from '@elastic/eui'; +import { + EuiButtonIcon, + EuiCheckbox, + EuiDataGridSorting, + EuiToolTip, + useDataGridColumnSorting, +} from '@elastic/eui'; +import deepEqual from 'fast-deep-equal'; import React, { useState, useEffect, useCallback, useMemo } from 'react'; import { Droppable, DraggableChildrenFn } from 'react-beautiful-dnd'; -import deepEqual from 'fast-deep-equal'; +import { useDispatch } from 'react-redux'; +import styled from 'styled-components'; import { DragEffects } from '../../../../../common/components/drag_and_drop/draggable_wrapper'; import { DraggableFieldBadge } from '../../../../../common/components/draggables/field_badge'; @@ -34,11 +42,18 @@ import { EventsThGroupData, EventsTrHeader, } from '../../styles'; -import { Sort } from '../sort'; +import { Sort, SortDirection } from '../sort'; import { EventsSelect } from './events_select'; import { ColumnHeader } from './column_header'; import * as i18n from './translations'; +import { timelineActions } from '../../../../store/timeline'; + +const SortingColumnsContainer = styled.div` + .euiPopover .euiButtonEmpty .euiButtonContent .euiButtonEmpty__text { + display: none; + } +`; interface Props { actionsColumnWidth: number; @@ -49,7 +64,7 @@ interface Props { onSelectAll: OnSelectAll; showEventsSelect: boolean; showSelectAllCheckbox: boolean; - sort: Sort; + sort: Sort[]; timelineId: string; } @@ -98,6 +113,7 @@ export const ColumnHeadersComponent = ({ sort, timelineId, }: Props) => { + const dispatch = useDispatch(); const [draggingIndex, setDraggingIndex] = useState(null); const { timelineFullScreen, @@ -189,6 +205,48 @@ export const ColumnHeadersComponent = ({ [ColumnHeaderList] ); + const myColumns = useMemo( + () => + columnHeaders.map(({ aggregatable, label, id, type }) => ({ + id, + isSortable: aggregatable, + displayAsText: label, + schema: type, + })), + [columnHeaders] + ); + + const onSortColumns = useCallback( + (cols: EuiDataGridSorting['columns']) => + dispatch( + timelineActions.updateSort({ + id: timelineId, + sort: cols.map(({ id, direction }) => ({ + columnId: id, + sortDirection: direction as SortDirection, + })), + }) + ), + [dispatch, timelineId] + ); + const sortedColumns = useMemo( + () => ({ + onSort: onSortColumns, + columns: sort.map<{ id: string; direction: 'asc' | 'desc' }>( + ({ columnId, sortDirection }) => ({ + id: columnId, + direction: sortDirection as 'asc' | 'desc', + }) + ), + }), + [onSortColumns, sort] + ); + const displayValues = useMemo( + () => columnHeaders.reduce((acc, ch) => ({ ...acc, [ch.id]: ch.label ?? ch.id }), {}), + [columnHeaders] + ); + const ColumnSorting = useDataGridColumnSorting(myColumns, sortedColumns, {}, [], displayValues); + return ( @@ -245,6 +303,13 @@ export const ColumnHeadersComponent = ({ + + + + {ColumnSorting} + + + {showEventsSelect && ( @@ -278,7 +343,7 @@ export const ColumnHeaders = React.memo( prevProps.onSelectAll === nextProps.onSelectAll && prevProps.showEventsSelect === nextProps.showEventsSelect && prevProps.showSelectAllCheckbox === nextProps.showSelectAllCheckbox && - prevProps.sort === nextProps.sort && + deepEqual(prevProps.sort, nextProps.sort) && prevProps.timelineId === nextProps.timelineId && deepEqual(prevProps.columnHeaders, nextProps.columnHeaders) && deepEqual(prevProps.browserFields, nextProps.browserFields) diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/translations.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/translations.ts index 1ebfa957b654f..c946182ddfe06 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/translations.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/translations.ts @@ -22,6 +22,10 @@ export const FULL_SCREEN = i18n.translate('xpack.securitySolution.timeline.fullS defaultMessage: 'Full screen', }); +export const SORT_FIELDS = i18n.translate('xpack.securitySolution.timeline.sortFieldsButton', { + defaultMessage: 'Sort fields', +}); + export const TYPE = i18n.translate('xpack.securitySolution.timeline.typeTooltip', { defaultMessage: 'Type', }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/constants.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/constants.ts index 6fddb5403561e..bf70d7bff1ff5 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/constants.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/constants.ts @@ -7,15 +7,17 @@ /** The minimum (fixed) width of the Actions column */ export const MINIMUM_ACTIONS_COLUMN_WIDTH = 50; // px; +/** Additional column width to include when checkboxes are shown **/ +export const SHOW_CHECK_BOXES_COLUMN_WIDTH = 24; // px; + /** The (fixed) width of the Actions column */ -export const DEFAULT_ACTIONS_COLUMN_WIDTH = 24 * 4; // px; +export const DEFAULT_ACTIONS_COLUMN_WIDTH = SHOW_CHECK_BOXES_COLUMN_WIDTH * 5; // px; /** * The (fixed) width of the Actions column when the timeline body is used as * an events viewer, which has fewer actions than a regular events viewer */ -export const EVENTS_VIEWER_ACTIONS_COLUMN_WIDTH = 24 * 3; // px; -/** Additional column width to include when checkboxes are shown **/ -export const SHOW_CHECK_BOXES_COLUMN_WIDTH = 24; // px; +export const EVENTS_VIEWER_ACTIONS_COLUMN_WIDTH = SHOW_CHECK_BOXES_COLUMN_WIDTH * 4; // px; + /** The default minimum width of a column (when a width for the column type is not specified) */ export const DEFAULT_COLUMN_MIN_WIDTH = 180; // px /** The default minimum width of a column of type `date` */ diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.tsx index 1d4cea700d003..0dae9a97b6e5b 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.tsx @@ -117,7 +117,9 @@ export const getEventType = (event: Ecs): Omit => { }; export const isInvestigateInResolverActionEnabled = (ecsData?: Ecs) => - get(['agent', 'type', 0], ecsData) === 'endpoint' && + (get(['agent', 'type', 0], ecsData) === 'endpoint' || + (get(['agent', 'type', 0], ecsData) === 'winlogbeat' && + get(['event', 'module', 0], ecsData) === 'sysmon')) && get(['process', 'entity_id'], ecsData)?.length === 1 && get(['process', 'entity_id', 0], ecsData) !== ''; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx index fc9967bdeff98..704af61b4a12f 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx @@ -16,13 +16,14 @@ import { TestProviders } from '../../../../common/mock/test_providers'; import { BodyComponent, StatefulBodyProps } from '.'; import { Sort } from './sort'; import { useMountAppended } from '../../../../common/utils/use_mount_appended'; -import { SELECTOR_TIMELINE_BODY_CLASS_NAME } from '../styles'; import { timelineActions } from '../../../store/timeline'; -const mockSort: Sort = { - columnId: '@timestamp', - sortDirection: Direction.desc, -}; +const mockSort: Sort[] = [ + { + columnId: '@timestamp', + sortDirection: Direction.desc, + }, +]; const mockDispatch = jest.fn(); jest.mock('react-redux', () => { @@ -130,20 +131,6 @@ describe('Body', () => { }); }); }, 20000); - - test(`it add attribute data-timeline-id in ${SELECTOR_TIMELINE_BODY_CLASS_NAME}`, () => { - const wrapper = mount( - - - - ); - expect( - wrapper - .find(`[data-timeline-id="timeline-test"].${SELECTOR_TIMELINE_BODY_CLASS_NAME}`) - .first() - .exists() - ).toEqual(true); - }); }); describe('action on event', () => { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx index 45641a34f2cf4..ea397b67c31cc 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx @@ -33,7 +33,7 @@ interface OwnProps { data: TimelineItem[]; id: string; isEventViewer?: boolean; - sort: Sort; + sort: Sort[]; refetch: inputsModel.Refetch; onRuleChange?: () => void; } @@ -144,7 +144,7 @@ export const BodyComponent = React.memo( return ( <> - + ); + } else if (fieldType === GEO_FIELD_TYPE) { + return <>{value}; } else if (fieldType === DATE_FIELD_TYPE) { return ( + `; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.test.tsx index dcaedb90e7252..6593abf71e368 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.test.tsx @@ -15,12 +15,12 @@ import { getDirection, SortIndicator } from './sort_indicator'; describe('SortIndicator', () => { describe('rendering', () => { test('renders correctly against snapshot', () => { - const wrapper = shallow(); + const wrapper = shallow(); expect(wrapper).toMatchSnapshot(); }); test('it renders the expected sort indicator when direction is ascending', () => { - const wrapper = mount(); + const wrapper = mount(); expect(wrapper.find('[data-test-subj="sortIndicator"]').first().prop('type')).toEqual( 'sortUp' @@ -28,7 +28,7 @@ describe('SortIndicator', () => { }); test('it renders the expected sort indicator when direction is descending', () => { - const wrapper = mount(); + const wrapper = mount(); expect(wrapper.find('[data-test-subj="sortIndicator"]').first().prop('type')).toEqual( 'sortDown' @@ -36,7 +36,7 @@ describe('SortIndicator', () => { }); test('it renders the expected sort indicator when direction is `none`', () => { - const wrapper = mount(); + const wrapper = mount(); expect(wrapper.find('[data-test-subj="sortIndicator"]').first().prop('type')).toEqual( 'empty' @@ -60,7 +60,7 @@ describe('SortIndicator', () => { describe('sort indicator tooltip', () => { test('it returns the expected tooltip when the direction is ascending', () => { - const wrapper = mount(); + const wrapper = mount(); expect( wrapper.find('[data-test-subj="sort-indicator-tooltip"]').first().props().content @@ -68,7 +68,7 @@ describe('SortIndicator', () => { }); test('it returns the expected tooltip when the direction is descending', () => { - const wrapper = mount(); + const wrapper = mount(); expect( wrapper.find('[data-test-subj="sort-indicator-tooltip"]').first().props().content @@ -76,7 +76,7 @@ describe('SortIndicator', () => { }); test('it does NOT render a tooltip when sort direction is `none`', () => { - const wrapper = mount(); + const wrapper = mount(); expect(wrapper.find('[data-test-subj="sort-indicator-tooltip"]').exists()).toBe(false); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.tsx index 8b842dfa2197e..518103e8cb643 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { Direction } from '../../../../../graphql/types'; import * as i18n from '../translations'; +import { SortNumber } from './sort_number'; import { SortDirection } from '.'; @@ -35,10 +36,11 @@ export const getDirection = (sortDirection: SortDirection): SortDirectionIndicat interface Props { sortDirection: SortDirection; + sortNumber: number; } /** Renders a sort indicator */ -export const SortIndicator = React.memo(({ sortDirection }) => { +export const SortIndicator = React.memo(({ sortDirection, sortNumber }) => { const direction = getDirection(sortDirection); if (direction != null) { @@ -51,7 +53,10 @@ export const SortIndicator = React.memo(({ sortDirection }) => { } data-test-subj="sort-indicator-tooltip" > - + <> + + + ); } else { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_number.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_number.tsx new file mode 100644 index 0000000000000..48dd70a16e70a --- /dev/null +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_number.tsx @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiIcon, EuiNotificationBadge } from '@elastic/eui'; +import React from 'react'; + +interface Props { + sortNumber: number; +} + +export const SortNumber = React.memo(({ sortNumber }) => { + if (sortNumber >= 0) { + return ( + + {sortNumber + 1} + + ); + } else { + return ; + } +}); + +SortNumber.displayName = 'SortNumber'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/events.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/events.ts index 54755fbc84277..11bc3da8c05bc 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/events.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/events.ts @@ -38,6 +38,10 @@ export type OnFilterChange = (filter: { columnId: ColumnId; filter: string }) => /** Invoked when a column is sorted */ export type OnColumnSorted = (sorted: { columnId: ColumnId; sortDirection: SortDirection }) => void; +export type OnColumnsSorted = ( + sorted: Array<{ columnId: ColumnId; sortDirection: SortDirection }> +) => void; + export type OnColumnRemoved = (columnId: ColumnId) => void; export type OnColumnResized = ({ columnId, delta }: { columnId: ColumnId; delta: number }) => void; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx index 085a9bf8cba3f..59a7b936dfbac 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx @@ -20,6 +20,7 @@ import { import { StatefulTimeline, Props as StatefulTimelineOwnProps } from './index'; import { useTimelineEvents } from '../../containers/index'; +import { SELECTOR_TIMELINE_GLOBAL_CONTAINER } from './styles'; jest.mock('../../containers/index', () => ({ useTimelineEvents: jest.fn(), @@ -56,7 +57,7 @@ jest.mock('../../../common/containers/sourcerer', () => { }); describe('StatefulTimeline', () => { const props: StatefulTimelineOwnProps = { - timelineId: 'id', + timelineId: 'timeline-test', }; beforeEach(() => { @@ -71,4 +72,18 @@ describe('StatefulTimeline', () => { ); expect(wrapper.find('[data-test-subj="timeline"]')).toBeTruthy(); }); + + test(`it add attribute data-timeline-id in ${SELECTOR_TIMELINE_GLOBAL_CONTAINER}`, () => { + const wrapper = mount( + + + + ); + expect( + wrapper + .find(`[data-timeline-id="timeline-test"].${SELECTOR_TIMELINE_GLOBAL_CONTAINER}`) + .first() + .exists() + ).toEqual(true); + }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx index 37145b9348ac1..4e6bca7fd9625 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx @@ -21,13 +21,7 @@ import { useDeepEqualSelector, useShallowEqualSelector } from '../../../common/h import { activeTimeline } from '../../containers/active_timeline_context'; import * as i18n from './translations'; import { TabsContent } from './tabs_content'; - -const TimelineContainer = styled.div` - height: 100%; - display: flex; - flex-direction: column; - position: relative; -`; +import { TimelineContainer } from './styles'; const TimelineTemplateBadge = styled.div` background: ${({ theme }) => theme.eui.euiColorVis3_behindText}; @@ -78,7 +72,7 @@ const StatefulTimelineComponent: React.FC = ({ timelineId }) => { }, []); return ( - + {timelineType === TimelineType.template && ( {i18n.TIMELINE_TEMPLATE} 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 c726e92455f25..c9355797193a0 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 @@ -276,10 +276,12 @@ In other use cases the message field can be used to concatenate different values showCallOutUnauthorizedMsg={false} showEventDetails={false} sort={ - Object { - "columnId": "@timestamp", - "sortDirection": "desc", - } + Array [ + Object { + "columnId": "@timestamp", + "sortDirection": "desc", + }, + ] } start="2018-03-23T18:49:23.132Z" status="active" 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 4019f46b8c07b..7e60461a01574 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 @@ -64,10 +64,12 @@ jest.mock('../../../../common/lib/kibana', () => { describe('Timeline', () => { let props = {} as QueryTabContentComponentProps; - const sort: Sort = { - columnId: '@timestamp', - sortDirection: Direction.desc, - }; + const sort: Sort[] = [ + { + columnId: '@timestamp', + sortDirection: Direction.desc, + }, + ]; const startDate = '2018-03-23T18:49:23.132Z'; const endDate = '2018-03-24T03:33:52.253Z'; 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 8186ee8b77628..69a7299b9833d 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 @@ -214,11 +214,12 @@ export const QueryTabContentComponent: React.FC = ({ }, [columns]); const timelineQuerySortField = useMemo( - () => ({ - field: sort.columnId, - direction: sort.sortDirection as Direction, - }), - [sort.columnId, sort.sortDirection] + () => + sort.map(({ columnId, sortDirection }) => ({ + field: columnId, + direction: sortDirection as Direction, + })), + [sort] ); const { initializeTimeline, setIsTimelineLoading } = useManageTimeline(); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/styles.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/styles.tsx index 9f9940203960c..ef7c821bd652d 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/styles.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/styles.tsx @@ -11,6 +11,19 @@ import styled, { createGlobalStyle } from 'styled-components'; import { TimelineEventsType } from '../../../../common/types/timeline'; import { IS_TIMELINE_FIELD_DRAGGING_CLASS_NAME } from '../../../common/components/drag_and_drop/helpers'; +/** + * TIMELINE BODY + */ +export const SELECTOR_TIMELINE_GLOBAL_CONTAINER = 'securitySolutionTimeline__container'; +export const TimelineContainer = styled.div.attrs(({ className = '' }) => ({ + className: `${SELECTOR_TIMELINE_GLOBAL_CONTAINER} ${className}`, +}))` + height: 100%; + display: flex; + flex-direction: column; + position: relative; +`; + /** * TIMELINE BODY */ @@ -99,6 +112,9 @@ export const EventsThGroupActions = styled.div.attrs(({ className = '' }) => ({ min-width: 0; padding-left: ${({ isEventViewer }) => !isEventViewer ? '4px;' : '0;'}; // match timeline event border + button { + color: ${({ theme }) => theme.eui.euiColorPrimary}; + } `; export const EventsThGroupData = styled.div.attrs(({ className = '' }) => ({ diff --git a/x-pack/plugins/security_solution/public/timelines/containers/api.test.ts b/x-pack/plugins/security_solution/public/timelines/containers/api.test.ts index a439699d27f6d..7e2a6fa1c15cf 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/api.test.ts +++ b/x-pack/plugins/security_solution/public/timelines/containers/api.test.ts @@ -73,10 +73,12 @@ const timelineData = { end: 1591084965409, }, savedQueryId: null, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, + sort: [ + { + columnId: '@timestamp', + sortDirection: 'desc', + }, + ], status: TimelineStatus.active, }; const mockPatchTimelineResponse = { diff --git a/x-pack/plugins/security_solution/public/timelines/containers/details/index.tsx b/x-pack/plugins/security_solution/public/timelines/containers/details/index.tsx index 8f1644550d147..ebc86b3c5cf5e 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/details/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/containers/details/index.tsx @@ -85,6 +85,9 @@ export const useTimelineEventsDetails = ({ } }, error: () => { + if (!didCancel) { + setLoading(false); + } notifications.toasts.addDanger('Failed to run search'); }, }); diff --git a/x-pack/plugins/security_solution/public/timelines/containers/index.tsx b/x-pack/plugins/security_solution/public/timelines/containers/index.tsx index a168e814208e7..3baab2024558f 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/containers/index.tsx @@ -56,7 +56,7 @@ export interface UseTimelineEventsProps { fields: string[]; indexNames: string[]; limit: number; - sort: SortField; + sort: SortField[]; startDate: string; timerangeKind?: 'absolute' | 'relative'; } @@ -65,10 +65,12 @@ const getTimelineEvents = (timelineEdges: TimelineEdges[]): TimelineItem[] => timelineEdges.map((e: TimelineEdges) => e.node); const ID = 'timelineEventsQuery'; -export const initSortDefault = { - field: '@timestamp', - direction: Direction.asc, -}; +export const initSortDefault = [ + { + field: '@timestamp', + direction: Direction.asc, + }, +]; function usePreviousRequest(value: TimelineEventsAllRequestOptions | null) { const ref = useRef(value); diff --git a/x-pack/plugins/security_solution/public/timelines/containers/local_storage/index.tsx b/x-pack/plugins/security_solution/public/timelines/containers/local_storage/index.tsx index 1a09868da7771..604767bcde26c 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/local_storage/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/containers/local_storage/index.tsx @@ -32,7 +32,12 @@ export const getTimelinesInStorageByIds = (storage: Storage, timelineIds: Timeli return { ...acc, - [timelineId]: timelineModel, + [timelineId]: { + ...timelineModel, + ...(timelineModel.sort != null && !Array.isArray(timelineModel.sort) + ? { sort: [timelineModel.sort] } + : {}), + }, }; }, {} as { [K in TimelineIdLiteral]: TimelineModel }); }; diff --git a/x-pack/plugins/security_solution/public/timelines/containers/one/index.gql_query.ts b/x-pack/plugins/security_solution/public/timelines/containers/one/index.gql_query.ts index fa0ecb349f9c8..9e34d3470d296 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/one/index.gql_query.ts +++ b/x-pack/plugins/security_solution/public/timelines/containers/one/index.gql_query.ts @@ -138,10 +138,7 @@ export const oneTimelineQuery = gql` templateTimelineId templateTimelineVersion savedQueryId - sort { - columnId - sortDirection - } + sort created createdBy updated diff --git a/x-pack/plugins/security_solution/public/timelines/containers/persist.gql_query.ts b/x-pack/plugins/security_solution/public/timelines/containers/persist.gql_query.ts index 12d3e6bfd7172..e255ac5bdda5b 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/persist.gql_query.ts +++ b/x-pack/plugins/security_solution/public/timelines/containers/persist.gql_query.ts @@ -102,10 +102,7 @@ export const persistTimelineMutation = gql` end } savedQueryId - sort { - columnId - sortDirection - } + sort created createdBy updated diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts index b8dfa698a9307..479c289cdd21d 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts @@ -72,7 +72,7 @@ export interface TimelineInput { filterQuery: SerializedFilterQuery | null; }; show?: boolean; - sort?: Sort; + sort?: Sort[]; showCheckboxes?: boolean; timelineType?: TimelineTypeLiteral; templateTimelineId?: string | null; @@ -216,7 +216,7 @@ export const updateRange = actionCreator<{ id: string; start: string; end: strin 'UPDATE_RANGE' ); -export const updateSort = actionCreator<{ id: string; sort: Sort }>('UPDATE_SORT'); +export const updateSort = actionCreator<{ id: string; sort: Sort[] }>('UPDATE_SORT'); export const updateAutoSaveMsg = actionCreator<{ timelineId: string | null; diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/defaults.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/defaults.ts index 84551de9ec628..211bba3cc47d2 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/defaults.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/defaults.ts @@ -52,10 +52,12 @@ export const timelineDefaults: SubsetTimelineModel & Pick { selectedEventIds: {}, show: true, showCheckboxes: false, - sort: { columnId: '@timestamp', sortDirection: Direction.desc }, + sort: [{ columnId: '@timestamp', sortDirection: Direction.desc }], status: TimelineStatus.active, version: 'WzM4LDFd', id: '11169110-fc22-11e9-8ca9-072f15ce2685', @@ -286,10 +286,12 @@ describe('Epic Timeline', () => { }, }, savedQueryId: 'my endgame timeline query', - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, + sort: [ + { + columnId: '@timestamp', + sortDirection: 'desc', + }, + ], templateTimelineId: null, templateTimelineVersion: null, timelineType: TimelineType.default, 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 a2bccaddb309e..5fcbcf434d3ee 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 @@ -58,10 +58,12 @@ describe('epicLocalStorage', () => { ); let props = {} as QueryTabContentComponentProps; - const sort: Sort = { - columnId: '@timestamp', - sortDirection: Direction.desc, - }; + const sort: Sort[] = [ + { + columnId: '@timestamp', + sortDirection: Direction.desc, + }, + ]; const startDate = '2018-03-23T18:49:23.132Z'; const endDate = '2018-03-24T03:33:52.253Z'; @@ -159,10 +161,12 @@ describe('epicLocalStorage', () => { store.dispatch( updateSort({ id: 'test', - sort: { - columnId: 'event.severity', - sortDirection: Direction.desc, - }, + sort: [ + { + columnId: 'event.severity', + sortDirection: Direction.desc, + }, + ], }) ); await waitFor(() => expect(addTimelineInStorageMock).toHaveBeenCalled()); diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts index 1122b7a94e0e0..f9f4622c9d63c 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts @@ -179,7 +179,7 @@ interface AddNewTimelineParams { filterQuery: SerializedFilterQuery | null; }; show?: boolean; - sort?: Sort; + sort?: Sort[]; showCheckboxes?: boolean; timelineById: TimelineById; timelineType: TimelineTypeLiteral; @@ -762,7 +762,7 @@ export const updateTimelineRange = ({ interface UpdateTimelineSortParams { id: string; - sort: Sort; + sort: Sort[]; timelineById: TimelineById; } diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/model.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/model.ts index e4d1a6b512689..9c71fabfffac5 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/model.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/model.ts @@ -124,7 +124,7 @@ export interface TimelineModel { /** When true, shows checkboxes enabling selection. Selected events store in selectedEventIds **/ showCheckboxes: boolean; /** Specifies which column the timeline is sorted on, and the direction (ascending / descending) */ - sort: Sort; + sort: Sort[]; /** status: active | draft */ status: TimelineStatus; /** updated saved object timestamp */ diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts index 2ca34742affef..59d5800271b8a 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts @@ -101,10 +101,12 @@ const basicTimeline: TimelineModel = { selectedEventIds: {}, show: true, showCheckboxes: false, - sort: { - columnId: '@timestamp', - sortDirection: Direction.desc, - }, + sort: [ + { + columnId: '@timestamp', + sortDirection: Direction.desc, + }, + ], status: TimelineStatus.active, templateTimelineId: null, templateTimelineVersion: null, @@ -953,10 +955,12 @@ describe('Timeline', () => { beforeAll(() => { update = updateTimelineSort({ id: 'foo', - sort: { - columnId: 'some column', - sortDirection: Direction.desc, - }, + sort: [ + { + columnId: 'some column', + sortDirection: Direction.desc, + }, + ], timelineById: timelineByIdMock, }); }); @@ -964,8 +968,8 @@ describe('Timeline', () => { expect(update).not.toBe(timelineByIdMock); }); - test('should update the timeline range', () => { - expect(update.foo.sort).toEqual({ columnId: 'some column', sortDirection: Direction.desc }); + test('should update the sort attribute', () => { + expect(update.foo.sort).toEqual([{ columnId: 'some column', sortDirection: Direction.desc }]); }); }); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/entity.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/entity.ts index c731692e6fb89..6d4168d744fca 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/entity.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/entity.ts @@ -19,7 +19,7 @@ interface SupportedSchema { /** * A constraint to search for in the documented returned by Elasticsearch */ - constraint: { field: string; value: string }; + constraints: Array<{ field: string; value: string }>; /** * Schema to return to the frontend so that it can be passed in to call to the /tree API @@ -34,10 +34,12 @@ interface SupportedSchema { const supportedSchemas: SupportedSchema[] = [ { name: 'endpoint', - constraint: { - field: 'agent.type', - value: 'endpoint', - }, + constraints: [ + { + field: 'agent.type', + value: 'endpoint', + }, + ], schema: { id: 'process.entity_id', parent: 'process.parent.entity_id', @@ -47,10 +49,16 @@ const supportedSchemas: SupportedSchema[] = [ }, { name: 'winlogbeat', - constraint: { - field: 'agent.type', - value: 'winlogbeat', - }, + constraints: [ + { + field: 'agent.type', + value: 'winlogbeat', + }, + { + field: 'event.module', + value: 'sysmon', + }, + ], schema: { id: 'process.entity_id', parent: 'process.parent.entity_id', @@ -104,14 +112,17 @@ export function handleEntities(): RequestHandler { - const kqlQuery: JsonObject[] = []; - if (kql) { - kqlQuery.push(esKuery.toElasticsearchQuery(esKuery.fromKueryExpression(kql))); - } + async search( + client: IScopedClusterClient, + filter: string | undefined + ): Promise { + const parsedFilters = EventsQuery.buildFilters(filter); const response: ApiResponse< SearchResponse - > = await client.asCurrentUser.search(this.buildSearch(kqlQuery)); + > = await client.asCurrentUser.search(this.buildSearch(parsedFilters)); return response.body.hits.hits.map((hit) => hit._source); } } diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/descendants.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/descendants.ts index 3baf3a8667529..63cd3b5d694af 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/descendants.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/descendants.ts @@ -8,12 +8,12 @@ import { ApiResponse } from '@elastic/elasticsearch'; import { IScopedClusterClient } from 'src/core/server'; import { FieldsObject, ResolverSchema } from '../../../../../../common/endpoint/types'; import { JsonObject, JsonValue } from '../../../../../../../../../src/plugins/kibana_utils/common'; -import { NodeID, Timerange, docValueFields } from '../utils/index'; +import { NodeID, TimeRange, docValueFields } from '../utils/index'; interface DescendantsParams { schema: ResolverSchema; indexPatterns: string | string[]; - timerange: Timerange; + timeRange: TimeRange; } /** @@ -22,13 +22,13 @@ interface DescendantsParams { export class DescendantsQuery { private readonly schema: ResolverSchema; private readonly indexPatterns: string | string[]; - private readonly timerange: Timerange; + private readonly timeRange: TimeRange; private readonly docValueFields: JsonValue[]; - constructor({ schema, indexPatterns, timerange }: DescendantsParams) { + constructor({ schema, indexPatterns, timeRange }: DescendantsParams) { this.docValueFields = docValueFields(schema); this.schema = schema; this.indexPatterns = indexPatterns; - this.timerange = timerange; + this.timeRange = timeRange; } private query(nodes: NodeID[], size: number): JsonObject { @@ -46,8 +46,8 @@ export class DescendantsQuery { { range: { '@timestamp': { - gte: this.timerange.from, - lte: this.timerange.to, + gte: this.timeRange.from, + lte: this.timeRange.to, format: 'strict_date_optional_time', }, }, @@ -126,8 +126,8 @@ export class DescendantsQuery { { range: { '@timestamp': { - gte: this.timerange.from, - lte: this.timerange.to, + gte: this.timeRange.from, + lte: this.timeRange.to, format: 'strict_date_optional_time', }, }, diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/lifecycle.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/lifecycle.ts index 5253806be66ba..150b07c63ce2f 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/lifecycle.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/lifecycle.ts @@ -8,12 +8,12 @@ import { ApiResponse } from '@elastic/elasticsearch'; import { IScopedClusterClient } from 'src/core/server'; import { FieldsObject, ResolverSchema } from '../../../../../../common/endpoint/types'; import { JsonObject, JsonValue } from '../../../../../../../../../src/plugins/kibana_utils/common'; -import { NodeID, Timerange, docValueFields } from '../utils/index'; +import { NodeID, TimeRange, docValueFields } from '../utils/index'; interface LifecycleParams { schema: ResolverSchema; indexPatterns: string | string[]; - timerange: Timerange; + timeRange: TimeRange; } /** @@ -22,13 +22,13 @@ interface LifecycleParams { export class LifecycleQuery { private readonly schema: ResolverSchema; private readonly indexPatterns: string | string[]; - private readonly timerange: Timerange; + private readonly timeRange: TimeRange; private readonly docValueFields: JsonValue[]; - constructor({ schema, indexPatterns, timerange }: LifecycleParams) { + constructor({ schema, indexPatterns, timeRange }: LifecycleParams) { this.docValueFields = docValueFields(schema); this.schema = schema; this.indexPatterns = indexPatterns; - this.timerange = timerange; + this.timeRange = timeRange; } private query(nodes: NodeID[]): JsonObject { @@ -46,8 +46,8 @@ export class LifecycleQuery { { range: { '@timestamp': { - gte: this.timerange.from, - lte: this.timerange.to, + gte: this.timeRange.from, + lte: this.timeRange.to, format: 'strict_date_optional_time', }, }, diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/stats.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/stats.ts index 117cc3647dd0e..22d2c600feb01 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/stats.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/stats.ts @@ -8,7 +8,7 @@ import { ApiResponse } from '@elastic/elasticsearch'; import { IScopedClusterClient } from 'src/core/server'; import { JsonObject } from '../../../../../../../../../src/plugins/kibana_utils/common'; import { EventStats, ResolverSchema } from '../../../../../../common/endpoint/types'; -import { NodeID, Timerange } from '../utils/index'; +import { NodeID, TimeRange } from '../utils/index'; interface AggBucket { key: string; @@ -28,7 +28,7 @@ interface CategoriesAgg extends AggBucket { interface StatsParams { schema: ResolverSchema; indexPatterns: string | string[]; - timerange: Timerange; + timeRange: TimeRange; } /** @@ -37,11 +37,11 @@ interface StatsParams { export class StatsQuery { private readonly schema: ResolverSchema; private readonly indexPatterns: string | string[]; - private readonly timerange: Timerange; - constructor({ schema, indexPatterns, timerange }: StatsParams) { + private readonly timeRange: TimeRange; + constructor({ schema, indexPatterns, timeRange }: StatsParams) { this.schema = schema; this.indexPatterns = indexPatterns; - this.timerange = timerange; + this.timeRange = timeRange; } private query(nodes: NodeID[]): JsonObject { @@ -53,8 +53,8 @@ export class StatsQuery { { range: { '@timestamp': { - gte: this.timerange.from, - lte: this.timerange.to, + gte: this.timeRange.from, + lte: this.timeRange.to, format: 'strict_date_optional_time', }, }, diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/utils/fetch.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/utils/fetch.test.ts index d5e0af9dea239..796ed60ddbbc3 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/utils/fetch.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/utils/fetch.test.ts @@ -80,7 +80,7 @@ describe('fetcher test', () => { descendantLevels: 1, descendants: 5, ancestors: 0, - timerange: { + timeRange: { from: '', to: '', }, @@ -100,7 +100,7 @@ describe('fetcher test', () => { descendantLevels: 0, descendants: 0, ancestors: 0, - timerange: { + timeRange: { from: '', to: '', }, @@ -163,7 +163,7 @@ describe('fetcher test', () => { descendantLevels: 2, descendants: 5, ancestors: 0, - timerange: { + timeRange: { from: '', to: '', }, @@ -188,7 +188,7 @@ describe('fetcher test', () => { descendantLevels: 0, descendants: 0, ancestors: 5, - timerange: { + timeRange: { from: '', to: '', }, @@ -211,7 +211,7 @@ describe('fetcher test', () => { descendantLevels: 0, descendants: 0, ancestors: 0, - timerange: { + timeRange: { from: '', to: '', }, @@ -249,7 +249,7 @@ describe('fetcher test', () => { descendantLevels: 0, descendants: 0, ancestors: 2, - timerange: { + timeRange: { from: '', to: '', }, @@ -292,7 +292,7 @@ describe('fetcher test', () => { descendantLevels: 0, descendants: 0, ancestors: 2, - timerange: { + timeRange: { from: '', to: '', }, @@ -342,7 +342,7 @@ describe('fetcher test', () => { descendantLevels: 0, descendants: 0, ancestors: 3, - timerange: { + timeRange: { from: '', to: '', }, diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/utils/fetch.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/utils/fetch.ts index 356357082d6ee..2ff231892a593 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/utils/fetch.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/utils/fetch.ts @@ -27,7 +27,7 @@ export interface TreeOptions { descendantLevels: number; descendants: number; ancestors: number; - timerange: { + timeRange: { from: string; to: string; }; @@ -76,7 +76,7 @@ export class Fetcher { const query = new StatsQuery({ indexPatterns: options.indexPatterns, schema: options.schema, - timerange: options.timerange, + timeRange: options.timeRange, }); const eventStats = await query.search(this.client, statsIDs); @@ -136,7 +136,7 @@ export class Fetcher { const query = new LifecycleQuery({ schema: options.schema, indexPatterns: options.indexPatterns, - timerange: options.timerange, + timeRange: options.timeRange, }); let nodes = options.nodes; @@ -182,7 +182,7 @@ export class Fetcher { const query = new DescendantsQuery({ schema: options.schema, indexPatterns: options.indexPatterns, - timerange: options.timerange, + timeRange: options.timeRange, }); let nodes: NodeID[] = options.nodes; diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/utils/index.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/utils/index.ts index be08b4390a69c..c00e90a386fb6 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/utils/index.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/utils/index.ts @@ -9,7 +9,7 @@ import { ResolverSchema } from '../../../../../../common/endpoint/types'; /** * Represents a time range filter */ -export interface Timerange { +export interface TimeRange { from: string; to: string; } diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/utils/ancestry_query_handler.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/utils/ancestry_query_handler.ts index 5bc911fb075b5..00aab683bf010 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/utils/ancestry_query_handler.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/utils/ancestry_query_handler.ts @@ -49,18 +49,18 @@ export class AncestryQueryHandler implements QueryHandler private toMapOfNodes(results: SafeResolverEvent[]) { return results.reduce( (nodes: Map, event: SafeResolverEvent) => { - const nodeId = entityIDSafeVersion(event); - if (!nodeId) { + const nodeID = entityIDSafeVersion(event); + if (!nodeID) { return nodes; } - let node = nodes.get(nodeId); + let node = nodes.get(nodeID); if (!node) { - node = createLifecycle(nodeId, []); + node = createLifecycle(nodeID, []); } node.lifecycle.push(event); - return nodes.set(nodeId, node); + return nodes.set(nodeID, node); }, new Map() ); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/mapping.ts b/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/mapping.ts index 1121e27e6e7bc..7476d1b59bf54 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/mapping.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/mapping.ts @@ -140,9 +140,7 @@ export const createEntryNested = (field: string, entries: NestedEntriesArray): E return { field, entries, type: 'nested' }; }; -export const conditionEntriesToEntries = ( - conditionEntries: Array> -): EntriesArray => { +export const conditionEntriesToEntries = (conditionEntries: ConditionEntry[]): EntriesArray => { return conditionEntries.map((conditionEntry) => { if (conditionEntry.field === ConditionEntryField.HASH) { return createEntryMatch( diff --git a/x-pack/plugins/security_solution/server/graphql/timeline/schema.gql.ts b/x-pack/plugins/security_solution/server/graphql/timeline/schema.gql.ts index 2358e78b044ed..ca6c57f025faf 100644 --- a/x-pack/plugins/security_solution/server/graphql/timeline/schema.gql.ts +++ b/x-pack/plugins/security_solution/server/graphql/timeline/schema.gql.ts @@ -174,7 +174,7 @@ export const timelineSchema = gql` timelineType: TimelineType dateRange: DateRangePickerInput savedQueryId: String - sort: SortTimelineInput + sort: [SortTimelineInput!] status: TimelineStatus } @@ -238,10 +238,6 @@ export const timelineSchema = gql` ${favoriteTimeline} } - type SortTimelineResult { - ${sortTimeline} - } - type FilterMetaTimelineResult { ${filtersMetaTimeline} } @@ -277,7 +273,7 @@ export const timelineSchema = gql` pinnedEventsSaveObject: [PinnedEvent!] savedQueryId: String savedObjectId: String! - sort: SortTimelineResult + sort: ToAny status: TimelineStatus title: String templateTimelineId: String diff --git a/x-pack/plugins/security_solution/server/graphql/types.ts b/x-pack/plugins/security_solution/server/graphql/types.ts index bda0fed494a6f..3ea964c0ee01f 100644 --- a/x-pack/plugins/security_solution/server/graphql/types.ts +++ b/x-pack/plugins/security_solution/server/graphql/types.ts @@ -105,7 +105,7 @@ export interface TimelineInput { savedQueryId?: Maybe; - sort?: Maybe; + sort?: Maybe; status?: Maybe; } @@ -634,7 +634,7 @@ export interface TimelineResult { savedObjectId: string; - sort?: Maybe; + sort?: Maybe; status?: Maybe; @@ -777,12 +777,6 @@ export interface KueryFilterQueryResult { expression?: Maybe; } -export interface SortTimelineResult { - columnId?: Maybe; - - sortDirection?: Maybe; -} - export interface ResponseTimelines { timeline: (Maybe)[]; @@ -2336,7 +2330,6 @@ export namespace AgentFieldsResolvers { > = Resolver; } - export namespace CloudFieldsResolvers { export interface Resolvers { instance?: InstanceResolver, TypeParent, TContext>; @@ -2665,7 +2658,7 @@ export namespace TimelineResultResolvers { savedObjectId?: SavedObjectIdResolver; - sort?: SortResolver, TypeParent, TContext>; + sort?: SortResolver, TypeParent, TContext>; status?: StatusResolver, TypeParent, TContext>; @@ -2785,7 +2778,7 @@ export namespace TimelineResultResolvers { TContext = SiemContext > = Resolver; export type SortResolver< - R = Maybe, + R = Maybe, Parent = TimelineResult, TContext = SiemContext > = Resolver; @@ -3245,25 +3238,6 @@ export namespace KueryFilterQueryResultResolvers { > = Resolver; } -export namespace SortTimelineResultResolvers { - export interface Resolvers { - columnId?: ColumnIdResolver, TypeParent, TContext>; - - sortDirection?: SortDirectionResolver, TypeParent, TContext>; - } - - export type ColumnIdResolver< - R = Maybe, - Parent = SortTimelineResult, - TContext = SiemContext - > = Resolver; - export type SortDirectionResolver< - R = Maybe, - Parent = SortTimelineResult, - TContext = SiemContext - > = Resolver; -} - export namespace ResponseTimelinesResolvers { export interface Resolvers { timeline?: TimelineResolver<(Maybe)[], TypeParent, TContext>; @@ -6091,7 +6065,6 @@ export type IResolvers = { SerializedFilterQueryResult?: SerializedFilterQueryResultResolvers.Resolvers; SerializedKueryQueryResult?: SerializedKueryQueryResultResolvers.Resolvers; KueryFilterQueryResult?: KueryFilterQueryResultResolvers.Resolvers; - SortTimelineResult?: SortTimelineResultResolvers.Resolvers; ResponseTimelines?: ResponseTimelinesResolvers.Resolvers; Mutation?: MutationResolvers.Resolvers; ResponseNote?: ResponseNoteResolvers.Resolvers; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_responses.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_responses.ts index 73e4845924acf..38ac6372fdb9c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_responses.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_responses.ts @@ -129,10 +129,11 @@ export const getDeleteAsPostBulkRequest = () => body: [{ rule_id: 'rule-1' }], }); -export const getPrivilegeRequest = () => +export const getPrivilegeRequest = (options: { auth?: { isAuthenticated: boolean } } = {}) => requestMock.create({ method: 'get', path: DETECTION_ENGINE_PRIVILEGES_URL, + ...options, }); export const addPrepackagedRulesRequest = () => diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.test.ts index cb4ec99748e47..945be0c584134 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.test.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { securityMock } from '../../../../../../security/server/mocks'; import { readPrivilegesRoute } from './read_privileges_route'; import { serverMock, requestContextMock } from '../__mocks__'; import { getPrivilegeRequest, getMockPrivilegesResult } from '../__mocks__/request_responses'; @@ -12,26 +11,29 @@ import { getPrivilegeRequest, getMockPrivilegesResult } from '../__mocks__/reque describe('read_privileges route', () => { let server: ReturnType; let { clients, context } = requestContextMock.createTools(); - let mockSecurity: ReturnType; beforeEach(() => { server = serverMock.create(); ({ clients, context } = requestContextMock.createTools()); - mockSecurity = securityMock.createSetup(); - mockSecurity.authc.isAuthenticated.mockReturnValue(false); clients.clusterClient.callAsCurrentUser.mockResolvedValue(getMockPrivilegesResult()); - readPrivilegesRoute(server.router, mockSecurity, false); + readPrivilegesRoute(server.router, false); }); describe('normal status codes', () => { test('returns 200 when doing a normal request', async () => { - const response = await server.inject(getPrivilegeRequest(), context); + const response = await server.inject( + getPrivilegeRequest({ auth: { isAuthenticated: false } }), + context + ); expect(response.status).toEqual(200); }); test('returns the payload when doing a normal request', async () => { - const response = await server.inject(getPrivilegeRequest(), context); + const response = await server.inject( + getPrivilegeRequest({ auth: { isAuthenticated: false } }), + context + ); const expectedBody = { ...getMockPrivilegesResult(), is_authenticated: false, @@ -42,14 +44,16 @@ describe('read_privileges route', () => { }); test('is authenticated when security says so', async () => { - mockSecurity.authc.isAuthenticated.mockReturnValue(true); const expectedBody = { ...getMockPrivilegesResult(), is_authenticated: true, has_encryption_key: true, }; - const response = await server.inject(getPrivilegeRequest(), context); + const response = await server.inject( + getPrivilegeRequest({ auth: { isAuthenticated: true } }), + context + ); expect(response.status).toEqual(200); expect(response.body).toEqual(expectedBody); }); @@ -58,38 +62,22 @@ describe('read_privileges route', () => { clients.clusterClient.callAsCurrentUser.mockImplementation(() => { throw new Error('Test error'); }); - const response = await server.inject(getPrivilegeRequest(), context); + const response = await server.inject( + getPrivilegeRequest({ auth: { isAuthenticated: false } }), + context + ); expect(response.status).toEqual(500); expect(response.body).toEqual({ message: 'Test error', status_code: 500 }); }); it('returns 404 if siem client is unavailable', async () => { const { securitySolution, ...contextWithoutSecuritySolution } = context; - const response = await server.inject(getPrivilegeRequest(), contextWithoutSecuritySolution); + const response = await server.inject( + getPrivilegeRequest({ auth: { isAuthenticated: false } }), + contextWithoutSecuritySolution + ); expect(response.status).toEqual(404); expect(response.body).toEqual({ message: 'Not Found', status_code: 404 }); }); }); - - describe('when security plugin is disabled', () => { - beforeEach(() => { - server = serverMock.create(); - ({ clients, context } = requestContextMock.createTools()); - - clients.clusterClient.callAsCurrentUser.mockResolvedValue(getMockPrivilegesResult()); - readPrivilegesRoute(server.router, undefined, false); - }); - - it('returns unauthenticated', async () => { - const expectedBody = { - ...getMockPrivilegesResult(), - is_authenticated: false, - has_encryption_key: true, - }; - - const response = await server.inject(getPrivilegeRequest(), context); - expect(response.status).toEqual(200); - expect(response.body).toEqual(expectedBody); - }); - }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.ts index 715a5be7462d1..174aa4911ba1e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.ts @@ -8,15 +8,10 @@ import { merge } from 'lodash/fp'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_PRIVILEGES_URL } from '../../../../../common/constants'; -import { SetupPlugins } from '../../../../plugin'; import { buildSiemResponse, transformError } from '../utils'; import { readPrivileges } from '../../privileges/read_privileges'; -export const readPrivilegesRoute = ( - router: IRouter, - security: SetupPlugins['security'], - usingEphemeralEncryptionKey: boolean -) => { +export const readPrivilegesRoute = (router: IRouter, usingEphemeralEncryptionKey: boolean) => { router.get( { path: DETECTION_ENGINE_PRIVILEGES_URL, @@ -39,7 +34,7 @@ export const readPrivilegesRoute = ( const index = siemClient.getSignalsIndex(); const clusterPrivileges = await readPrivileges(clusterClient.callAsCurrentUser, index); const privileges = merge(clusterPrivileges, { - is_authenticated: security?.authc.isAuthenticated(request) ?? false, + is_authenticated: request.auth.isAuthenticated ?? false, has_encryption_key: !usingEphemeralEncryptionKey, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts index a68e534a2d4ea..b2074ad20b674 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts @@ -28,7 +28,7 @@ export const findRulesRoute = (router: IRouter) => { ), }, options: { - tags: ['access'], + tags: ['access:securitySolution'], }, }, async (context, request, response) => { diff --git a/x-pack/plugins/security_solution/server/lib/machine_learning/index.ts b/x-pack/plugins/security_solution/server/lib/machine_learning/index.ts index ec801f6c49ae7..c8bf6790ae9b2 100644 --- a/x-pack/plugins/security_solution/server/lib/machine_learning/index.ts +++ b/x-pack/plugins/security_solution/server/lib/machine_learning/index.ts @@ -6,8 +6,8 @@ import { RequestParams } from '@elastic/elasticsearch'; +import { buildExceptionFilter } from '../../../common/detection_engine/build_exceptions_filter'; import { ExceptionListItemSchema } from '../../../../lists/common'; -import { buildExceptionFilter } from '../../../common/detection_engine/get_query_filter'; import { AnomalyRecordDoc as Anomaly } from '../../../../ml/server'; import { SearchResponse } from '../types'; @@ -54,12 +54,6 @@ export const getAnomalies = async ( ], must_not: buildExceptionFilter({ lists: params.exceptionItems, - config: { - allowLeadingWildcards: true, - queryStringOptions: { analyze_wildcard: true }, - ignoreFilterIfFieldNotInIndex: false, - dateFormatTZ: 'Zulu', - }, excludeExceptions: true, chunkSize: 1024, })?.query, diff --git a/x-pack/plugins/security_solution/server/lib/timeline/convert_saved_object_to_savedtimeline.ts b/x-pack/plugins/security_solution/server/lib/timeline/convert_saved_object_to_savedtimeline.ts index f888675b60410..271e53d4e6c9b 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/convert_saved_object_to_savedtimeline.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/convert_saved_object_to_savedtimeline.ts @@ -60,6 +60,12 @@ export const convertSavedObjectToSavedTimeline = (savedObject: unknown): Timelin savedTimeline.attributes.timelineType, savedTimeline.attributes.status ), + sort: + savedTimeline.attributes.sort != null + ? Array.isArray(savedTimeline.attributes.sort) + ? savedTimeline.attributes.sort + : [savedTimeline.attributes.sort] + : [], }; return { savedObjectId: savedTimeline.id, diff --git a/x-pack/plugins/security_solution/server/routes/index.ts b/x-pack/plugins/security_solution/server/routes/index.ts index 000bd875930f9..3467d0bb66860 100644 --- a/x-pack/plugins/security_solution/server/routes/index.ts +++ b/x-pack/plugins/security_solution/server/routes/index.ts @@ -93,5 +93,5 @@ export const initRoutes = ( readTagsRoute(router); // Privileges API to get the generic user privileges - readPrivilegesRoute(router, security, usingEphemeralEncryptionKey); + readPrivilegesRoute(router, usingEphemeralEncryptionKey); }; diff --git a/x-pack/plugins/security_solution/server/search_strategy/helpers/to_array.ts b/x-pack/plugins/security_solution/server/search_strategy/helpers/to_array.ts index 1aba6660677cd..9fd371c6f1cca 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/helpers/to_array.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/helpers/to_array.ts @@ -7,5 +7,37 @@ export const toArray = (value: T | T[] | null): T[] => Array.isArray(value) ? value : value == null ? [] : [value]; -export const toStringArray = (value: T | T[] | null): T[] | string[] => - Array.isArray(value) ? value : value == null ? [] : [`${value}`]; +export const toStringArray = (value: T | T[] | null): string[] => { + if (Array.isArray(value)) { + return value.reduce((acc, v) => { + if (v != null) { + switch (typeof v) { + case 'number': + case 'boolean': + return [...acc, v.toString()]; + case 'object': + try { + return [...acc, JSON.stringify(value)]; + } catch { + return [...acc, 'Invalid Object']; + } + case 'string': + return [...acc, v]; + default: + return [...acc, `${v}`]; + } + } + return acc; + }, []); + } else if (value == null) { + return []; + } else if (!Array.isArray(value) && typeof value === 'object') { + try { + return [JSON.stringify(value)]; + } catch { + return ['Invalid Object']; + } + } else { + return [`${value}`]; + } +}; diff --git a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/helpers.test.ts b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/helpers.test.ts new file mode 100644 index 0000000000000..b62ddc00f2e30 --- /dev/null +++ b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/helpers.test.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EventHit } from '../../../../../../common/search_strategy'; +import { TIMELINE_EVENTS_FIELDS } from './constants'; +import { formatTimelineData } from './helpers'; + +describe('#formatTimelineData', () => { + it('happy path', () => { + const response: EventHit = { + _index: 'auditbeat-7.8.0-2020.11.05-000003', + _id: 'tkCt1nUBaEgqnrVSZ8R_', + _score: 0, + _type: '', + fields: { + 'event.category': ['process'], + 'process.ppid': [3977], + 'user.name': ['jenkins'], + 'process.args': ['go', 'vet', './...'], + message: ['Process go (PID: 4313) by user jenkins STARTED'], + 'process.pid': [4313], + 'process.working_directory': [ + '/var/lib/jenkins/workspace/Beats_beats_PR-22624/src/github.com/elastic/beats/libbeat', + ], + 'process.entity_id': ['Z59cIkAAIw8ZoK0H'], + 'host.ip': ['10.224.1.237', 'fe80::4001:aff:fee0:1ed', '172.17.0.1'], + 'process.name': ['go'], + 'event.action': ['process_started'], + 'agent.type': ['auditbeat'], + '@timestamp': ['2020-11-17T14:48:08.922Z'], + 'event.module': ['system'], + 'event.type': ['start'], + 'host.name': ['beats-ci-immutable-ubuntu-1804-1605624279743236239'], + 'process.hash.sha1': ['1eac22336a41e0660fb302add9d97daa2bcc7040'], + 'host.os.family': ['debian'], + 'event.kind': ['event'], + 'host.id': ['e59991e835905c65ed3e455b33e13bd6'], + 'event.dataset': ['process'], + 'process.executable': [ + '/var/lib/jenkins/workspace/Beats_beats_PR-22624/.gvm/versions/go1.14.7.linux.amd64/bin/go', + ], + }, + _source: {}, + sort: ['1605624488922', 'beats-ci-immutable-ubuntu-1804-1605624279743236239'], + aggregations: {}, + }; + + expect( + formatTimelineData( + ['@timestamp', 'host.name', 'destination.ip', 'source.ip'], + TIMELINE_EVENTS_FIELDS, + response + ) + ).toEqual({ + cursor: { + tiebreaker: 'beats-ci-immutable-ubuntu-1804-1605624279743236239', + value: '1605624488922', + }, + node: { + _id: 'tkCt1nUBaEgqnrVSZ8R_', + _index: 'auditbeat-7.8.0-2020.11.05-000003', + data: [ + { + field: '@timestamp', + value: ['2020-11-17T14:48:08.922Z'], + }, + { + field: 'host.name', + value: ['beats-ci-immutable-ubuntu-1804-1605624279743236239'], + }, + ], + ecs: { + '@timestamp': ['2020-11-17T14:48:08.922Z'], + _id: 'tkCt1nUBaEgqnrVSZ8R_', + _index: 'auditbeat-7.8.0-2020.11.05-000003', + agent: { + type: ['auditbeat'], + }, + event: { + action: ['process_started'], + category: ['process'], + dataset: ['process'], + kind: ['event'], + module: ['system'], + type: ['start'], + }, + host: { + id: ['e59991e835905c65ed3e455b33e13bd6'], + ip: ['10.224.1.237', 'fe80::4001:aff:fee0:1ed', '172.17.0.1'], + name: ['beats-ci-immutable-ubuntu-1804-1605624279743236239'], + os: { + family: ['debian'], + }, + }, + message: ['Process go (PID: 4313) by user jenkins STARTED'], + process: { + args: ['go', 'vet', './...'], + entity_id: ['Z59cIkAAIw8ZoK0H'], + executable: [ + '/var/lib/jenkins/workspace/Beats_beats_PR-22624/.gvm/versions/go1.14.7.linux.amd64/bin/go', + ], + hash: { + sha1: ['1eac22336a41e0660fb302add9d97daa2bcc7040'], + }, + name: ['go'], + pid: ['4313'], + ppid: ['3977'], + working_directory: [ + '/var/lib/jenkins/workspace/Beats_beats_PR-22624/src/github.com/elastic/beats/libbeat', + ], + }, + timestamp: '2020-11-17T14:48:08.922Z', + user: { + name: ['jenkins'], + }, + }, + }, + }); + }); +}); diff --git a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/helpers.ts b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/helpers.ts index 8e2bfb5426610..a9aee2175b31d 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/helpers.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/helpers.ts @@ -7,6 +7,7 @@ import { get, has, merge, uniq } from 'lodash/fp'; import { EventHit, TimelineEdges } from '../../../../../../common/search_strategy'; import { toStringArray } from '../../../../helpers/to_array'; +import { formatGeoLocation, isGeoField } from '../details/helpers'; export const formatTimelineData = ( dataFields: readonly string[], @@ -18,7 +19,7 @@ export const formatTimelineData = ( flattenedFields.node._id = hit._id; flattenedFields.node._index = hit._index; flattenedFields.node.ecs._id = hit._id; - flattenedFields.node.ecs.timestamp = hit._source['@timestamp']; + flattenedFields.node.ecs.timestamp = (hit.fields['@timestamp'][0] ?? '') as string; flattenedFields.node.ecs._index = hit._index; if (hit.sort && hit.sort.length > 1) { flattenedFields.cursor.value = hit.sort[0]; @@ -40,13 +41,12 @@ const specialFields = ['_id', '_index', '_type', '_score']; const mergeTimelineFieldsWithHit = ( fieldName: string, flattenedFields: T, - hit: { _source: {} }, + hit: { fields: Record }, dataFields: readonly string[], ecsFields: readonly string[] ) => { if (fieldName != null || dataFields.includes(fieldName)) { - const esField = fieldName; - if (has(esField, hit._source) || specialFields.includes(esField)) { + if (has(fieldName, hit.fields) || specialFields.includes(fieldName)) { const objectWithProperty = { node: { ...get('node', flattenedFields), @@ -55,9 +55,11 @@ const mergeTimelineFieldsWithHit = ( ...get('node.data', flattenedFields), { field: fieldName, - value: specialFields.includes(esField) - ? toStringArray(get(esField, hit)) - : toStringArray(get(esField, hit._source)), + value: specialFields.includes(fieldName) + ? toStringArray(get(fieldName, hit)) + : isGeoField(fieldName) + ? formatGeoLocation(hit.fields[fieldName]) + : toStringArray(hit.fields[fieldName]), }, ] : get('node.data', flattenedFields), @@ -68,7 +70,7 @@ const mergeTimelineFieldsWithHit = ( ...fieldName.split('.').reduceRight( // @ts-expect-error (obj, next) => ({ [next]: obj }), - toStringArray(get(esField, hit._source)) + toStringArray(hit.fields[fieldName]) ), } : get('node.ecs', flattenedFields), diff --git a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/index.ts b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/index.ts index 19535fa3dc8a8..de58e7cf44d64 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/index.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/index.ts @@ -9,11 +9,12 @@ import { cloneDeep, uniq } from 'lodash/fp'; import { DEFAULT_MAX_TABLE_QUERY_SIZE } from '../../../../../../common/constants'; import { IEsSearchResponse } from '../../../../../../../../../src/plugins/data/common'; import { + EventHit, TimelineEventsQueries, TimelineEventsAllStrategyResponse, TimelineEventsAllRequestOptions, TimelineEdges, -} from '../../../../../../common/search_strategy/timeline'; +} from '../../../../../../common/search_strategy'; import { inspectStringifyObject } from '../../../../../utils/build_query'; import { SecuritySolutionTimelineFactory } from '../../types'; import { buildTimelineEventsAllQuery } from './query.events_all.dsl'; @@ -39,8 +40,7 @@ export const timelineEventsAll: SecuritySolutionTimelineFactory - // @ts-expect-error - formatTimelineData(options.fieldRequested, TIMELINE_EVENTS_FIELDS, hit) + formatTimelineData(options.fieldRequested, TIMELINE_EVENTS_FIELDS, hit as EventHit) ); const inspect = { dsl: [inspectStringifyObject(buildTimelineEventsAllQuery(queryOptions))], diff --git a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/query.events_all.dsl.ts b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/query.events_all.dsl.ts index a5a0c877ecdd3..034a2b3c6ea95 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/query.events_all.dsl.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/all/query.events_all.dsl.ts @@ -44,14 +44,11 @@ export const buildTimelineEventsAllQuery = ({ const filter = [...filterClause, ...getTimerangeFilter(timerange), { match_all: {} }]; - const getSortField = (sortField: SortField) => { - if (sortField.field) { - const field: string = sortField.field === 'timestamp' ? '@timestamp' : sortField.field; - - return [{ [field]: sortField.direction }]; - } - return []; - }; + const getSortField = (sortFields: SortField[]) => + sortFields.map((item) => { + const field: string = item.field === 'timestamp' ? '@timestamp' : item.field; + return { [field]: item.direction }; + }); const dslQuery = { allowNoIndices: true, @@ -68,7 +65,7 @@ export const buildTimelineEventsAllQuery = ({ size: querySize, track_total_hits: true, sort: getSortField(sort), - _source: fields, + fields, }, }; diff --git a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/helpers.test.ts b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/helpers.test.ts new file mode 100644 index 0000000000000..34610da7d7aa3 --- /dev/null +++ b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/helpers.test.ts @@ -0,0 +1,153 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EventHit } from '../../../../../../common/search_strategy'; +import { getDataFromHits } from './helpers'; + +describe('#getDataFromHits', () => { + it('happy path', () => { + const response: EventHit = { + _index: 'auditbeat-7.8.0-2020.11.05-000003', + _id: 'tkCt1nUBaEgqnrVSZ8R_', + _score: 0, + _type: '', + fields: { + 'event.category': ['process'], + 'process.ppid': [3977], + 'user.name': ['jenkins'], + 'process.args': ['go', 'vet', './...'], + message: ['Process go (PID: 4313) by user jenkins STARTED'], + 'process.pid': [4313], + 'process.working_directory': [ + '/var/lib/jenkins/workspace/Beats_beats_PR-22624/src/github.com/elastic/beats/libbeat', + ], + 'process.entity_id': ['Z59cIkAAIw8ZoK0H'], + 'host.ip': ['10.224.1.237', 'fe80::4001:aff:fee0:1ed', '172.17.0.1'], + 'process.name': ['go'], + 'event.action': ['process_started'], + 'agent.type': ['auditbeat'], + '@timestamp': ['2020-11-17T14:48:08.922Z'], + 'event.module': ['system'], + 'event.type': ['start'], + 'host.name': ['beats-ci-immutable-ubuntu-1804-1605624279743236239'], + 'process.hash.sha1': ['1eac22336a41e0660fb302add9d97daa2bcc7040'], + 'host.os.family': ['debian'], + 'event.kind': ['event'], + 'host.id': ['e59991e835905c65ed3e455b33e13bd6'], + 'event.dataset': ['process'], + 'process.executable': [ + '/var/lib/jenkins/workspace/Beats_beats_PR-22624/.gvm/versions/go1.14.7.linux.amd64/bin/go', + ], + }, + _source: {}, + sort: ['1605624488922', 'beats-ci-immutable-ubuntu-1804-1605624279743236239'], + aggregations: {}, + }; + + expect(getDataFromHits(response.fields)).toEqual([ + { + category: 'event', + field: 'event.category', + originalValue: ['process'], + values: ['process'], + }, + { category: 'process', field: 'process.ppid', originalValue: ['3977'], values: ['3977'] }, + { category: 'user', field: 'user.name', originalValue: ['jenkins'], values: ['jenkins'] }, + { + category: 'process', + field: 'process.args', + originalValue: ['go', 'vet', './...'], + values: ['go', 'vet', './...'], + }, + { + category: 'base', + field: 'message', + originalValue: ['Process go (PID: 4313) by user jenkins STARTED'], + values: ['Process go (PID: 4313) by user jenkins STARTED'], + }, + { category: 'process', field: 'process.pid', originalValue: ['4313'], values: ['4313'] }, + { + category: 'process', + field: 'process.working_directory', + originalValue: [ + '/var/lib/jenkins/workspace/Beats_beats_PR-22624/src/github.com/elastic/beats/libbeat', + ], + values: [ + '/var/lib/jenkins/workspace/Beats_beats_PR-22624/src/github.com/elastic/beats/libbeat', + ], + }, + { + category: 'process', + field: 'process.entity_id', + originalValue: ['Z59cIkAAIw8ZoK0H'], + values: ['Z59cIkAAIw8ZoK0H'], + }, + { + category: 'host', + field: 'host.ip', + originalValue: ['10.224.1.237', 'fe80::4001:aff:fee0:1ed', '172.17.0.1'], + values: ['10.224.1.237', 'fe80::4001:aff:fee0:1ed', '172.17.0.1'], + }, + { category: 'process', field: 'process.name', originalValue: ['go'], values: ['go'] }, + { + category: 'event', + field: 'event.action', + originalValue: ['process_started'], + values: ['process_started'], + }, + { + category: 'agent', + field: 'agent.type', + originalValue: ['auditbeat'], + values: ['auditbeat'], + }, + { + category: 'base', + field: '@timestamp', + originalValue: ['2020-11-17T14:48:08.922Z'], + values: ['2020-11-17T14:48:08.922Z'], + }, + { category: 'event', field: 'event.module', originalValue: ['system'], values: ['system'] }, + { category: 'event', field: 'event.type', originalValue: ['start'], values: ['start'] }, + { + category: 'host', + field: 'host.name', + originalValue: ['beats-ci-immutable-ubuntu-1804-1605624279743236239'], + values: ['beats-ci-immutable-ubuntu-1804-1605624279743236239'], + }, + { + category: 'process', + field: 'process.hash.sha1', + originalValue: ['1eac22336a41e0660fb302add9d97daa2bcc7040'], + values: ['1eac22336a41e0660fb302add9d97daa2bcc7040'], + }, + { category: 'host', field: 'host.os.family', originalValue: ['debian'], values: ['debian'] }, + { category: 'event', field: 'event.kind', originalValue: ['event'], values: ['event'] }, + { + category: 'host', + field: 'host.id', + originalValue: ['e59991e835905c65ed3e455b33e13bd6'], + values: ['e59991e835905c65ed3e455b33e13bd6'], + }, + { + category: 'event', + field: 'event.dataset', + originalValue: ['process'], + values: ['process'], + }, + { + category: 'process', + field: 'process.executable', + originalValue: [ + '/var/lib/jenkins/workspace/Beats_beats_PR-22624/.gvm/versions/go1.14.7.linux.amd64/bin/go', + ], + values: [ + '/var/lib/jenkins/workspace/Beats_beats_PR-22624/.gvm/versions/go1.14.7.linux.amd64/bin/go', + ], + }, + ]); + }); +}); diff --git a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/helpers.ts b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/helpers.ts index 2dd406ffaa450..68bef2e8c656a 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/helpers.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/helpers.ts @@ -4,9 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { get, isEmpty, isNumber, isObject, isString } from 'lodash/fp'; +import { isEmpty } from 'lodash/fp'; import { TimelineEventsDetailsItem } from '../../../../../../common/search_strategy/timeline'; +import { toStringArray } from '../../../../helpers/to_array'; export const baseCategoryFields = ['@timestamp', 'labels', 'message', 'tags']; @@ -18,39 +19,32 @@ export const getFieldCategory = (field: string): string => { return fieldCategory; }; -export const getDataFromHits = ( - sources: EventSource, - category?: string, - path?: string -): TimelineEventsDetailsItem[] => - Object.keys(sources).reduce((accumulator, source) => { - const item: EventSource = get(source, sources); - if (Array.isArray(item) || isString(item) || isNumber(item)) { - const field = path ? `${path}.${source}` : source; - const fieldCategory = getFieldCategory(field); +export const formatGeoLocation = (item: unknown[]) => { + const itemGeo = item.length > 0 ? (item[0] as { coordinates: number[] }) : null; + if (itemGeo != null && !isEmpty(itemGeo.coordinates)) { + try { + return toStringArray({ long: itemGeo.coordinates[0], lat: itemGeo.coordinates[1] }); + } catch { + return toStringArray(item); + } + } + return toStringArray(item); +}; - return [ - ...accumulator, - { - category: fieldCategory, - field, - values: Array.isArray(item) - ? item.map((value) => { - if (isObject(value)) { - return JSON.stringify(value); - } +export const isGeoField = (field: string) => + field.includes('geo.location') || field.includes('geoip.location'); - return value; - }) - : [item], - originalValue: item, - } as TimelineEventsDetailsItem, - ]; - } else if (isObject(item)) { - return [ - ...accumulator, - ...getDataFromHits(item, category || source, path ? `${path}.${source}` : source), - ]; - } - return accumulator; +export const getDataFromHits = (fields: Record): TimelineEventsDetailsItem[] => + Object.keys(fields).reduce((accumulator, field) => { + const item: unknown[] = fields[field]; + const fieldCategory = getFieldCategory(field); + return [ + ...accumulator, + { + category: fieldCategory, + field, + values: isGeoField(field) ? formatGeoLocation(item) : toStringArray(item), + originalValue: toStringArray(item), + } as TimelineEventsDetailsItem, + ]; }, []); diff --git a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/index.ts b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/index.ts index 54e138c1e9d6f..0a011d2bfe878 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/index.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/index.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getOr, merge } from 'lodash/fp'; +import { cloneDeep, merge } from 'lodash/fp'; import { IEsSearchResponse } from '../../../../../../../../../src/plugins/data/common'; import { @@ -27,13 +27,14 @@ export const timelineEventsDetails: SecuritySolutionTimelineFactory ): Promise => { const { indexName, eventId, docValueFields = [] } = options; - const sourceData = getOr({}, 'hits.hits.0._source', response.rawResponse); - const hitsData = getOr({}, 'hits.hits.0', response.rawResponse); + const fieldsData = cloneDeep(response.rawResponse.hits.hits[0].fields ?? {}); + const hitsData = cloneDeep(response.rawResponse.hits.hits[0] ?? {}); delete hitsData._source; + delete hitsData.fields; const inspect = { dsl: [inspectStringifyObject(buildTimelineDetailsQuery(indexName, eventId, docValueFields))], }; - const data = getDataFromHits(merge(sourceData, hitsData)); + const data = getDataFromHits(merge(fieldsData, hitsData)); return { ...response, diff --git a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/query.events_details.dsl.ts b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/query.events_details.dsl.ts index 216e8f947d261..8d70a08c214d8 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/query.events_details.dsl.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/timeline/factory/events/details/query.events_details.dsl.ts @@ -21,6 +21,7 @@ export const buildTimelineDetailsQuery = ( _id: [id], }, }, + fields: ['*'], }, size: 1, }); diff --git a/x-pack/plugins/snapshot_restore/public/application/components/policy_form/steps/step_logistics.tsx b/x-pack/plugins/snapshot_restore/public/application/components/policy_form/steps/step_logistics.tsx index 7d3ba92cf2ad7..c3d29bce57d54 100644 --- a/x-pack/plugins/snapshot_restore/public/application/components/policy_form/steps/step_logistics.tsx +++ b/x-pack/plugins/snapshot_restore/public/application/components/policy_form/steps/step_logistics.tsx @@ -23,7 +23,7 @@ import { } from '@elastic/eui'; import { Repository } from '../../../../../common/types'; -import { CronEditor, SectionError } from '../../../../shared_imports'; +import { Frequency, CronEditor, SectionError } from '../../../../shared_imports'; import { useServices } from '../../../app_context'; import { DEFAULT_POLICY_SCHEDULE, DEFAULT_POLICY_FREQUENCY } from '../../../constants'; import { useLoadRepositories } from '../../../services/http'; @@ -71,7 +71,7 @@ export const PolicyStepLogistics: React.FunctionComponent = ({ // State for cron editor const [simpleCron, setSimpleCron] = useState<{ expression: string; - frequency: string; + frequency: Frequency; }>({ expression: DEFAULT_POLICY_SCHEDULE, frequency: DEFAULT_POLICY_FREQUENCY, @@ -480,6 +480,7 @@ export const PolicyStepLogistics: React.FunctionComponent = ({ ) : ( = ({ cronExpression: expression, frequency, fieldToPreferredValueMap: newFieldToPreferredValueMap, - }: { - cronExpression: string; - frequency: string; - fieldToPreferredValueMap: any; }) => { setSimpleCron({ expression, diff --git a/x-pack/plugins/snapshot_restore/public/application/components/policy_form/steps/step_retention.tsx b/x-pack/plugins/snapshot_restore/public/application/components/policy_form/steps/step_retention.tsx index 407b9be14e3c1..ee638edd09bb8 100644 --- a/x-pack/plugins/snapshot_restore/public/application/components/policy_form/steps/step_retention.tsx +++ b/x-pack/plugins/snapshot_restore/public/application/components/policy_form/steps/step_retention.tsx @@ -14,6 +14,7 @@ import { EuiButtonEmpty, EuiFieldNumber, EuiSelect, + EuiCode, } from '@elastic/eui'; import { SlmPolicyPayload } from '../../../../../common/types'; @@ -135,7 +136,10 @@ export const PolicyStepRetention: React.FunctionComponent = ({ description={ 200, + }} /> } fullWidth diff --git a/x-pack/plugins/snapshot_restore/public/application/components/retention_update_modal_provider.tsx b/x-pack/plugins/snapshot_restore/public/application/components/retention_update_modal_provider.tsx index 2765006f9dcbc..40f37d6e67e90 100644 --- a/x-pack/plugins/snapshot_restore/public/application/components/retention_update_modal_provider.tsx +++ b/x-pack/plugins/snapshot_restore/public/application/components/retention_update_modal_provider.tsx @@ -25,7 +25,7 @@ import { import { useServices, useToastNotifications } from '../app_context'; import { documentationLinksService } from '../services/documentation'; -import { CronEditor } from '../../shared_imports'; +import { Frequency, CronEditor } from '../../shared_imports'; import { DEFAULT_RETENTION_SCHEDULE, DEFAULT_RETENTION_FREQUENCY } from '../constants'; import { updateRetentionSchedule } from '../services/http'; @@ -57,7 +57,7 @@ export const RetentionSettingsUpdateModalProvider: React.FunctionComponent({ expression: DEFAULT_RETENTION_SCHEDULE, frequency: DEFAULT_RETENTION_FREQUENCY, @@ -234,10 +234,6 @@ export const RetentionSettingsUpdateModalProvider: React.FunctionComponent { setSimpleCron({ expression, diff --git a/x-pack/plugins/snapshot_restore/public/application/constants/index.ts b/x-pack/plugins/snapshot_restore/public/application/constants/index.ts index 2f4945b625b53..1cf41da736e19 100644 --- a/x-pack/plugins/snapshot_restore/public/application/constants/index.ts +++ b/x-pack/plugins/snapshot_restore/public/application/constants/index.ts @@ -4,8 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { DAY } from '../../shared_imports'; - export const BASE_PATH = ''; export const DEFAULT_SECTION: Section = 'snapshots'; export type Section = 'repositories' | 'snapshots' | 'restore_status' | 'policies'; @@ -89,10 +87,10 @@ export const REMOVE_INDEX_SETTINGS_SUGGESTIONS: string[] = INDEX_SETTING_SUGGEST ); export const DEFAULT_POLICY_SCHEDULE = '0 30 1 * * ?'; -export const DEFAULT_POLICY_FREQUENCY = DAY; +export const DEFAULT_POLICY_FREQUENCY = 'DAY'; export const DEFAULT_RETENTION_SCHEDULE = '0 30 1 * * ?'; -export const DEFAULT_RETENTION_FREQUENCY = DAY; +export const DEFAULT_RETENTION_FREQUENCY = 'DAY'; // UI Metric constants export const UIM_APP_NAME = 'snapshot_restore'; diff --git a/x-pack/plugins/snapshot_restore/public/shared_imports.ts b/x-pack/plugins/snapshot_restore/public/shared_imports.ts index bd1c0e0cd395b..411ec8627c726 100644 --- a/x-pack/plugins/snapshot_restore/public/shared_imports.ts +++ b/x-pack/plugins/snapshot_restore/public/shared_imports.ts @@ -7,8 +7,8 @@ export { AuthorizationProvider, CronEditor, - DAY, Error, + Frequency, NotAuthorizedSection, SectionError, sendRequest, diff --git a/x-pack/plugins/spaces/public/management/edit_space/manage_space_page.test.tsx b/x-pack/plugins/spaces/public/management/edit_space/manage_space_page.test.tsx index 54960fba731d2..bc26d6f132522 100644 --- a/x-pack/plugins/spaces/public/management/edit_space/manage_space_page.test.tsx +++ b/x-pack/plugins/spaces/public/management/edit_space/manage_space_page.test.tsx @@ -7,7 +7,7 @@ import { EuiButton, EuiCheckboxProps } from '@elastic/eui'; import { ReactWrapper } from 'enzyme'; import React from 'react'; -import { wait } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import { mountWithIntl } from '@kbn/test/jest'; import { ConfirmAlterActiveSpaceModal } from './confirm_alter_active_space_modal'; @@ -70,7 +70,7 @@ describe('ManageSpacePage', () => { /> ); - await wait(() => { + await waitFor(() => { wrapper.update(); expect(wrapper.find('input[name="name"]')).toHaveLength(1); }); @@ -132,7 +132,7 @@ describe('ManageSpacePage', () => { /> ); - await wait(() => { + await waitFor(() => { wrapper.update(); expect(spacesManager.getSpace).toHaveBeenCalledWith('existing-space'); }); @@ -185,7 +185,7 @@ describe('ManageSpacePage', () => { /> ); - await wait(() => { + await waitFor(() => { wrapper.update(); expect(notifications.toasts.addError).toHaveBeenCalledWith(error, { title: 'Error loading available features', @@ -223,7 +223,7 @@ describe('ManageSpacePage', () => { /> ); - await wait(() => { + await waitFor(() => { wrapper.update(); expect(spacesManager.getSpace).toHaveBeenCalledWith('my-space'); }); @@ -285,7 +285,7 @@ describe('ManageSpacePage', () => { /> ); - await wait(() => { + await waitFor(() => { wrapper.update(); expect(spacesManager.getSpace).toHaveBeenCalledWith('my-space'); }); diff --git a/x-pack/plugins/spaces/public/nav_control/nav_control_popover.test.tsx b/x-pack/plugins/spaces/public/nav_control/nav_control_popover.test.tsx index b08c1c834ac4f..e841d3efc828c 100644 --- a/x-pack/plugins/spaces/public/nav_control/nav_control_popover.test.tsx +++ b/x-pack/plugins/spaces/public/nav_control/nav_control_popover.test.tsx @@ -13,7 +13,7 @@ import { SpacesManager } from '../spaces_manager'; import { NavControlPopover } from './nav_control_popover'; import { EuiHeaderSectionItemButton } from '@elastic/eui'; import { mountWithIntl } from '@kbn/test/jest'; -import { wait } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; describe('NavControlPopover', () => { it('renders without crashing', () => { @@ -65,7 +65,7 @@ describe('NavControlPopover', () => { wrapper.find(EuiHeaderSectionItemButton).simulate('click'); // Wait for `getSpaces` promise to resolve - await wait(() => { + await waitFor(() => { wrapper.update(); expect(wrapper.find(SpaceAvatar)).toHaveLength(3); }); diff --git a/x-pack/plugins/spaces/server/lib/copy_to_spaces/copy_to_spaces.test.ts b/x-pack/plugins/spaces/server/lib/copy_to_spaces/copy_to_spaces.test.ts index d1a8e93bff929..945a2bdbf6daf 100644 --- a/x-pack/plugins/spaces/server/lib/copy_to_spaces/copy_to_spaces.test.ts +++ b/x-pack/plugins/spaces/server/lib/copy_to_spaces/copy_to_spaces.test.ts @@ -18,6 +18,9 @@ import { } from 'src/core/server/mocks'; import { copySavedObjectsToSpacesFactory } from './copy_to_spaces'; +// Mock out circular dependency +jest.mock('../../../../../../src/core/server/saved_objects/es_query', () => {}); + jest.mock('../../../../../../src/core/server', () => { return { ...(jest.requireActual('../../../../../../src/core/server') as Record), diff --git a/x-pack/plugins/spaces/server/lib/copy_to_spaces/resolve_copy_conflicts.test.ts b/x-pack/plugins/spaces/server/lib/copy_to_spaces/resolve_copy_conflicts.test.ts index f1b475ee9d1b3..0e54412ee61ae 100644 --- a/x-pack/plugins/spaces/server/lib/copy_to_spaces/resolve_copy_conflicts.test.ts +++ b/x-pack/plugins/spaces/server/lib/copy_to_spaces/resolve_copy_conflicts.test.ts @@ -18,6 +18,9 @@ import { } from 'src/core/server/mocks'; import { resolveCopySavedObjectsToSpacesConflictsFactory } from './resolve_copy_conflicts'; +// Mock out circular dependency +jest.mock('../../../../../../src/core/server/saved_objects/es_query', () => {}); + jest.mock('../../../../../../src/core/server', () => { return { ...(jest.requireActual('../../../../../../src/core/server') as Record), diff --git a/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.test.ts b/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.test.ts index cb81476454cd3..c8b25bf3cf7fa 100644 --- a/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.test.ts +++ b/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.test.ts @@ -27,6 +27,10 @@ import { usageStatsServiceMock } from '../../../usage_stats/usage_stats_service. import { initCopyToSpacesApi } from './copy_to_space'; import { spacesConfig } from '../../../lib/__fixtures__'; import { ObjectType } from '@kbn/config-schema'; + +// Mock out circular dependency +jest.mock('../../../../../../../src/core/server/saved_objects/es_query', () => {}); + jest.mock('../../../../../../../src/core/server', () => { return { ...(jest.requireActual('../../../../../../../src/core/server') as Record), diff --git a/x-pack/plugins/stack_alerts/common/config.ts b/x-pack/plugins/stack_alerts/common/config.ts index 88d4699027425..a1ec8a1e1c454 100644 --- a/x-pack/plugins/stack_alerts/common/config.ts +++ b/x-pack/plugins/stack_alerts/common/config.ts @@ -8,7 +8,7 @@ import { schema, TypeOf } from '@kbn/config-schema'; export const configSchema = schema.object({ enabled: schema.boolean({ defaultValue: true }), - enableGeoAlerts: schema.boolean({ defaultValue: false }), + enableGeoAlerting: schema.boolean({ defaultValue: false }), }); export type Config = TypeOf; diff --git a/x-pack/plugins/stack_alerts/public/alert_types/index.ts b/x-pack/plugins/stack_alerts/public/alert_types/index.ts index 9d611aefb738b..1a9710eb08eb0 100644 --- a/x-pack/plugins/stack_alerts/public/alert_types/index.ts +++ b/x-pack/plugins/stack_alerts/public/alert_types/index.ts @@ -17,7 +17,7 @@ export function registerAlertTypes({ alertTypeRegistry: TriggersAndActionsUIPublicPluginSetup['alertTypeRegistry']; config: Config; }) { - if (config.enableGeoAlerts) { + if (config.enableGeoAlerting) { alertTypeRegistry.register(getGeoThresholdAlertType()); alertTypeRegistry.register(getGeoContainmentAlertType()); } diff --git a/x-pack/plugins/stack_alerts/server/feature.ts b/x-pack/plugins/stack_alerts/server/feature.ts index 4ac0bc43adcd7..448e1e698858b 100644 --- a/x-pack/plugins/stack_alerts/server/feature.ts +++ b/x-pack/plugins/stack_alerts/server/feature.ts @@ -7,6 +7,7 @@ import { i18n } from '@kbn/i18n'; import { ID as IndexThreshold } from './alert_types/index_threshold/alert_type'; import { GEO_THRESHOLD_ID as GeoThreshold } from './alert_types/geo_threshold/alert_type'; +import { GEO_CONTAINMENT_ID as GeoContainment } from './alert_types/geo_containment/alert_type'; import { STACK_ALERTS_FEATURE_ID } from '../common'; import { DEFAULT_APP_CATEGORIES } from '../../../../src/core/server'; @@ -20,7 +21,7 @@ export const BUILT_IN_ALERTS_FEATURE = { management: { insightsAndAlerting: ['triggersActions'], }, - alerting: [IndexThreshold, GeoThreshold], + alerting: [IndexThreshold, GeoThreshold, GeoContainment], privileges: { all: { app: [], @@ -29,7 +30,7 @@ export const BUILT_IN_ALERTS_FEATURE = { insightsAndAlerting: ['triggersActions'], }, alerting: { - all: [IndexThreshold, GeoThreshold], + all: [IndexThreshold, GeoThreshold, GeoContainment], read: [], }, savedObject: { @@ -47,7 +48,7 @@ export const BUILT_IN_ALERTS_FEATURE = { }, alerting: { all: [], - read: [IndexThreshold, GeoThreshold], + read: [IndexThreshold, GeoThreshold, GeoContainment], }, savedObject: { all: [], diff --git a/x-pack/plugins/stack_alerts/server/index.ts b/x-pack/plugins/stack_alerts/server/index.ts index 3ef8db33983de..08197b368d9d9 100644 --- a/x-pack/plugins/stack_alerts/server/index.ts +++ b/x-pack/plugins/stack_alerts/server/index.ts @@ -11,13 +11,13 @@ export { ID as INDEX_THRESHOLD_ID } from './alert_types/index_threshold/alert_ty export const config: PluginConfigDescriptor = { exposeToBrowser: { - enableGeoAlerts: true, + enableGeoAlerting: true, }, schema: configSchema, deprecations: ({ renameFromRoot }) => [ renameFromRoot( 'xpack.triggers_actions_ui.enableGeoTrackingThresholdAlert', - 'xpack.stack_alerts.enableGeoAlerts' + 'xpack.stack_alerts.enableGeoAlerting' ), ], }; diff --git a/x-pack/plugins/transform/server/client/elasticsearch_transform.ts b/x-pack/plugins/transform/server/client/elasticsearch_transform.ts deleted file mode 100644 index a17eb1416408a..0000000000000 --- a/x-pack/plugins/transform/server/client/elasticsearch_transform.ts +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -export const elasticsearchJsPlugin = (Client: any, config: any, components: any) => { - const ca = components.clientAction.factory; - - Client.prototype.transform = components.clientAction.namespaceFactory(); - const transform = Client.prototype.transform.prototype; - - // Currently the endpoint uses a default size of 100 unless a size is supplied. - // So until paging is supported in the UI, explicitly supply a size of 1000 - // to match the max number of docs that the endpoint can return. - transform.getTransforms = ca({ - urls: [ - { - fmt: '/_transform/<%=transformId%>', - req: { - transformId: { - type: 'string', - }, - }, - }, - { - fmt: '/_transform/_all?size=1000', - }, - ], - method: 'GET', - }); - - transform.getTransformsStats = ca({ - urls: [ - { - fmt: '/_transform/<%=transformId%>/_stats', - req: { - transformId: { - type: 'string', - }, - }, - }, - { - // Currently the endpoint uses a default size of 100 unless a size is supplied. - // So until paging is supported in the UI, explicitly supply a size of 1000 - // to match the max number of docs that the endpoint can return. - fmt: '/_transform/_all/_stats?size=1000', - }, - ], - method: 'GET', - }); - - transform.createTransform = ca({ - urls: [ - { - fmt: '/_transform/<%=transformId%>', - req: { - transformId: { - type: 'string', - }, - }, - }, - ], - needBody: true, - method: 'PUT', - }); - - transform.updateTransform = ca({ - urls: [ - { - fmt: '/_transform/<%=transformId%>/_update', - req: { - transformId: { - type: 'string', - }, - }, - }, - ], - needBody: true, - method: 'POST', - }); - - transform.deleteTransform = ca({ - urls: [ - { - fmt: '/_transform/<%=transformId%>?&force=<%=force%>', - req: { - transformId: { - type: 'string', - }, - force: { - type: 'boolean', - }, - }, - }, - ], - method: 'DELETE', - }); - - transform.getTransformsPreview = ca({ - urls: [ - { - fmt: '/_transform/_preview', - }, - ], - needBody: true, - method: 'POST', - }); - - transform.startTransform = ca({ - urls: [ - { - fmt: '/_transform/<%=transformId%>/_start', - req: { - transformId: { - type: 'string', - }, - }, - }, - ], - method: 'POST', - }); - - transform.stopTransform = ca({ - urls: [ - { - fmt: - '/_transform/<%=transformId%>/_stop?&force=<%=force%>&wait_for_completion=<%waitForCompletion%>', - req: { - transformId: { - type: 'string', - }, - force: { - type: 'boolean', - }, - waitForCompletion: { - type: 'boolean', - }, - }, - }, - ], - method: 'POST', - }); -}; diff --git a/x-pack/plugins/transform/server/plugin.ts b/x-pack/plugins/transform/server/plugin.ts index 988750f70efe0..987028dcacf05 100644 --- a/x-pack/plugins/transform/server/plugin.ts +++ b/x-pack/plugins/transform/server/plugin.ts @@ -4,30 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ import { i18n } from '@kbn/i18n'; -import { - CoreSetup, - ILegacyCustomClusterClient, - Plugin, - ILegacyScopedClusterClient, - Logger, - PluginInitializerContext, -} from 'src/core/server'; +import { CoreSetup, Plugin, Logger, PluginInitializerContext } from 'src/core/server'; import { LicenseType } from '../../licensing/common/types'; -import { elasticsearchJsPlugin } from './client/elasticsearch_transform'; import { Dependencies } from './types'; import { ApiRoutes } from './routes'; import { License } from './services'; -declare module 'kibana/server' { - interface RequestHandlerContext { - transform?: { - dataClient: ILegacyScopedClusterClient; - }; - } -} - const basicLicense: LicenseType = 'basic'; const PLUGIN = { @@ -39,18 +23,10 @@ const PLUGIN = { }), }; -async function getCustomEsClient(getStartServices: CoreSetup['getStartServices']) { - const [core] = await getStartServices(); - return core.elasticsearch.legacy.createClient('transform', { - plugins: [elasticsearchJsPlugin], - }); -} - export class TransformServerPlugin implements Plugin<{}, void, any, any> { private readonly apiRoutes: ApiRoutes; private readonly license: License; private readonly logger: Logger; - private transformESClient?: ILegacyCustomClusterClient; constructor(initContext: PluginInitializerContext) { this.logger = initContext.logger.get(); @@ -58,7 +34,10 @@ export class TransformServerPlugin implements Plugin<{}, void, any, any> { this.license = new License(); } - setup({ http, getStartServices }: CoreSetup, { licensing, features }: Dependencies): {} { + setup( + { http, getStartServices, elasticsearch }: CoreSetup, + { licensing, features }: Dependencies + ): {} { const router = http.createRouter(); this.license.setup( @@ -94,23 +73,10 @@ export class TransformServerPlugin implements Plugin<{}, void, any, any> { license: this.license, }); - // Can access via new platform router's handler function 'context' parameter - context.transform.client - http.registerRouteHandlerContext('transform', async (context, request) => { - this.transformESClient = - this.transformESClient ?? (await getCustomEsClient(getStartServices)); - return { - dataClient: this.transformESClient.asScoped(request), - }; - }); - return {}; } start() {} - stop() { - if (this.transformESClient) { - this.transformESClient.close(); - } - } + stop() {} } diff --git a/x-pack/plugins/transform/server/routes/api/error_utils.ts b/x-pack/plugins/transform/server/routes/api/error_utils.ts index cf388f3c8ca08..fe50830cd24f2 100644 --- a/x-pack/plugins/transform/server/routes/api/error_utils.ts +++ b/x-pack/plugins/transform/server/routes/api/error_utils.ts @@ -76,7 +76,7 @@ export function fillResultsWithTimeouts({ results, id, items, action }: Params) } export function wrapError(error: any): CustomHttpResponseOptions { - const boom = Boom.isBoom(error) ? error : Boom.boomify(error, { statusCode: error.status }); + const boom = Boom.isBoom(error) ? error : Boom.boomify(error, { statusCode: error.statusCode }); return { body: boom, headers: boom.output.headers, @@ -109,14 +109,16 @@ function extractCausedByChain( * @return Object Boom error response */ export function wrapEsError(err: any, statusCodeToMessageMap: Record = {}) { - const { statusCode, response } = err; + const { + meta: { body, statusCode }, + } = err; const { error: { root_cause = [], // eslint-disable-line @typescript-eslint/naming-convention caused_by = {}, // eslint-disable-line @typescript-eslint/naming-convention } = {}, - } = JSON.parse(response); + } = body; // If no custom message if specified for the error's status code, just // wrap the error as a Boom error response, include the additional information from ES, and return it @@ -130,6 +132,12 @@ export function wrapEsError(err: any, statusCodeToMessageMap: Record { - const options = {}; + license.guardApiRoute(async (ctx, req, res) => { try { - const transforms = await getTransforms( - options, - ctx.transform!.dataClient.callAsCurrentUser - ); - return res.ok({ body: transforms }); + const { body } = await ctx.core.elasticsearch.client.asCurrentUser.transform.getTransform({ + size: 1000, + ...req.params, + }); + return res.ok({ body }); } catch (e) { return res.customError(wrapError(wrapEsError(e))); } @@ -113,13 +107,11 @@ export function registerTransformsRoutes(routeDependencies: RouteDependencies) { }, license.guardApiRoute(async (ctx, req, res) => { const { transformId } = req.params; - const options = transformId !== undefined ? { transformId } : {}; try { - const transforms = await getTransforms( - options, - ctx.transform!.dataClient.callAsCurrentUser - ); - return res.ok({ body: transforms }); + const { body } = await ctx.core.elasticsearch.client.asCurrentUser.transform.getTransform({ + transform_id: transformId, + }); + return res.ok({ body }); } catch (e) { return res.customError(wrapError(wrapEsError(e))); } @@ -135,18 +127,21 @@ export function registerTransformsRoutes(routeDependencies: RouteDependencies) { */ router.get( { path: addBasePath('transforms/_stats'), validate: false }, - license.guardApiRoute(async (ctx, req, res) => { - const options = {}; - try { - const stats = await ctx.transform!.dataClient.callAsCurrentUser( - 'transform.getTransformsStats', - options - ); - return res.ok({ body: stats }); - } catch (e) { - return res.customError(wrapError(wrapEsError(e))); + license.guardApiRoute( + async (ctx, req, res) => { + try { + const { + body, + } = await ctx.core.elasticsearch.client.asCurrentUser.transform.getTransformStats({ + size: 1000, + transform_id: '_all', + }); + return res.ok({ body }); + } catch (e) { + return res.customError(wrapError(wrapEsError(e))); + } } - }) + ) ); /** @@ -165,15 +160,13 @@ export function registerTransformsRoutes(routeDependencies: RouteDependencies) { }, license.guardApiRoute(async (ctx, req, res) => { const { transformId } = req.params; - const options = { - ...(transformId !== undefined ? { transformId } : {}), - }; try { - const stats = await ctx.transform!.dataClient.callAsCurrentUser( - 'transform.getTransformsStats', - options - ); - return res.ok({ body: stats }); + const { + body, + } = await ctx.core.elasticsearch.client.asCurrentUser.transform.getTransformStats({ + transform_id: transformId, + }); + return res.ok({ body }); } catch (e) { return res.customError(wrapError(wrapEsError(e))); } @@ -208,12 +201,14 @@ export function registerTransformsRoutes(routeDependencies: RouteDependencies) { errors: [], }; - await ctx - .transform!.dataClient.callAsCurrentUser('transform.createTransform', { + await ctx.core.elasticsearch.client.asCurrentUser.transform + .putTransform({ body: req.body, - transformId, + transform_id: transformId, + }) + .then(() => { + response.transformsCreated.push({ transform: transformId }); }) - .then(() => response.transformsCreated.push({ transform: transformId })) .catch((e) => response.errors.push({ id: transformId, @@ -249,11 +244,14 @@ export function registerTransformsRoutes(routeDependencies: RouteDependencies) { const { transformId } = req.params; try { + const { + body, + } = await ctx.core.elasticsearch.client.asCurrentUser.transform.updateTransform({ + body: req.body, + transform_id: transformId, + }); return res.ok({ - body: (await ctx.transform!.dataClient.callAsCurrentUser('transform.updateTransform', { - body: req.body, - transformId, - })) as PostTransformsUpdateResponseSchema, + body, }); } catch (e) { return res.customError(wrapError(e)); @@ -381,9 +379,8 @@ export function registerTransformsRoutes(routeDependencies: RouteDependencies) { }, license.guardApiRoute(async (ctx, req, res) => { try { - return res.ok({ - body: await ctx.transform!.dataClient.callAsCurrentUser('search', req.body), - }); + const { body } = await ctx.core.elasticsearch.client.asCurrentUser.search(req.body); + return res.ok({ body }); } catch (e) { return res.customError(wrapError(wrapEsError(e))); } @@ -391,13 +388,6 @@ export function registerTransformsRoutes(routeDependencies: RouteDependencies) { ); } -const getTransforms = async ( - options: { transformId?: string }, - callAsCurrentUser: LegacyAPICaller -): Promise => { - return await callAsCurrentUser('transform.getTransforms', options); -}; - async function getIndexPatternId( indexName: string, savedObjectsClient: SavedObjectsClientContract @@ -452,11 +442,10 @@ async function deleteTransforms( } // Grab destination index info to delete try { - const transformConfigs = await getTransforms( - { transformId }, - ctx.transform!.dataClient.callAsCurrentUser - ); - const transformConfig = transformConfigs.transforms[0]; + const { body } = await ctx.core.elasticsearch.client.asCurrentUser.transform.getTransform({ + transform_id: transformId, + }); + const transformConfig = body.transforms[0]; destinationIndex = Array.isArray(transformConfig.dest.index) ? transformConfig.dest.index[0] : transformConfig.dest.index; @@ -468,6 +457,7 @@ async function deleteTransforms( destIndexPatternDeleted, destinationIndex, }; + // No need to perform further delete attempts continue; } @@ -476,7 +466,7 @@ async function deleteTransforms( try { // If user does have privilege to delete the index, then delete the index // if no permission then return 403 forbidden - await ctx.transform!.dataClient.callAsCurrentUser('indices.delete', { + await ctx.core.elasticsearch.client.asCurrentUser.indices.delete({ index: destinationIndex, }); destIndexDeleted.success = true; @@ -502,14 +492,14 @@ async function deleteTransforms( } try { - await ctx.transform!.dataClient.callAsCurrentUser('transform.deleteTransform', { - transformId, + await ctx.core.elasticsearch.client.asCurrentUser.transform.deleteTransform({ + transform_id: transformId, force: shouldForceDelete && needToForceDelete, }); transformDeleted.success = true; } catch (deleteTransformJobError) { transformDeleted.error = wrapError(deleteTransformJobError); - if (transformDeleted.error.statusCode === 403) { + if (deleteTransformJobError.statusCode === 403) { return response.forbidden(); } } @@ -541,11 +531,10 @@ const previewTransformHandler: RequestHandler< PostTransformsPreviewRequestSchema > = async (ctx, req, res) => { try { - return res.ok({ - body: await ctx.transform!.dataClient.callAsCurrentUser('transform.getTransformsPreview', { - body: req.body, - }), + const { body } = await ctx.core.elasticsearch.client.asCurrentUser.transform.previewTransform({ + body: req.body, }); + return res.ok({ body }); } catch (e) { return res.customError(wrapError(wrapEsError(e))); } @@ -559,8 +548,9 @@ const startTransformsHandler: RequestHandler< const transformsInfo = req.body; try { + const body = await startTransforms(transformsInfo, ctx.core.elasticsearch.client.asCurrentUser); return res.ok({ - body: await startTransforms(transformsInfo, ctx.transform!.dataClient.callAsCurrentUser), + body, }); } catch (e) { return res.customError(wrapError(wrapEsError(e))); @@ -569,14 +559,16 @@ const startTransformsHandler: RequestHandler< async function startTransforms( transformsInfo: StartTransformsRequestSchema, - callAsCurrentUser: LegacyAPICaller + esClient: ElasticsearchClient ) { const results: StartTransformsResponseSchema = {}; for (const transformInfo of transformsInfo) { const transformId = transformInfo.id; try { - await callAsCurrentUser('transform.startTransform', { transformId }); + await esClient.transform.startTransform({ + transform_id: transformId, + }); results[transformId] = { success: true }; } catch (e) { if (isRequestTimeout(e)) { @@ -602,7 +594,7 @@ const stopTransformsHandler: RequestHandler< try { return res.ok({ - body: await stopTransforms(transformsInfo, ctx.transform!.dataClient.callAsCurrentUser), + body: await stopTransforms(transformsInfo, ctx.core.elasticsearch.client.asCurrentUser), }); } catch (e) { return res.customError(wrapError(wrapEsError(e))); @@ -611,21 +603,21 @@ const stopTransformsHandler: RequestHandler< async function stopTransforms( transformsInfo: StopTransformsRequestSchema, - callAsCurrentUser: LegacyAPICaller + esClient: ElasticsearchClient ) { const results: StopTransformsResponseSchema = {}; for (const transformInfo of transformsInfo) { const transformId = transformInfo.id; try { - await callAsCurrentUser('transform.stopTransform', { - transformId, + await esClient.transform.stopTransform({ + transform_id: transformId, force: transformInfo.state !== undefined ? transformInfo.state === TRANSFORM_STATE.FAILED : false, - waitForCompletion: true, - } as StopOptions); + wait_for_completion: true, + }); results[transformId] = { success: true }; } catch (e) { if (isRequestTimeout(e)) { diff --git a/x-pack/plugins/transform/server/routes/api/transforms_audit_messages.ts b/x-pack/plugins/transform/server/routes/api/transforms_audit_messages.ts index 8c95ab5c786ed..3563775b26f3c 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms_audit_messages.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms_audit_messages.ts @@ -77,7 +77,7 @@ export function registerTransformsAuditMessagesRoutes({ router, license }: Route } try { - const resp = await ctx.transform!.dataClient.callAsCurrentUser('search', { + const { body: resp } = await ctx.core.elasticsearch.client.asCurrentUser.search({ index: ML_DF_NOTIFICATION_INDEX_PATTERN, ignore_unavailable: true, size: SIZE, diff --git a/x-pack/plugins/transform/server/routes/index.ts b/x-pack/plugins/transform/server/routes/index.ts index 4f35b094017a4..36aea6677b815 100644 --- a/x-pack/plugins/transform/server/routes/index.ts +++ b/x-pack/plugins/transform/server/routes/index.ts @@ -20,7 +20,4 @@ export class ApiRoutes { registerPrivilegesRoute(dependencies); registerTransformsRoutes(dependencies); } - - start() {} - stop() {} } diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 1f36a5a71537b..2effc90946b58 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -7190,22 +7190,15 @@ "xpack.fleet.agentList.policyFilterText": "エージェントポリシー", "xpack.fleet.agentList.reassignActionText": "新しいポリシーに割り当てる", "xpack.fleet.agentList.revisionNumber": "rev. {revNumber}", - "xpack.fleet.agentList.showInactiveSwitchLabel": "非アクティブ", "xpack.fleet.agentList.showUpgradeableFilterLabel": "アップグレードが利用可能です", "xpack.fleet.agentList.statusColumnTitle": "ステータス", - "xpack.fleet.agentList.statusErrorFilterText": "エラー", "xpack.fleet.agentList.statusFilterText": "ステータス", "xpack.fleet.agentList.statusOfflineFilterText": "オフライン", - "xpack.fleet.agentList.statusOnlineFilterText": "オンライン", "xpack.fleet.agentList.statusUpdatingFilterText": "更新中", "xpack.fleet.agentList.unenrollOneButton": "エージェントの登録解除", "xpack.fleet.agentList.upgradeOneButton": "エージェントをアップグレード", "xpack.fleet.agentList.versionTitle": "バージョン", "xpack.fleet.agentList.viewActionText": "エージェントを表示", - "xpack.fleet.agentListStatus.errorLabel": "エラー", - "xpack.fleet.agentListStatus.offlineLabel": "オフライン", - "xpack.fleet.agentListStatus.onlineLabel": "オンライン", - "xpack.fleet.agentListStatus.totalLabel": "エージェント", "xpack.fleet.agentPolicy.confirmModalCalloutDescription": "選択されたエージェントポリシー{policyName}が一部のエージェントですでに使用されていることをFleetが検出しました。このアクションの結果として、Fleetはこのポリシーで使用されているすべてのエージェントに更新をデプロイします。", "xpack.fleet.agentPolicy.confirmModalCancelButtonLabel": "キャンセル", "xpack.fleet.agentPolicy.confirmModalConfirmButtonLabel": "変更を保存してデプロイ", @@ -7359,7 +7352,6 @@ "xpack.fleet.dataStreamList.viewDashboardActionText": "ダッシュボードを表示", "xpack.fleet.dataStreamList.viewDashboardsActionText": "ダッシュボードを表示", "xpack.fleet.dataStreamList.viewDashboardsPanelTitle": "ダッシュボードを表示", - "xpack.fleet.defaultSearchPlaceholderText": "検索", "xpack.fleet.deleteAgentPolicy.confirmModal.affectedAgentsMessage": "{agentsCount, plural, one {#個のエージェントは} other {#個のエージェントは}}このエージェントポリシーに割り当てられました。このポリシーを削除する前に、これらのエージェントの割り当てを解除します。", "xpack.fleet.deleteAgentPolicy.confirmModal.affectedAgentsTitle": "使用中のポリシー", "xpack.fleet.deleteAgentPolicy.confirmModal.cancelButtonLabel": "キャンセル", @@ -11302,7 +11294,6 @@ "xpack.maps.source.emsTile.settingsTitle": "ベースマップ", "xpack.maps.source.emsTileDescription": "Elastic Maps Service のマップタイル", "xpack.maps.source.emsTileTitle": "タイル", - "xpack.maps.source.esAggSource.topTermLabel": "トップ {fieldName}", "xpack.maps.source.esGeoGrid.geofieldLabel": "地理空間フィールド", "xpack.maps.source.esGeoGrid.geofieldPlaceholder": "ジオフィールドを選択", "xpack.maps.source.esGeoGrid.gridRectangleDropdownOption": "グリッド", @@ -17915,7 +17906,6 @@ "xpack.securitySolution.resolver.eventDescription.networkEventLabel": "{ networkDirection } { forwardedIP }", "xpack.securitySolution.resolver.eventDescription.registryKeyLabel": "{ registryKey }", "xpack.securitySolution.resolver.eventDescription.registryPathLabel": "{ registryPath }", - "xpack.securitySolution.resolver.node_icon": "{running, select, true {実行中のプロセス} false {終了したプロセス}}", "xpack.securitySolution.resolver.panel.copyToClipboard": "クリップボードにコピー", "xpack.securitySolution.resolver.panel.eventDetail.requestError": "イベント詳細を取得できませんでした", "xpack.securitySolution.resolver.panel.nodeList.title": "すべてのプロセスイベント", @@ -18134,13 +18124,9 @@ "xpack.securitySolution.trustedapps.list.columns.actions": "アクション", "xpack.securitySolution.trustedapps.list.pageTitle": "信頼できるアプリケーション", "xpack.securitySolution.trustedapps.list.totalCount": "{totalItemCount, plural, one {#個の信頼できるアプリケーション} other {#個の信頼できるアプリケーション}}", - "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.field": "フィールド", "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.field.hash": "ハッシュ", "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.field.path": "パス", - "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.operator": "演算子", - "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.operator.is": "is", "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.removeLabel": "エントリを削除", - "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.value": "値", "xpack.securitySolution.trustedapps.logicalConditionBuilder.group.andOperator": "AND", "xpack.securitySolution.trustedapps.logicalConditionBuilder.noEntries": "条件が定義されていません", "xpack.securitySolution.trustedapps.noResults": "項目が見つかりません", @@ -18377,7 +18363,6 @@ "xpack.snapshotRestore.policyForm.stepLogistics.snapshotNameDescription": "スナップショットの名前です。それぞれの名前に自動的に追加される固有の識別子です。", "xpack.snapshotRestore.policyForm.stepLogistics.snapshotNameDescriptionTitle": "スナップショット名", "xpack.snapshotRestore.policyForm.stepLogisticsTitle": "ロジスティクス", - "xpack.snapshotRestore.policyForm.stepRetention.countDescription": "クラスターに格納するスナップショットの最少数と最大数。", "xpack.snapshotRestore.policyForm.stepRetention.countTitle": "保存するスナップショット", "xpack.snapshotRestore.policyForm.stepRetention.docsButtonLabel": "スナップショット保存ドキュメント", "xpack.snapshotRestore.policyForm.stepRetention.expirationDescription": "スナップショットの削除までに待つ時間です。", @@ -20323,8 +20308,6 @@ "xpack.uptime.breadcrumbs.overviewBreadcrumbText": "アップタイム", "xpack.uptime.certificates.heading": "TLS証明書({total})", "xpack.uptime.certificates.refresh": "更新", - "xpack.uptime.certificates.returnToOverviewLinkLabel": "概要に戻る", - "xpack.uptime.certificates.settingsLinkLabel": "設定", "xpack.uptime.certs.expired": "期限切れ", "xpack.uptime.certs.expires": "有効期限", "xpack.uptime.certs.expireSoon": "まもなく期限切れ", @@ -20462,7 +20445,6 @@ "xpack.uptime.monitorList.table.description": "列にステータス、名前、URL、IP、ダウンタイム履歴、統合が入力されたモニターステータス表です。この表は現在 {length} 項目を表示しています。", "xpack.uptime.monitorList.table.url.name": "Url", "xpack.uptime.monitorList.tlsColumnLabel": "TLS証明書", - "xpack.uptime.monitorList.viewCertificateTitle": "証明書ステータス", "xpack.uptime.monitorStatusBar.durationTextAriaLabel": "ミリ秒単位の監視時間", "xpack.uptime.monitorStatusBar.healthStatusMessageAriaLabel": "監視ステータス", "xpack.uptime.monitorStatusBar.loadingMessage": "読み込み中…", @@ -20528,7 +20510,6 @@ "xpack.uptime.settings.error.couldNotSave": "設定を保存できませんでした!", "xpack.uptime.settings.invalid.error": "値は0よりも大きい値でなければなりません。", "xpack.uptime.settings.invalid.nanError": "値は整数でなければなりません。", - "xpack.uptime.settings.returnToOverviewLinkLabel": "概要に戻る", "xpack.uptime.settings.saveSuccess": "設定が保存されました。", "xpack.uptime.settingsBreadcrumbText": "設定", "xpack.uptime.snapshot.donutChart.ariaLabel": "現在のステータスを表す円グラフ、{total}個中{down}個のモニターがダウンしています。", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 3151b863cc4a1..b2380d9ac226b 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -7196,22 +7196,15 @@ "xpack.fleet.agentList.policyFilterText": "代理策略", "xpack.fleet.agentList.reassignActionText": "分配到新策略", "xpack.fleet.agentList.revisionNumber": "修订 {revNumber}", - "xpack.fleet.agentList.showInactiveSwitchLabel": "非活动", "xpack.fleet.agentList.showUpgradeableFilterLabel": "升级可用", "xpack.fleet.agentList.statusColumnTitle": "状态", - "xpack.fleet.agentList.statusErrorFilterText": "错误", "xpack.fleet.agentList.statusFilterText": "状态", "xpack.fleet.agentList.statusOfflineFilterText": "脱机", - "xpack.fleet.agentList.statusOnlineFilterText": "联机", "xpack.fleet.agentList.statusUpdatingFilterText": "正在更新", "xpack.fleet.agentList.unenrollOneButton": "取消注册代理", "xpack.fleet.agentList.upgradeOneButton": "升级代理", "xpack.fleet.agentList.versionTitle": "版本", "xpack.fleet.agentList.viewActionText": "查看代理", - "xpack.fleet.agentListStatus.errorLabel": "错误", - "xpack.fleet.agentListStatus.offlineLabel": "脱机", - "xpack.fleet.agentListStatus.onlineLabel": "联机", - "xpack.fleet.agentListStatus.totalLabel": "代理", "xpack.fleet.agentPolicy.confirmModalCalloutDescription": "Fleet 检测到您的部分代理已在使用选定代理策略 {policyName}。由于此操作,Fleet 会将更新部署到使用此策略的所有代理。", "xpack.fleet.agentPolicy.confirmModalCalloutTitle": "此操作将更新 {agentCount, plural, one {# 个代理} other {# 个代理}}", "xpack.fleet.agentPolicy.confirmModalCancelButtonLabel": "取消", @@ -7366,7 +7359,6 @@ "xpack.fleet.dataStreamList.viewDashboardActionText": "查看仪表板", "xpack.fleet.dataStreamList.viewDashboardsActionText": "查看仪表板", "xpack.fleet.dataStreamList.viewDashboardsPanelTitle": "查看仪表板", - "xpack.fleet.defaultSearchPlaceholderText": "搜索", "xpack.fleet.deleteAgentPolicy.confirmModal.affectedAgentsMessage": "{agentsCount, plural, one {# 个代理} other {# 个代理}}已分配到此代理策略。在删除此策略前取消分配这些代理。", "xpack.fleet.deleteAgentPolicy.confirmModal.affectedAgentsTitle": "在用的策略", "xpack.fleet.deleteAgentPolicy.confirmModal.cancelButtonLabel": "取消", @@ -11315,7 +11307,6 @@ "xpack.maps.source.emsTile.settingsTitle": "Basemap", "xpack.maps.source.emsTileDescription": "Elastic 地图服务的地图磁贴", "xpack.maps.source.emsTileTitle": "磁贴", - "xpack.maps.source.esAggSource.topTermLabel": "热门{fieldName}", "xpack.maps.source.esGeoGrid.geofieldLabel": "地理空间字段", "xpack.maps.source.esGeoGrid.geofieldPlaceholder": "选择地理字段", "xpack.maps.source.esGeoGrid.gridRectangleDropdownOption": "网格", @@ -17933,7 +17924,6 @@ "xpack.securitySolution.resolver.eventDescription.networkEventLabel": "{ networkDirection } { forwardedIP }", "xpack.securitySolution.resolver.eventDescription.registryKeyLabel": "{ registryKey }", "xpack.securitySolution.resolver.eventDescription.registryPathLabel": "{ registryPath }", - "xpack.securitySolution.resolver.node_icon": "{running, select, true {正在运行的进程} false {已终止的进程}}", "xpack.securitySolution.resolver.panel.copyToClipboard": "复制到剪贴板", "xpack.securitySolution.resolver.panel.eventDetail.requestError": "无法检索事件详情", "xpack.securitySolution.resolver.panel.nodeList.title": "所有进程事件", @@ -18152,13 +18142,9 @@ "xpack.securitySolution.trustedapps.list.columns.actions": "操作", "xpack.securitySolution.trustedapps.list.pageTitle": "受信任的应用程序", "xpack.securitySolution.trustedapps.list.totalCount": "{totalItemCount, plural, one {# 个受信任的应用程序} other {# 个受信任的应用程序}}", - "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.field": "字段", "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.field.hash": "哈希", "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.field.path": "路径", - "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.operator": "运算符", - "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.operator.is": "is", "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.removeLabel": "移除条目", - "xpack.securitySolution.trustedapps.logicalConditionBuilder.entry.value": "值", "xpack.securitySolution.trustedapps.logicalConditionBuilder.group.andOperator": "AND", "xpack.securitySolution.trustedapps.logicalConditionBuilder.noEntries": "未定义条件", "xpack.securitySolution.trustedapps.noResults": "找不到项目", @@ -18395,7 +18381,6 @@ "xpack.snapshotRestore.policyForm.stepLogistics.snapshotNameDescription": "快照的名称。唯一标识符将自动添加到每个名称中。", "xpack.snapshotRestore.policyForm.stepLogistics.snapshotNameDescriptionTitle": "快照名称", "xpack.snapshotRestore.policyForm.stepLogisticsTitle": "运筹", - "xpack.snapshotRestore.policyForm.stepRetention.countDescription": "在您的集群中要存储的最小和最大快照数目。", "xpack.snapshotRestore.policyForm.stepRetention.countTitle": "要保留的快照", "xpack.snapshotRestore.policyForm.stepRetention.docsButtonLabel": "快照保留文档", "xpack.snapshotRestore.policyForm.stepRetention.expirationDescription": "删除快照前要等候的时间。", @@ -20342,8 +20327,6 @@ "xpack.uptime.breadcrumbs.overviewBreadcrumbText": "运行时间", "xpack.uptime.certificates.heading": "TLS 证书 ({total})", "xpack.uptime.certificates.refresh": "刷新", - "xpack.uptime.certificates.returnToOverviewLinkLabel": "返回到概览", - "xpack.uptime.certificates.settingsLinkLabel": "设置", "xpack.uptime.certs.expired": "已过期", "xpack.uptime.certs.expires": "过期", "xpack.uptime.certs.expireSoon": "即将过期", @@ -20481,7 +20464,6 @@ "xpack.uptime.monitorList.table.description": "具有“状态”、“名称”、“URL”、“IP”、“中断历史记录”和“集成”列的“监测状态”表。该表当前显示 {length} 个项目。", "xpack.uptime.monitorList.table.url.name": "URL", "xpack.uptime.monitorList.tlsColumnLabel": "TLS 证书", - "xpack.uptime.monitorList.viewCertificateTitle": "证书状态", "xpack.uptime.monitorStatusBar.durationTextAriaLabel": "监测持续时间(毫秒)", "xpack.uptime.monitorStatusBar.healthStatusMessageAriaLabel": "检测状态", "xpack.uptime.monitorStatusBar.loadingMessage": "正在加载……", @@ -20547,7 +20529,6 @@ "xpack.uptime.settings.error.couldNotSave": "无法保存设置!", "xpack.uptime.settings.invalid.error": "值必须大于 0。", "xpack.uptime.settings.invalid.nanError": "值必须为整数。", - "xpack.uptime.settings.returnToOverviewLinkLabel": "返回到概览", "xpack.uptime.settings.saveSuccess": "设置已保存!", "xpack.uptime.settingsBreadcrumbText": "设置", "xpack.uptime.snapshot.donutChart.ariaLabel": "显示当前状态的饼图。{total} 个监测中有 {down} 个已关闭。", diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.test.tsx index 5b2c8bd63a2f5..9de3ae21a8ef7 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.test.tsx @@ -11,6 +11,11 @@ import { actionTypeRegistryMock } from '../../action_type_registry.mock'; import { ValidationResult, Alert, AlertAction } from '../../../types'; import ActionForm from './action_form'; import { useKibana } from '../../../common/lib/kibana'; +import { + RecoveredActionGroup, + isActionGroupDisabledForActionTypeId, +} from '../../../../../alerts/common'; + jest.mock('../../../common/lib/kibana'); jest.mock('../../lib/action_connector_api', () => ({ loadAllActions: jest.fn(), @@ -65,6 +70,21 @@ describe('action_form', () => { actionParamsFields: mockedActionParamsFields, }; + const disabledByActionType = { + id: '.jira', + iconClass: 'test', + selectMessage: 'test', + validateConnector: (): ValidationResult => { + return { errors: {} }; + }, + validateParams: (): ValidationResult => { + const validationResult = { errors: {} }; + return validationResult; + }, + actionConnectorFields: null, + actionParamsFields: mockedActionParamsFields, + }; + const disabledByLicenseActionType = { id: 'disabled-by-license', iconClass: 'test', @@ -112,7 +132,7 @@ describe('action_form', () => { const useKibanaMock = useKibana as jest.Mocked; describe('action_form in alert', () => { - async function setup(customActions?: AlertAction[]) { + async function setup(customActions?: AlertAction[], customRecoveredActionGroup?: string) { const actionTypeRegistry = actionTypeRegistryMock.create(); const { loadAllActions } = jest.requireMock('../../lib/action_connector_api'); @@ -159,6 +179,14 @@ describe('action_form', () => { }, isPreconfigured: false, }, + { + secrets: {}, + id: '.jira', + actionTypeId: disabledByActionType.id, + name: 'Connector with disabled action group', + config: {}, + isPreconfigured: false, + }, ]); const mocks = coreMock.createSetup(); const [ @@ -179,6 +207,7 @@ describe('action_form', () => { actionType, disabledByConfigActionType, disabledByLicenseActionType, + disabledByActionType, preconfiguredOnly, actionTypeWithoutParams, ]); @@ -223,12 +252,24 @@ describe('action_form', () => { context: [{ name: 'contextVar', description: 'context var1' }], }} defaultActionGroupId={'default'} + isActionGroupDisabledForActionType={(actionGroupId: string, actionTypeId: string) => { + const recoveryActionGroupId = customRecoveredActionGroup + ? customRecoveredActionGroup + : 'recovered'; + return isActionGroupDisabledForActionTypeId( + actionGroupId === recoveryActionGroupId ? RecoveredActionGroup.id : actionGroupId, + actionTypeId + ); + }} setActionIdByIndex={(id: string, index: number) => { initialAlert.actions[index].id = id; }} actionGroups={[ { id: 'default', name: 'Default', defaultActionMessage }, - { id: 'recovered', name: 'Recovered' }, + { + id: customRecoveredActionGroup ? customRecoveredActionGroup : 'recovered', + name: customRecoveredActionGroup ? 'I feel better' : 'Recovered', + }, ]} setActionGroupIdByIndex={(group: string, index: number) => { initialAlert.actions[index].group = group; @@ -280,6 +321,14 @@ describe('action_form', () => { enabledInLicense: false, minimumLicenseRequired: 'gold', }, + { + id: '.jira', + name: 'Disabled by action type', + enabled: true, + enabledInConfig: true, + enabledInLicense: true, + minimumLicenseRequired: 'basic', + }, { id: actionTypeWithoutParams.id, name: 'Action type without params', @@ -342,11 +391,13 @@ describe('action_form', () => { Array [ Object { "data-test-subj": "addNewActionConnectorActionGroup-0-option-default", + "disabled": false, "inputDisplay": "Default", "value": "default", }, Object { "data-test-subj": "addNewActionConnectorActionGroup-0-option-recovered", + "disabled": false, "inputDisplay": "Recovered", "value": "recovered", }, @@ -354,6 +405,77 @@ describe('action_form', () => { `); }); + it('renders disabled action groups for selected action type', async () => { + const wrapper = await setup([ + { + group: 'recovered', + id: 'test', + actionTypeId: disabledByActionType.id, + params: { + message: '', + }, + }, + ]); + const actionOption = wrapper.find(`[data-test-subj=".jira-ActionTypeSelectOption"]`); + actionOption.first().simulate('click'); + const actionGroupsSelect = wrapper.find( + `[data-test-subj="addNewActionConnectorActionGroup-1"]` + ); + expect((actionGroupsSelect.first().props() as any).options).toMatchInlineSnapshot(` + Array [ + Object { + "data-test-subj": "addNewActionConnectorActionGroup-1-option-default", + "disabled": false, + "inputDisplay": "Default", + "value": "default", + }, + Object { + "data-test-subj": "addNewActionConnectorActionGroup-1-option-recovered", + "disabled": true, + "inputDisplay": "Recovered (Not Currently Supported)", + "value": "recovered", + }, + ] + `); + }); + + it('renders disabled action groups for custom recovered action groups', async () => { + const wrapper = await setup( + [ + { + group: 'iHaveRecovered', + id: 'test', + actionTypeId: disabledByActionType.id, + params: { + message: '', + }, + }, + ], + 'iHaveRecovered' + ); + const actionOption = wrapper.find(`[data-test-subj=".jira-ActionTypeSelectOption"]`); + actionOption.first().simulate('click'); + const actionGroupsSelect = wrapper.find( + `[data-test-subj="addNewActionConnectorActionGroup-1"]` + ); + expect((actionGroupsSelect.first().props() as any).options).toMatchInlineSnapshot(` + Array [ + Object { + "data-test-subj": "addNewActionConnectorActionGroup-1-option-default", + "disabled": false, + "inputDisplay": "Default", + "value": "default", + }, + Object { + "data-test-subj": "addNewActionConnectorActionGroup-1-option-iHaveRecovered", + "disabled": true, + "inputDisplay": "I feel better (Not Currently Supported)", + "value": "iHaveRecovered", + }, + ] + `); + }); + it('renders available connectors for the selected action type', async () => { const wrapper = await setup(); const actionOption = wrapper.find( diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.tsx index 0337f6879e24a..1cb1a68986192 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.tsx @@ -59,6 +59,7 @@ export interface ActionAccordionFormProps { setHasActionsWithBrokenConnector?: (value: boolean) => void; actionTypeRegistry: ActionTypeRegistryContract; getDefaultActionParams?: DefaultActionParamsGetter; + isActionGroupDisabledForActionType?: (actionGroupId: string, actionTypeId: string) => boolean; } interface ActiveActionConnectorState { @@ -81,6 +82,7 @@ export const ActionForm = ({ setHasActionsWithBrokenConnector, actionTypeRegistry, getDefaultActionParams, + isActionGroupDisabledForActionType, }: ActionAccordionFormProps) => { const { http, @@ -345,6 +347,7 @@ export const ActionForm = ({ actionGroups={actionGroups} defaultActionMessage={defaultActionMessage} defaultParams={getDefaultActionParams?.(actionItem.actionTypeId, actionItem.group)} + isActionGroupDisabledForActionType={isActionGroupDisabledForActionType} setActionGroupIdByIndex={setActionGroupIdByIndex} onAddConnector={() => { setActiveActionItem({ actionTypeId: actionItem.actionTypeId, index }); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_form.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_form.tsx index d68f66f373135..9a721b2f2bed0 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_form.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_form.tsx @@ -60,6 +60,7 @@ export type ActionTypeFormProps = { connectors: ActionConnector[]; actionTypeRegistry: ActionTypeRegistryContract; defaultParams: DefaultActionParams; + isActionGroupDisabledForActionType?: (actionGroupId: string, actionTypeId: string) => boolean; } & Pick< ActionAccordionFormProps, | 'defaultActionGroupId' @@ -94,6 +95,7 @@ export const ActionTypeForm = ({ actionGroups, setActionGroupIdByIndex, actionTypeRegistry, + isActionGroupDisabledForActionType, defaultParams, }: ActionTypeFormProps) => { const { @@ -145,6 +147,28 @@ export const ActionTypeForm = ({ const actionType = actionTypesIndex[actionItem.actionTypeId]; + const actionGroupDisplay = ( + actionGroupId: string, + actionGroupName: string, + actionTypeId: string + ): string => + isActionGroupDisabledForActionType + ? isActionGroupDisabledForActionType(actionGroupId, actionTypeId) + ? i18n.translate( + 'xpack.triggersActionsUI.sections.alertForm.addNewActionConnectorActionGroup.display', + { + defaultMessage: '{actionGroupName} (Not Currently Supported)', + values: { actionGroupName }, + } + ) + : actionGroupName + : actionGroupName; + + const isActionGroupDisabled = (actionGroupId: string, actionTypeId: string): boolean => + isActionGroupDisabledForActionType + ? isActionGroupDisabledForActionType(actionGroupId, actionTypeId) + : false; + const optionsList = connectors .filter( (connectorItem) => @@ -191,7 +215,8 @@ export const ActionTypeForm = ({ data-test-subj={`addNewActionConnectorActionGroup-${index}`} options={actionGroups.map(({ id: value, name }) => ({ value, - inputDisplay: name, + inputDisplay: actionGroupDisplay(value, name, actionItem.actionTypeId), + disabled: isActionGroupDisabled(value, actionItem.actionTypeId), 'data-test-subj': `addNewActionConnectorActionGroup-${index}-option-${value}`, }))} valueOfSelected={selectedActionGroup.id} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_menu.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_menu.tsx index 7cd95c92b22a3..3264f22bb928f 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_menu.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_menu.tsx @@ -12,6 +12,7 @@ import { loadActionTypes } from '../../lib/action_connector_api'; import { actionTypeCompare } from '../../lib/action_type_compare'; import { checkActionTypeEnabled } from '../../lib/check_action_type_enabled'; import { useKibana } from '../../../common/lib/kibana'; +import { DEFAULT_HIDDEN_ACTION_TYPES } from '../../..'; interface Props { onActionTypeChange: (actionType: ActionType) => void; @@ -35,7 +36,18 @@ export const ActionTypeMenu = ({ useEffect(() => { (async () => { try { - const availableActionTypes = actionTypes ?? (await loadActionTypes({ http })); + /** + * Hidden action types will be hidden only on Alerts & Actions. + * actionTypes prop is not filtered. Thus, any consumer that provides it's own actionTypes + * can use the hidden action types. For example, Cases or Detections of Security Solution. + * + * TODO: Remove when cases connector is available across Kibana. Issue: https://github.com/elastic/kibana/issues/82502. + * */ + const availableActionTypes = + actionTypes ?? + (await loadActionTypes({ http })).filter( + (actionType) => !DEFAULT_HIDDEN_ACTION_TYPES.includes(actionType.id) + ); const index: ActionTypeIndex = {}; for (const actionTypeItem of availableActionTypes) { index[actionTypeItem.id] = actionTypeItem; 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 fed888b40ad86..2df75436f5f96 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 @@ -39,6 +39,7 @@ import './actions_connectors_list.scss'; import { ActionConnector, ActionConnectorTableItem, ActionTypeIndex } from '../../../../types'; import { EmptyConnectorsPrompt } from '../../../components/prompts/empty_connectors_prompt'; import { useKibana } from '../../../../common/lib/kibana'; +import { DEFAULT_HIDDEN_ACTION_TYPES } from '../../../../'; export const ActionsConnectorsList: React.FunctionComponent = () => { const { @@ -94,18 +95,23 @@ export const ActionsConnectorsList: React.FunctionComponent = () => { }, []); const actionConnectorTableItems: ActionConnectorTableItem[] = actionTypesIndex - ? actions.map((action) => { - return { - ...action, - actionType: actionTypesIndex[action.actionTypeId] - ? actionTypesIndex[action.actionTypeId].name - : action.actionTypeId, - }; - }) + ? actions + // TODO: Remove when cases connector is available across Kibana. Issue: https://github.com/elastic/kibana/issues/82502. + .filter((action) => !DEFAULT_HIDDEN_ACTION_TYPES.includes(action.actionTypeId)) + .map((action) => { + return { + ...action, + actionType: actionTypesIndex[action.actionTypeId] + ? actionTypesIndex[action.actionTypeId].name + : action.actionTypeId, + }; + }) : []; const actionTypesList: Array<{ value: string; name: string }> = actionTypesIndex ? Object.values(actionTypesIndex) + // TODO: Remove when cases connector is available across Kibana. Issue: https://github.com/elastic/kibana/issues/82502. + .filter((actionType) => !DEFAULT_HIDDEN_ACTION_TYPES.includes(actionType.id)) .map((actionType) => ({ value: actionType.id, name: `${actionType.name} (${getActionsCountByActionType(actions, actionType.id)})`, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.tsx index c94086a6adab9..3a8835825acd1 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.tsx @@ -55,7 +55,12 @@ import { } from '../../../types'; import { getTimeOptions } from '../../../common/lib/get_time_options'; import { ActionForm } from '../action_connector_form'; -import { AlertActionParam, ALERTS_FEATURE_ID } from '../../../../../alerts/common'; +import { + AlertActionParam, + ALERTS_FEATURE_ID, + RecoveredActionGroup, + isActionGroupDisabledForActionTypeId, +} from '../../../../../alerts/common'; import { hasAllPrivilege, hasShowActionsCapability } from '../../lib/capabilities'; import { SolutionFilter } from './solution_filter'; import './alert_form.scss'; @@ -192,6 +197,7 @@ export const AlertForm = ({ setDefaultActionGroupId(index.get(alert.alertTypeId)!.defaultActionGroupId); } setAlertTypesIndex(index); + const availableAlertTypesResult = getAvailableAlertTypes(alertTypesResult); setAvailableAlertTypes(availableAlertTypesResult); @@ -331,6 +337,18 @@ export const AlertForm = ({ const tagsOptions = alert.tags ? alert.tags.map((label: string) => ({ label })) : []; + const isActionGroupDisabledForActionType = useCallback( + (alertType: AlertType, actionGroupId: string, actionTypeId: string): boolean => { + return isActionGroupDisabledForActionTypeId( + actionGroupId === alertType?.recoveryActionGroup?.id + ? RecoveredActionGroup.id + : actionGroupId, + actionTypeId + ); + }, + [] + ); + const AlertParamsExpressionComponent = alertTypeModel ? alertTypeModel.alertParamsExpression : null; @@ -513,6 +531,9 @@ export const AlertForm = ({ setHasActionsWithBrokenConnector={setHasActionsWithBrokenConnector} messageVariables={selectedAlertType.actionVariables} defaultActionGroupId={defaultActionGroupId} + isActionGroupDisabledForActionType={(actionGroupId: string, actionTypeId: string) => + isActionGroupDisabledForActionType(selectedAlertType, actionGroupId, actionTypeId) + } actionGroups={selectedAlertType.actionGroups.map((actionGroup) => actionGroup.id === selectedAlertType.recoveryActionGroup.id ? { diff --git a/x-pack/plugins/ui_actions_enhanced/public/drilldowns/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.test.tsx b/x-pack/plugins/ui_actions_enhanced/public/drilldowns/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.test.tsx index dab28fb03f4e0..780cb05d31d8d 100644 --- a/x-pack/plugins/ui_actions_enhanced/public/drilldowns/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.test.tsx +++ b/x-pack/plugins/ui_actions_enhanced/public/drilldowns/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.test.tsx @@ -5,7 +5,7 @@ */ import React from 'react'; -import { fireEvent, render, wait, cleanup } from '@testing-library/react'; +import { fireEvent, render, waitFor, cleanup } from '@testing-library/react'; import { createFlyoutManageDrilldowns } from './connected_flyout_manage_drilldowns'; import { mockGetTriggerInfo, @@ -50,7 +50,7 @@ test('Allows to manage drilldowns', async () => { ); // wait for initial render. It is async because resolving compatible action factories is async - await wait(() => expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible()); + await waitFor(() => expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible()); // no drilldowns in the list expect(screen.queryAllByTestId(TEST_SUBJ_DRILLDOWN_ITEM)).toHaveLength(0); @@ -87,7 +87,7 @@ test('Allows to manage drilldowns', async () => { expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible(); - await wait(() => expect(screen.queryAllByTestId(TEST_SUBJ_DRILLDOWN_ITEM)).toHaveLength(1)); + await waitFor(() => expect(screen.queryAllByTestId(TEST_SUBJ_DRILLDOWN_ITEM)).toHaveLength(1)); expect(screen.getByText(name)).toBeVisible(); const editButton = screen.getByText(/edit/i); fireEvent.click(editButton); @@ -105,14 +105,14 @@ test('Allows to manage drilldowns', async () => { fireEvent.click(screen.getByText(/save/i)); expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible(); - await wait(() => screen.getByText(newName)); + await waitFor(() => screen.getByText(newName)); // delete drilldown from edit view fireEvent.click(screen.getByText(/edit/i)); fireEvent.click(screen.getByText(/delete/i)); expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible(); - await wait(() => expect(screen.queryAllByTestId(TEST_SUBJ_DRILLDOWN_ITEM)).toHaveLength(0)); + await waitFor(() => expect(screen.queryAllByTestId(TEST_SUBJ_DRILLDOWN_ITEM)).toHaveLength(0)); }); test('Can delete multiple drilldowns', async () => { @@ -123,7 +123,7 @@ test('Can delete multiple drilldowns', async () => { /> ); // wait for initial render. It is async because resolving compatible action factories is async - await wait(() => expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible()); + await waitFor(() => expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible()); const createDrilldown = async () => { const oldCount = screen.queryAllByTestId(TEST_SUBJ_DRILLDOWN_ITEM).length; @@ -136,7 +136,7 @@ test('Can delete multiple drilldowns', async () => { target: { value: 'https://elastic.co' }, }); fireEvent.click(screen.getAllByText(/Create Drilldown/i)[1]); - await wait(() => + await waitFor(() => expect(screen.queryAllByTestId(TEST_SUBJ_DRILLDOWN_ITEM)).toHaveLength(oldCount + 1) ); }; @@ -151,7 +151,7 @@ test('Can delete multiple drilldowns', async () => { expect(screen.queryByText(/Create/i)).not.toBeInTheDocument(); fireEvent.click(screen.getByText(/Delete \(3\)/i)); - await wait(() => expect(screen.queryAllByTestId(TEST_SUBJ_DRILLDOWN_ITEM)).toHaveLength(0)); + await waitFor(() => expect(screen.queryAllByTestId(TEST_SUBJ_DRILLDOWN_ITEM)).toHaveLength(0)); }); test('Create only mode', async () => { @@ -165,7 +165,7 @@ test('Create only mode', async () => { /> ); // wait for initial render. It is async because resolving compatible action factories is async - await wait(() => expect(screen.getAllByText(/Create/i).length).toBeGreaterThan(0)); + await waitFor(() => expect(screen.getAllByText(/Create/i).length).toBeGreaterThan(0)); fireEvent.change(screen.getByLabelText(/name/i), { target: { value: 'test' }, }); @@ -175,7 +175,7 @@ test('Create only mode', async () => { }); fireEvent.click(screen.getAllByText(/Create Drilldown/i)[1]); - await wait(() => expect(toasts.addSuccess).toBeCalled()); + await waitFor(() => expect(toasts.addSuccess).toBeCalled()); expect(onClose).toBeCalled(); expect(await mockDynamicActionManager.state.get().events.length).toBe(1); }); @@ -189,7 +189,7 @@ test('After switching between action factories state is restored', async () => { /> ); // wait for initial render. It is async because resolving compatible action factories is async - await wait(() => expect(screen.getAllByText(/Create/i).length).toBeGreaterThan(0)); + await waitFor(() => expect(screen.getAllByText(/Create/i).length).toBeGreaterThan(0)); fireEvent.change(screen.getByLabelText(/name/i), { target: { value: 'test' }, }); @@ -210,7 +210,7 @@ test('After switching between action factories state is restored', async () => { expect(screen.getByLabelText(/name/i)).toHaveValue('test'); fireEvent.click(screen.getAllByText(/Create Drilldown/i)[1]); - await wait(() => expect(toasts.addSuccess).toBeCalled()); + await waitFor(() => expect(toasts.addSuccess).toBeCalled()); expect(await (mockDynamicActionManager.state.get().events[0].action.config as any).url).toBe( 'https://elastic.co' ); @@ -230,7 +230,7 @@ test("Error when can't save drilldown changes", async () => { /> ); // wait for initial render. It is async because resolving compatible action factories is async - await wait(() => expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible()); + await waitFor(() => expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible()); fireEvent.click(screen.getByText(/Create new/i)); fireEvent.change(screen.getByLabelText(/name/i), { target: { value: 'test' }, @@ -240,7 +240,7 @@ test("Error when can't save drilldown changes", async () => { target: { value: 'https://elastic.co' }, }); fireEvent.click(screen.getAllByText(/Create Drilldown/i)[1]); - await wait(() => + await waitFor(() => expect(toasts.addError).toBeCalledWith(error, { title: toastDrilldownsCRUDError }) ); }); @@ -254,7 +254,7 @@ test('Should show drilldown welcome message. Should be able to dismiss it', asyn ); // wait for initial render. It is async because resolving compatible action factories is async - await wait(() => expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible()); + await waitFor(() => expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible()); expect(screen.getByTestId(WELCOME_MESSAGE_TEST_SUBJ)).toBeVisible(); fireEvent.click(screen.getByText(/hide/i)); @@ -268,7 +268,7 @@ test('Should show drilldown welcome message. Should be able to dismiss it', asyn /> ); // wait for initial render. It is async because resolving compatible action factories is async - await wait(() => expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible()); + await waitFor(() => expect(screen.getByText(/Manage Drilldowns/i)).toBeVisible()); expect(screen.queryByTestId(WELCOME_MESSAGE_TEST_SUBJ)).toBeNull(); }); @@ -281,7 +281,7 @@ test('Drilldown type is not shown if no supported trigger', async () => { /> ); // wait for initial render. It is async because resolving compatible action factories is async - await wait(() => expect(screen.getAllByText(/Create/i).length).toBeGreaterThan(0)); + await waitFor(() => expect(screen.getAllByText(/Create/i).length).toBeGreaterThan(0)); expect(screen.queryByText(/Go to Dashboard/i)).not.toBeInTheDocument(); // dashboard action is not visible, because APPLY_FILTER_TRIGGER not supported expect(screen.getByTestId('selectedActionFactory-Url')).toBeInTheDocument(); }); @@ -295,7 +295,7 @@ test('Can pick a trigger', async () => { /> ); // wait for initial render. It is async because resolving compatible action factories is async - await wait(() => expect(screen.getAllByText(/Create/i).length).toBeGreaterThan(0)); + await waitFor(() => expect(screen.getAllByText(/Create/i).length).toBeGreaterThan(0)); // input drilldown name const name = 'Test name'; @@ -318,6 +318,6 @@ test('Can pick a trigger', async () => { expect(createButton).toBeEnabled(); fireEvent.click(createButton); - await wait(() => expect(toasts.addSuccess).toBeCalled()); + await waitFor(() => expect(toasts.addSuccess).toBeCalled()); expect(mockDynamicActionManager.state.get().events[0].triggers).toEqual(['SELECT_RANGE_TRIGGER']); }); diff --git a/x-pack/plugins/uptime/public/apps/render_app.tsx b/x-pack/plugins/uptime/public/apps/render_app.tsx index c0567ff956ce4..803431dc25b24 100644 --- a/x-pack/plugins/uptime/public/apps/render_app.tsx +++ b/x-pack/plugins/uptime/public/apps/render_app.tsx @@ -21,7 +21,7 @@ export function renderApp( core: CoreStart, plugins: ClientPluginsSetup, startPlugins: ClientPluginsStart, - { element, history }: AppMountParameters + appMountParameters: AppMountParameters ) { const { application: { capabilities }, @@ -47,7 +47,6 @@ export function renderApp( basePath: basePath.get(), darkMode: core.uiSettings.get(DEFAULT_DARK_MODE), commonlyUsedRanges: core.uiSettings.get(DEFAULT_TIMEPICKER_QUICK_RANGES), - history, isApmAvailable: apm, isInfraAvailable: infrastructure, isLogsAvailable: logs, @@ -68,12 +67,13 @@ export function renderApp( ], }), setBadge, + appMountParameters, setBreadcrumbs: core.chrome.setBreadcrumbs, }; - ReactDOM.render(, element); + ReactDOM.render(, appMountParameters.element); return () => { - ReactDOM.unmountComponentAtNode(element); + ReactDOM.unmountComponentAtNode(appMountParameters.element); }; } diff --git a/x-pack/plugins/uptime/public/apps/uptime_app.tsx b/x-pack/plugins/uptime/public/apps/uptime_app.tsx index 9bbcde041a794..061398b25e452 100644 --- a/x-pack/plugins/uptime/public/apps/uptime_app.tsx +++ b/x-pack/plugins/uptime/public/apps/uptime_app.tsx @@ -9,7 +9,7 @@ import { i18n } from '@kbn/i18n'; import React, { useEffect } from 'react'; import { Provider as ReduxProvider } from 'react-redux'; import { Router } from 'react-router-dom'; -import { I18nStart, ChromeBreadcrumb, CoreStart } from 'kibana/public'; +import { I18nStart, ChromeBreadcrumb, CoreStart, AppMountParameters } from 'kibana/public'; import { KibanaContextProvider, RedirectAppLinks, @@ -28,7 +28,7 @@ import { PageRouter } from '../routes'; import { UptimeAlertsFlyoutWrapper } from '../components/overview/alerts'; import { store } from '../state'; import { kibanaService } from '../state/kibana_service'; -import { ScopedHistory } from '../../../../../src/core/public'; +import { ActionMenu } from '../components/common/header/action_menu'; import { EuiThemeProvider } from '../../../observability/public'; export interface UptimeAppColors { @@ -47,7 +47,6 @@ export interface UptimeAppProps { canSave: boolean; core: CoreStart; darkMode: boolean; - history: ScopedHistory; i18n: I18nStart; isApmAvailable: boolean; isInfraAvailable: boolean; @@ -58,6 +57,7 @@ export interface UptimeAppProps { renderGlobalHelpControls(): void; commonlyUsedRanges: CommonlyUsedRange[]; setBreadcrumbs: (crumbs: ChromeBreadcrumb[]) => void; + appMountParameters: AppMountParameters; } const Application = (props: UptimeAppProps) => { @@ -71,6 +71,7 @@ const Application = (props: UptimeAppProps) => { renderGlobalHelpControls, setBadge, startPlugins, + appMountParameters, } = props; useEffect(() => { @@ -101,7 +102,7 @@ const Application = (props: UptimeAppProps) => { - + @@ -112,6 +113,7 @@ const Application = (props: UptimeAppProps) => {
+
diff --git a/x-pack/plugins/uptime/public/components/certificates/cert_refresh_btn.tsx b/x-pack/plugins/uptime/public/components/certificates/cert_refresh_btn.tsx new file mode 100644 index 0000000000000..d0823276f1885 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/certificates/cert_refresh_btn.tsx @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useContext } from 'react'; +import { + EuiButton, + EuiButtonEmpty, + EuiFlexGroup, + EuiFlexItem, + EuiHideFor, + EuiShowFor, +} from '@elastic/eui'; +import * as labels from '../../pages/translations'; +import { UptimeRefreshContext } from '../../contexts'; + +export const CertRefreshBtn = () => { + const { refreshApp } = useContext(UptimeRefreshContext); + + return ( + + + + + { + refreshApp(); + }} + data-test-subj="superDatePickerApplyTimeButton" + > + {labels.REFRESH_CERT} + + + + { + refreshApp(); + }} + data-test-subj="superDatePickerApplyTimeButton" + /> + + + + + ); +}; diff --git a/x-pack/plugins/uptime/public/pages/__tests__/__snapshots__/page_header.test.tsx.snap b/x-pack/plugins/uptime/public/components/common/header/__tests__/__snapshots__/page_header.test.tsx.snap similarity index 64% rename from x-pack/plugins/uptime/public/pages/__tests__/__snapshots__/page_header.test.tsx.snap rename to x-pack/plugins/uptime/public/components/common/header/__tests__/__snapshots__/page_header.test.tsx.snap index 7bb578494ab44..05a78624848c6 100644 --- a/x-pack/plugins/uptime/public/pages/__tests__/__snapshots__/page_header.test.tsx.snap +++ b/x-pack/plugins/uptime/public/components/common/header/__tests__/__snapshots__/page_header.test.tsx.snap @@ -107,97 +107,86 @@ Array [ }
-
-
- -
-
-
- -
@@ -308,7 +297,7 @@ Array [ }
, ] `; @@ -420,16 +409,91 @@ Array [ } +
+
- TestingHeading - +
+ +
+
, ] `; exports[`PageHeader shallow renders without the date picker: page_header_no_date_picker 1`] = ` Array [ -
, -
, - +
+
+
+ +
+
+
+
+
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+ + + +
+
, -
, ] `; diff --git a/x-pack/plugins/uptime/public/pages/__tests__/page_header.test.tsx b/x-pack/plugins/uptime/public/components/common/header/__tests__/page_header.test.tsx similarity index 82% rename from x-pack/plugins/uptime/public/pages/__tests__/page_header.test.tsx rename to x-pack/plugins/uptime/public/components/common/header/__tests__/page_header.test.tsx index 63d4c24f965d9..0b72cc64f8102 100644 --- a/x-pack/plugins/uptime/public/pages/__tests__/page_header.test.tsx +++ b/x-pack/plugins/uptime/public/components/common/header/__tests__/page_header.test.tsx @@ -6,13 +6,13 @@ import React from 'react'; import { PageHeader } from '../page_header'; -import { renderWithRouter, MountWithReduxProvider } from '../../lib'; +import { renderWithRouter, MountWithReduxProvider } from '../../../../lib'; describe('PageHeader', () => { it('shallow renders with the date picker', () => { const component = renderWithRouter( - + ); expect(component).toMatchSnapshot('page_header_with_date_picker'); @@ -21,7 +21,7 @@ describe('PageHeader', () => { it('shallow renders without the date picker', () => { const component = renderWithRouter( - + ); expect(component).toMatchSnapshot('page_header_no_date_picker'); @@ -30,7 +30,7 @@ describe('PageHeader', () => { it('shallow renders extra links', () => { const component = renderWithRouter( - + ); expect(component).toMatchSnapshot('page_header_with_extra_links'); diff --git a/x-pack/plugins/uptime/public/components/common/header/action_menu.tsx b/x-pack/plugins/uptime/public/components/common/header/action_menu.tsx new file mode 100644 index 0000000000000..b59470f66f796 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/common/header/action_menu.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { EuiButtonEmpty, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { useKibana } from '../../../../../../../src/plugins/kibana_react/public'; +import { HeaderMenuPortal } from '../../../../../observability/public'; +import { AppMountParameters } from '../../../../../../../src/core/public'; + +const ADD_DATA_LABEL = i18n.translate('xpack.uptime.addDataButtonLabel', { + defaultMessage: 'Add data', +}); + +export const ActionMenu = ({ appMountParameters }: { appMountParameters: AppMountParameters }) => { + const kibana = useKibana(); + + return ( + + + + + {ADD_DATA_LABEL} + + + + + ); +}; diff --git a/x-pack/plugins/uptime/public/components/common/header/page_header.tsx b/x-pack/plugins/uptime/public/components/common/header/page_header.tsx new file mode 100644 index 0000000000000..63bcb6663619d --- /dev/null +++ b/x-pack/plugins/uptime/public/components/common/header/page_header.tsx @@ -0,0 +1,65 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { EuiFlexGroup, EuiFlexItem, EuiHorizontalRule, EuiSpacer } from '@elastic/eui'; +import styled from 'styled-components'; +import { useRouteMatch } from 'react-router-dom'; +import { UptimeDatePicker } from '../uptime_date_picker'; +import { SyntheticsCallout } from '../../overview/synthetics_callout'; +import { PageTabs } from './page_tabs'; +import { CERTIFICATES_ROUTE, MONITOR_ROUTE, SETTINGS_ROUTE } from '../../../../common/constants'; +import { CertRefreshBtn } from '../../certificates/cert_refresh_btn'; +import { ToggleAlertFlyoutButton } from '../../overview/alerts/alerts_containers'; + +const StyledPicker = styled(EuiFlexItem)` + &&& { + @media only screen and (max-width: 1024px) and (min-width: 868px) { + .euiSuperDatePicker__flexWrapper { + width: 500px; + } + } + @media only screen and (max-width: 880px) { + flex-grow: 1; + .euiSuperDatePicker__flexWrapper { + width: calc(100% + 8px); + } + } + } +`; + +export const PageHeader = () => { + const isCertRoute = useRouteMatch(CERTIFICATES_ROUTE); + const isSettingsRoute = useRouteMatch(SETTINGS_ROUTE); + + const DatePickerComponent = () => + isCertRoute ? ( + + ) : ( + + + + ); + + const isMonRoute = useRouteMatch(MONITOR_ROUTE); + + return ( + <> + + + + + + + + + {!isSettingsRoute && } + + {isMonRoute && } + {!isMonRoute && } + + ); +}; diff --git a/x-pack/plugins/uptime/public/components/common/header/page_tabs.tsx b/x-pack/plugins/uptime/public/components/common/header/page_tabs.tsx new file mode 100644 index 0000000000000..68df15c52c65e --- /dev/null +++ b/x-pack/plugins/uptime/public/components/common/header/page_tabs.tsx @@ -0,0 +1,80 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useEffect, useState } from 'react'; + +import { EuiTabs, EuiTab } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { useHistory, useRouteMatch } from 'react-router-dom'; +import { CERTIFICATES_ROUTE, OVERVIEW_ROUTE, SETTINGS_ROUTE } from '../../../../common/constants'; + +const tabs = [ + { + id: OVERVIEW_ROUTE, + name: i18n.translate('xpack.uptime.overviewPage.headerText', { + defaultMessage: 'Overview', + description: `The text that will be displayed in the app's heading when the Overview page loads.`, + }), + dataTestSubj: 'uptimeSettingsToOverviewLink', + }, + { + id: CERTIFICATES_ROUTE, + name: 'Certificates', + dataTestSubj: 'uptimeCertificatesLink', + }, + { + id: SETTINGS_ROUTE, + dataTestSubj: 'settings-page-link', + name: i18n.translate('xpack.uptime.page_header.settingsLink', { + defaultMessage: 'Settings', + }), + }, +]; + +export const PageTabs = () => { + const [selectedTabId, setSelectedTabId] = useState(null); + + const history = useHistory(); + + const isOverView = useRouteMatch(OVERVIEW_ROUTE); + const isSettings = useRouteMatch(SETTINGS_ROUTE); + const isCerts = useRouteMatch(CERTIFICATES_ROUTE); + + useEffect(() => { + if (isOverView?.isExact) { + setSelectedTabId(OVERVIEW_ROUTE); + } + if (isCerts) { + setSelectedTabId(CERTIFICATES_ROUTE); + } + if (isSettings) { + setSelectedTabId(SETTINGS_ROUTE); + } + if (!isOverView?.isExact && !isCerts && !isSettings) { + setSelectedTabId(null); + } + }, [isCerts, isSettings, isOverView]); + + const renderTabs = () => { + return tabs.map(({ dataTestSubj, name, id }, index) => ( + setSelectedTabId(id)} + isSelected={id === selectedTabId} + key={index} + data-test-subj={dataTestSubj} + href={history.createHref({ pathname: id })} + > + {name} + + )); + }; + + return ( + + {renderTabs()} + + ); +}; diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/__snapshots__/monitor_list.test.tsx.snap b/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/__snapshots__/monitor_list.test.tsx.snap index 39f860f76f2bd..bd1aecc9ede48 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/__snapshots__/monitor_list.test.tsx.snap +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/__snapshots__/monitor_list.test.tsx.snap @@ -826,26 +826,20 @@ exports[`MonitorList component renders loading state 1`] = ` `; exports[`MonitorList component renders the monitor list 1`] = ` -.c3 { +.c2 { padding-right: 4px; } -.c4 { +.c3 { padding-top: 12px; } -.c1 { - position: absolute; - right: 16px; - top: 16px; -} - .c0 { position: relative; } @media (max-width:574px) { - .c2 { + .c1 { min-width: 230px; } } @@ -936,13 +930,6 @@ exports[`MonitorList component renders the monitor list 1`] = `
- - Certificates status -