diff --git a/.ci/pipeline-library/src/test/KibanaBasePipelineTest.groovy b/.ci/pipeline-library/src/test/KibanaBasePipelineTest.groovy index 086484f2385b0..4112cb3c0e14b 100644 --- a/.ci/pipeline-library/src/test/KibanaBasePipelineTest.groovy +++ b/.ci/pipeline-library/src/test/KibanaBasePipelineTest.groovy @@ -78,6 +78,10 @@ class KibanaBasePipelineTest extends BasePipelineTest { return helper.callStack.find { it.methodName == name } } + def fnMocks(String name) { + helper.callStack.findAll { it.methodName == name } + } + void mockFailureBuild() { props([ buildUtils: [ diff --git a/.ci/pipeline-library/src/test/slackNotifications.groovy b/.ci/pipeline-library/src/test/slackNotifications.groovy index 467e4a0e5f520..f7e39f5fad903 100644 --- a/.ci/pipeline-library/src/test/slackNotifications.groovy +++ b/.ci/pipeline-library/src/test/slackNotifications.groovy @@ -59,4 +59,67 @@ class SlackNotificationsTest extends KibanaBasePipelineTest { args.blocks[2].text.text.toString() ) } + + @Test + void 'sendFailedBuild() should call slackSend() with a backup message when first attempt fails'() { + mockFailureBuild() + def counter = 0 + helper.registerAllowedMethod('slackSend', [Map.class], { ++counter > 1 }) + slackNotifications.sendFailedBuild() + + def args = fnMocks('slackSend')[1].args[0] + + def expected = [ + channel: '#kibana-operations-alerts', + username: 'Kibana Operations', + iconEmoji: ':jenkins:', + color: 'danger', + message: ':broken_heart: elastic / kibana # master #1', + ] + + expected.each { + assertEquals(it.value.toString(), args[it.key].toString()) + } + + assertEquals( + ":broken_heart: **" + + "\n\nFirst attempt at sending this notification failed. Please check the build.", + args.blocks[0].text.text.toString() + ) + } + + @Test + void 'getTestFailures() should truncate list of failures to 10'() { + prop('testUtils', [ + getFailures: { + return (1..12).collect { + return [ + url: Mocks.TEST_FAILURE_URL, + fullDisplayName: "Failure #${it}", + ] + } + }, + ]) + + def message = (String) slackNotifications.getTestFailures() + + assertTrue("Message ends with truncated indicator", message.endsWith("...and 2 more")) + assertTrue("Message contains Failure #10", message.contains("Failure #10")) + assertTrue("Message does not contain Failure #11", !message.contains("Failure #11")) + } + + @Test + void 'shortenMessage() should truncate a long message, but leave parts that fit'() { + assertEquals('Hello\nHello\n[...truncated...]', slackNotifications.shortenMessage('Hello\nHello\nthis is a long string', 29)) + } + + @Test + void 'shortenMessage() should not modify a short message'() { + assertEquals('Hello world', slackNotifications.shortenMessage('Hello world', 11)) + } + + @Test + void 'shortenMessage() should truncate an entire message with only one part'() { + assertEquals('[...truncated...]', slackNotifications.shortenMessage('Hello world this is a really long message', 40)) + } } diff --git a/.eslintrc.js b/.eslintrc.js index e2674e8d7b407..c9f9d96f9ddae 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -771,19 +771,22 @@ module.exports = { }, /** - * APM overrides + * APM and Observability overrides */ { - files: ['x-pack/plugins/apm/**/*.js'], + files: [ + 'x-pack/plugins/apm/**/*.{js,mjs,ts,tsx}', + 'x-pack/plugins/observability/**/*.{js,mjs,ts,tsx}', + ], rules: { - 'no-unused-vars': ['error', { ignoreRestSiblings: true }], 'no-console': ['warn', { allow: ['error'] }], - }, - }, - { - plugins: ['react-hooks'], - files: ['x-pack/plugins/apm/**/*.{ts,tsx}'], - rules: { + 'react/function-component-definition': [ + 'warn', + { + namedComponents: 'function-declaration', + unnamedComponents: 'arrow-function', + }, + ], 'react-hooks/rules-of-hooks': 'error', // Checks rules of Hooks 'react-hooks/exhaustive-deps': ['error', { additionalHooks: '^useFetcher$' }], }, diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 2ad82ded6cb38..f1a374445657f 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -115,7 +115,6 @@ /src/dev/ @elastic/kibana-operations /src/setup_node_env/ @elastic/kibana-operations /src/optimize/ @elastic/kibana-operations -/src/es_archiver/ @elastic/kibana-operations /packages/*eslint*/ @elastic/kibana-operations /packages/*babel*/ @elastic/kibana-operations /packages/kbn-dev-utils*/ @elastic/kibana-operations @@ -124,6 +123,7 @@ /packages/kbn-pm/ @elastic/kibana-operations /packages/kbn-test/ @elastic/kibana-operations /packages/kbn-ui-shared-deps/ @elastic/kibana-operations +/packages/kbn-es-archiver/ @elastic/kibana-operations /src/legacy/server/keystore/ @elastic/kibana-operations /src/legacy/server/pid/ @elastic/kibana-operations /src/legacy/server/sass/ @elastic/kibana-operations diff --git a/Jenkinsfile b/Jenkinsfile index 69c61b5bfa988..818ba748ee165 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -43,7 +43,7 @@ kibanaPipeline(timeoutMinutes: 155, checkPrChanges: true, setCommitStatus: true) 'xpack-accessibility': kibanaPipeline.functionalTestProcess('xpack-accessibility', './test/scripts/jenkins_xpack_accessibility.sh'), 'xpack-savedObjectsFieldMetrics': kibanaPipeline.functionalTestProcess('xpack-savedObjectsFieldMetrics', './test/scripts/jenkins_xpack_saved_objects_field_metrics.sh'), 'xpack-securitySolutionCypress': { processNumber -> - whenChanged(['x-pack/plugins/security_solution/', 'x-pack/test/security_solution_cypress/']) { + whenChanged(['x-pack/plugins/security_solution/', 'x-pack/test/security_solution_cypress/', 'x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/', 'x-pack/plugins/triggers_actions_ui/public/application/context/actions_connectors_context.tsx']) { kibanaPipeline.functionalTestProcess('xpack-securitySolutionCypress', './test/scripts/jenkins_security_solution_cypress.sh')(processNumber) } }, diff --git a/docs/developer/advanced/running-elasticsearch.asciidoc b/docs/developer/advanced/running-elasticsearch.asciidoc index 2361f805c7635..e5c86fafd1ce7 100644 --- a/docs/developer/advanced/running-elasticsearch.asciidoc +++ b/docs/developer/advanced/running-elasticsearch.asciidoc @@ -13,6 +13,10 @@ This will run a snapshot of {es} that is usually built nightly. Read more about ---- yarn es snapshot ---- +By default, two users are added to Elasticsearch: + + - A superuser with username: `elastic` and password: `changeme`, which can be used to log into Kibana with. + - A user with username: `kibana_system` and password `changeme`. This account is used by the Kibana server to authenticate itself to Elasticsearch, and to perform certain actions on behalf of the end user. These credentials should be specified in your kibana.yml as described in <> See all available options, like how to specify a specific license, with the `--help` flag. @@ -115,4 +119,4 @@ PUT _cluster/settings } ---- -Follow the cross-cluster search instructions for setting up index patterns to search across clusters (<>). \ No newline at end of file +Follow the cross-cluster search instructions for setting up index patterns to search across clusters (<>). diff --git a/docs/developer/architecture/code-exploration.asciidoc b/docs/developer/architecture/code-exploration.asciidoc index 2f67ae002c916..4481dea44795c 100644 --- a/docs/developer/architecture/code-exploration.asciidoc +++ b/docs/developer/architecture/code-exploration.asciidoc @@ -186,11 +186,6 @@ WARNING: Missing README. Replaces the legacy ui/share module for registering share context menus. -- {kib-repo}blob/{branch}/src/plugins/status_page[statusPage] - -WARNING: Missing README. - - - {kib-repo}blob/{branch}/src/plugins/telemetry/README.md[telemetry] Telemetry allows Kibana features to have usage tracked in the wild. The general term "telemetry" refers to multiple things: @@ -529,9 +524,9 @@ WARNING: Missing README. See Configuring security in Kibana. -- {kib-repo}blob/{branch}/x-pack/plugins/security_solution[securitySolution] +- {kib-repo}blob/{branch}/x-pack/plugins/security_solution/README.md[securitySolution] -WARNING: Missing README. +Welcome to the Kibana Security Solution plugin! This README will go over getting started with development and testing. - {kib-repo}blob/{branch}/x-pack/plugins/snapshot_restore/README.md[snapshotRestore] diff --git a/docs/developer/contributing/development-tests.asciidoc b/docs/developer/contributing/development-tests.asciidoc index 78a2a90b69ce5..2e40f664faba9 100644 --- a/docs/developer/contributing/development-tests.asciidoc +++ b/docs/developer/contributing/development-tests.asciidoc @@ -26,8 +26,6 @@ root) |Functional |`test/*integration/**/config.js` `test/*functional/**/config.js` `test/accessibility/config.js` |`yarn test:ftr:server --config test/[directory]/config.js``yarn test:ftr:runner --config test/[directory]/config.js --grep=regexp` - -|Karma |`src/**/public/__tests__/*.js` |`yarn test:karma:debug` |=== For X-Pack tests located in `x-pack/` see diff --git a/docs/developer/contributing/development-unit-tests.asciidoc b/docs/developer/contributing/development-unit-tests.asciidoc index 8b4954150bb5b..5322106b17ac1 100644 --- a/docs/developer/contributing/development-unit-tests.asciidoc +++ b/docs/developer/contributing/development-unit-tests.asciidoc @@ -95,38 +95,6 @@ to proceed in this mode. node scripts/mocha --debug ---- -With `yarn test:karma`, you can run only the browser tests. Coverage -reports are available for browser tests by running -`yarn test:coverage`. You can find the results under the `coverage/` -directory that will be created upon completion. - -[source,bash] ----- -yarn test:karma ----- - -Using `yarn test:karma:debug` initializes an environment for debugging -the browser tests. Includes an dedicated instance of the {kib} server -for building the test bundle, and a karma server. When running this task -the build is optimized for the first time and then a karma-owned -instance of the browser is opened. Click the "`debug`" button to open a -new tab that executes the unit tests. - -[source,bash] ----- -yarn test:karma:debug ----- - -In the screenshot below, you’ll notice the URL is -`localhost:9876/debug.html`. You can append a `grep` query parameter -to this URL and set it to a string value which will be used to exclude -tests which don’t match. For example, if you changed the URL to -`localhost:9876/debug.html?query=my test` and then refreshed the -browser, you’d only see tests run which contain "`my test`" in the test -description. - -image:http://i.imgur.com/DwHxgfq.png[Browser test debugging] - [discrete] === Unit Testing Plugins @@ -141,5 +109,4 @@ command from your plugin: [source,bash] ---- yarn test:mocha -yarn test:karma:debug # remove the debug flag to run them once and close ---- \ No newline at end of file diff --git a/docs/development/core/server/kibana-plugin-core-server.countresponse._shards.md b/docs/development/core/server/kibana-plugin-core-server.countresponse._shards.md new file mode 100644 index 0000000000000..0f31a554e2208 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.countresponse._shards.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [CountResponse](./kibana-plugin-core-server.countresponse.md) > [\_shards](./kibana-plugin-core-server.countresponse._shards.md) + +## CountResponse.\_shards property + +Signature: + +```typescript +_shards: ShardsInfo; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.countresponse.count.md b/docs/development/core/server/kibana-plugin-core-server.countresponse.count.md new file mode 100644 index 0000000000000..3cd1a6aaf6644 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.countresponse.count.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [CountResponse](./kibana-plugin-core-server.countresponse.md) > [count](./kibana-plugin-core-server.countresponse.count.md) + +## CountResponse.count property + +Signature: + +```typescript +count: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.countresponse.md b/docs/development/core/server/kibana-plugin-core-server.countresponse.md new file mode 100644 index 0000000000000..f8664f4878f46 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.countresponse.md @@ -0,0 +1,20 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [CountResponse](./kibana-plugin-core-server.countresponse.md) + +## CountResponse interface + + +Signature: + +```typescript +export interface CountResponse +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [\_shards](./kibana-plugin-core-server.countresponse._shards.md) | ShardsInfo | | +| [count](./kibana-plugin-core-server.countresponse.count.md) | number | | + diff --git a/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._id.md b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._id.md new file mode 100644 index 0000000000000..ccc6a76361f26 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._id.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [DeleteDocumentResponse](./kibana-plugin-core-server.deletedocumentresponse.md) > [\_id](./kibana-plugin-core-server.deletedocumentresponse._id.md) + +## DeleteDocumentResponse.\_id property + +Signature: + +```typescript +_id: string; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._index.md b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._index.md new file mode 100644 index 0000000000000..a9a04bb2b2ed7 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._index.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [DeleteDocumentResponse](./kibana-plugin-core-server.deletedocumentresponse.md) > [\_index](./kibana-plugin-core-server.deletedocumentresponse._index.md) + +## DeleteDocumentResponse.\_index property + +Signature: + +```typescript +_index: string; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._shards.md b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._shards.md new file mode 100644 index 0000000000000..e3d5e9208db0a --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._shards.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [DeleteDocumentResponse](./kibana-plugin-core-server.deletedocumentresponse.md) > [\_shards](./kibana-plugin-core-server.deletedocumentresponse._shards.md) + +## DeleteDocumentResponse.\_shards property + +Signature: + +```typescript +_shards: ShardsResponse; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._type.md b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._type.md new file mode 100644 index 0000000000000..690852e20a76e --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._type.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [DeleteDocumentResponse](./kibana-plugin-core-server.deletedocumentresponse.md) > [\_type](./kibana-plugin-core-server.deletedocumentresponse._type.md) + +## DeleteDocumentResponse.\_type property + +Signature: + +```typescript +_type: string; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._version.md b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._version.md new file mode 100644 index 0000000000000..acfe8ef55ae71 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse._version.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [DeleteDocumentResponse](./kibana-plugin-core-server.deletedocumentresponse.md) > [\_version](./kibana-plugin-core-server.deletedocumentresponse._version.md) + +## DeleteDocumentResponse.\_version property + +Signature: + +```typescript +_version: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse.error.md b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse.error.md new file mode 100644 index 0000000000000..aafe850188998 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse.error.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [DeleteDocumentResponse](./kibana-plugin-core-server.deletedocumentresponse.md) > [error](./kibana-plugin-core-server.deletedocumentresponse.error.md) + +## DeleteDocumentResponse.error property + +Signature: + +```typescript +error?: { + type: string; + }; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse.found.md b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse.found.md new file mode 100644 index 0000000000000..00bc89bda66ed --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse.found.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [DeleteDocumentResponse](./kibana-plugin-core-server.deletedocumentresponse.md) > [found](./kibana-plugin-core-server.deletedocumentresponse.found.md) + +## DeleteDocumentResponse.found property + +Signature: + +```typescript +found: boolean; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse.md b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse.md new file mode 100644 index 0000000000000..e8ac7d2fd8ec1 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse.md @@ -0,0 +1,26 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [DeleteDocumentResponse](./kibana-plugin-core-server.deletedocumentresponse.md) + +## DeleteDocumentResponse interface + + +Signature: + +```typescript +export interface DeleteDocumentResponse +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [\_id](./kibana-plugin-core-server.deletedocumentresponse._id.md) | string | | +| [\_index](./kibana-plugin-core-server.deletedocumentresponse._index.md) | string | | +| [\_shards](./kibana-plugin-core-server.deletedocumentresponse._shards.md) | ShardsResponse | | +| [\_type](./kibana-plugin-core-server.deletedocumentresponse._type.md) | string | | +| [\_version](./kibana-plugin-core-server.deletedocumentresponse._version.md) | number | | +| [error](./kibana-plugin-core-server.deletedocumentresponse.error.md) | {
type: string;
} | | +| [found](./kibana-plugin-core-server.deletedocumentresponse.found.md) | boolean | | +| [result](./kibana-plugin-core-server.deletedocumentresponse.result.md) | string | | + diff --git a/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse.result.md b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse.result.md new file mode 100644 index 0000000000000..88f7568d3d9bc --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.deletedocumentresponse.result.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [DeleteDocumentResponse](./kibana-plugin-core-server.deletedocumentresponse.md) > [result](./kibana-plugin-core-server.deletedocumentresponse.result.md) + +## DeleteDocumentResponse.result property + +Signature: + +```typescript +result: string; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.elasticsearchclient.md b/docs/development/core/server/kibana-plugin-core-server.elasticsearchclient.md new file mode 100644 index 0000000000000..279262aa6a5ec --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.elasticsearchclient.md @@ -0,0 +1,17 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ElasticsearchClient](./kibana-plugin-core-server.elasticsearchclient.md) + +## ElasticsearchClient type + +Client used to query the elasticsearch cluster. + +Signature: + +```typescript +export declare type ElasticsearchClient = Omit & { + transport: { + request(params: TransportRequestParams, options?: TransportRequestOptions): TransportRequestPromise; + }; +}; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.explanation.description.md b/docs/development/core/server/kibana-plugin-core-server.explanation.description.md new file mode 100644 index 0000000000000..37fc90f5ac5d8 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.explanation.description.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [Explanation](./kibana-plugin-core-server.explanation.md) > [description](./kibana-plugin-core-server.explanation.description.md) + +## Explanation.description property + +Signature: + +```typescript +description: string; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.explanation.details.md b/docs/development/core/server/kibana-plugin-core-server.explanation.details.md new file mode 100644 index 0000000000000..afba9175d86cf --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.explanation.details.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [Explanation](./kibana-plugin-core-server.explanation.md) > [details](./kibana-plugin-core-server.explanation.details.md) + +## Explanation.details property + +Signature: + +```typescript +details: Explanation[]; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.explanation.md b/docs/development/core/server/kibana-plugin-core-server.explanation.md new file mode 100644 index 0000000000000..eb18910c4795b --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.explanation.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [Explanation](./kibana-plugin-core-server.explanation.md) + +## Explanation interface + + +Signature: + +```typescript +export interface Explanation +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [description](./kibana-plugin-core-server.explanation.description.md) | string | | +| [details](./kibana-plugin-core-server.explanation.details.md) | Explanation[] | | +| [value](./kibana-plugin-core-server.explanation.value.md) | number | | + diff --git a/docs/development/core/server/kibana-plugin-core-server.explanation.value.md b/docs/development/core/server/kibana-plugin-core-server.explanation.value.md new file mode 100644 index 0000000000000..b10f60176b0c8 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.explanation.value.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [Explanation](./kibana-plugin-core-server.explanation.md) > [value](./kibana-plugin-core-server.explanation.value.md) + +## Explanation.value property + +Signature: + +```typescript +value: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.getresponse._id.md b/docs/development/core/server/kibana-plugin-core-server.getresponse._id.md new file mode 100644 index 0000000000000..d31b61f3962c8 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.getresponse._id.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [GetResponse](./kibana-plugin-core-server.getresponse.md) > [\_id](./kibana-plugin-core-server.getresponse._id.md) + +## GetResponse.\_id property + +Signature: + +```typescript +_id: string; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.getresponse._index.md b/docs/development/core/server/kibana-plugin-core-server.getresponse._index.md new file mode 100644 index 0000000000000..0353ec1a17b2c --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.getresponse._index.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [GetResponse](./kibana-plugin-core-server.getresponse.md) > [\_index](./kibana-plugin-core-server.getresponse._index.md) + +## GetResponse.\_index property + +Signature: + +```typescript +_index: string; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.getresponse._primary_term.md b/docs/development/core/server/kibana-plugin-core-server.getresponse._primary_term.md new file mode 100644 index 0000000000000..8412302ab727d --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.getresponse._primary_term.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [GetResponse](./kibana-plugin-core-server.getresponse.md) > [\_primary\_term](./kibana-plugin-core-server.getresponse._primary_term.md) + +## GetResponse.\_primary\_term property + +Signature: + +```typescript +_primary_term: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.getresponse._routing.md b/docs/development/core/server/kibana-plugin-core-server.getresponse._routing.md new file mode 100644 index 0000000000000..1af3ed31ee112 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.getresponse._routing.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [GetResponse](./kibana-plugin-core-server.getresponse.md) > [\_routing](./kibana-plugin-core-server.getresponse._routing.md) + +## GetResponse.\_routing property + +Signature: + +```typescript +_routing?: string; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.getresponse._seq_no.md b/docs/development/core/server/kibana-plugin-core-server.getresponse._seq_no.md new file mode 100644 index 0000000000000..e8d72563f8149 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.getresponse._seq_no.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [GetResponse](./kibana-plugin-core-server.getresponse.md) > [\_seq\_no](./kibana-plugin-core-server.getresponse._seq_no.md) + +## GetResponse.\_seq\_no property + +Signature: + +```typescript +_seq_no: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.getresponse._source.md b/docs/development/core/server/kibana-plugin-core-server.getresponse._source.md new file mode 100644 index 0000000000000..97aacb42992a3 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.getresponse._source.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [GetResponse](./kibana-plugin-core-server.getresponse.md) > [\_source](./kibana-plugin-core-server.getresponse._source.md) + +## GetResponse.\_source property + +Signature: + +```typescript +_source: T; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.getresponse._type.md b/docs/development/core/server/kibana-plugin-core-server.getresponse._type.md new file mode 100644 index 0000000000000..b3205e2fe91d7 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.getresponse._type.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [GetResponse](./kibana-plugin-core-server.getresponse.md) > [\_type](./kibana-plugin-core-server.getresponse._type.md) + +## GetResponse.\_type property + +Signature: + +```typescript +_type: string; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.getresponse._version.md b/docs/development/core/server/kibana-plugin-core-server.getresponse._version.md new file mode 100644 index 0000000000000..23d3a8c91f4a2 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.getresponse._version.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [GetResponse](./kibana-plugin-core-server.getresponse.md) > [\_version](./kibana-plugin-core-server.getresponse._version.md) + +## GetResponse.\_version property + +Signature: + +```typescript +_version: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.getresponse.found.md b/docs/development/core/server/kibana-plugin-core-server.getresponse.found.md new file mode 100644 index 0000000000000..8d34a3e743cca --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.getresponse.found.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [GetResponse](./kibana-plugin-core-server.getresponse.md) > [found](./kibana-plugin-core-server.getresponse.found.md) + +## GetResponse.found property + +Signature: + +```typescript +found: boolean; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.getresponse.md b/docs/development/core/server/kibana-plugin-core-server.getresponse.md new file mode 100644 index 0000000000000..bab3092c6b1fa --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.getresponse.md @@ -0,0 +1,27 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [GetResponse](./kibana-plugin-core-server.getresponse.md) + +## GetResponse interface + + +Signature: + +```typescript +export interface GetResponse +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [\_id](./kibana-plugin-core-server.getresponse._id.md) | string | | +| [\_index](./kibana-plugin-core-server.getresponse._index.md) | string | | +| [\_primary\_term](./kibana-plugin-core-server.getresponse._primary_term.md) | number | | +| [\_routing](./kibana-plugin-core-server.getresponse._routing.md) | string | | +| [\_seq\_no](./kibana-plugin-core-server.getresponse._seq_no.md) | number | | +| [\_source](./kibana-plugin-core-server.getresponse._source.md) | T | | +| [\_type](./kibana-plugin-core-server.getresponse._type.md) | string | | +| [\_version](./kibana-plugin-core-server.getresponse._version.md) | number | | +| [found](./kibana-plugin-core-server.getresponse.found.md) | boolean | | + diff --git a/docs/development/core/server/kibana-plugin-core-server.md b/docs/development/core/server/kibana-plugin-core-server.md index 61ffc532f0de5..95b7627398b45 100644 --- a/docs/development/core/server/kibana-plugin-core-server.md +++ b/docs/development/core/server/kibana-plugin-core-server.md @@ -74,7 +74,9 @@ The plugin integrates with the core system via lifecycle events: `setup` | [CoreSetup](./kibana-plugin-core-server.coresetup.md) | Context passed to the plugins setup method. | | [CoreStart](./kibana-plugin-core-server.corestart.md) | Context passed to the plugins start method. | | [CoreStatus](./kibana-plugin-core-server.corestatus.md) | Status of core services. | +| [CountResponse](./kibana-plugin-core-server.countresponse.md) | | | [CustomHttpResponseOptions](./kibana-plugin-core-server.customhttpresponseoptions.md) | HTTP response parameters for a response with adjustable status code. | +| [DeleteDocumentResponse](./kibana-plugin-core-server.deletedocumentresponse.md) | | | [DeprecationAPIClientParams](./kibana-plugin-core-server.deprecationapiclientparams.md) | | | [DeprecationAPIResponse](./kibana-plugin-core-server.deprecationapiresponse.md) | | | [DeprecationInfo](./kibana-plugin-core-server.deprecationinfo.md) | | @@ -85,7 +87,9 @@ The plugin integrates with the core system via lifecycle events: `setup` | [ElasticsearchStatusMeta](./kibana-plugin-core-server.elasticsearchstatusmeta.md) | | | [EnvironmentMode](./kibana-plugin-core-server.environmentmode.md) | | | [ErrorHttpResponseOptions](./kibana-plugin-core-server.errorhttpresponseoptions.md) | HTTP response parameters | +| [Explanation](./kibana-plugin-core-server.explanation.md) | | | [FakeRequest](./kibana-plugin-core-server.fakerequest.md) | Fake request object created manually by Kibana plugins. | +| [GetResponse](./kibana-plugin-core-server.getresponse.md) | | | [HttpAuth](./kibana-plugin-core-server.httpauth.md) | | | [HttpResources](./kibana-plugin-core-server.httpresources.md) | HttpResources service is responsible for serving static & dynamic assets for Kibana application via HTTP. Provides API allowing plug-ins to respond with: - a pre-configured HTML page bootstrapping Kibana client app - custom HTML page - custom JS script file. | | [HttpResourcesRenderOptions](./kibana-plugin-core-server.httpresourcesrenderoptions.md) | Allows to configure HTTP response parameters | @@ -189,11 +193,14 @@ The plugin integrates with the core system via lifecycle events: `setup` | [SavedObjectsTypeMappingDefinition](./kibana-plugin-core-server.savedobjectstypemappingdefinition.md) | Describe a saved object type mapping. | | [SavedObjectsUpdateOptions](./kibana-plugin-core-server.savedobjectsupdateoptions.md) | | | [SavedObjectsUpdateResponse](./kibana-plugin-core-server.savedobjectsupdateresponse.md) | | +| [SearchResponse](./kibana-plugin-core-server.searchresponse.md) | | | [ServiceStatus](./kibana-plugin-core-server.servicestatus.md) | The current status of a service at a point in time. | | [SessionCookieValidationResult](./kibana-plugin-core-server.sessioncookievalidationresult.md) | Return type from a function to validate cookie contents. | | [SessionStorage](./kibana-plugin-core-server.sessionstorage.md) | Provides an interface to store and retrieve data across requests. | | [SessionStorageCookieOptions](./kibana-plugin-core-server.sessionstoragecookieoptions.md) | Configuration used to create HTTP session storage based on top of cookie mechanism. | | [SessionStorageFactory](./kibana-plugin-core-server.sessionstoragefactory.md) | SessionStorage factory to bind one to an incoming request | +| [ShardsInfo](./kibana-plugin-core-server.shardsinfo.md) | | +| [ShardsResponse](./kibana-plugin-core-server.shardsresponse.md) | | | [StatusServiceSetup](./kibana-plugin-core-server.statusservicesetup.md) | API for accessing status of Core and this plugin's dependencies as well as for customizing this plugin's status. | | [StringValidationRegex](./kibana-plugin-core-server.stringvalidationregex.md) | StringValidation with regex object | | [StringValidationRegexString](./kibana-plugin-core-server.stringvalidationregexstring.md) | StringValidation as regex string | @@ -228,6 +235,7 @@ The plugin integrates with the core system via lifecycle events: `setup` | [ConfigDeprecationProvider](./kibana-plugin-core-server.configdeprecationprovider.md) | A provider that should returns a list of [ConfigDeprecation](./kibana-plugin-core-server.configdeprecation.md).See [ConfigDeprecationFactory](./kibana-plugin-core-server.configdeprecationfactory.md) for more usage examples. | | [ConfigPath](./kibana-plugin-core-server.configpath.md) | | | [DestructiveRouteMethod](./kibana-plugin-core-server.destructiveroutemethod.md) | Set of HTTP methods changing the state of the server. | +| [ElasticsearchClient](./kibana-plugin-core-server.elasticsearchclient.md) | Client used to query the elasticsearch cluster. | | [Freezable](./kibana-plugin-core-server.freezable.md) | | | [GetAuthHeaders](./kibana-plugin-core-server.getauthheaders.md) | Get headers to authenticate a user against Elasticsearch. | | [GetAuthState](./kibana-plugin-core-server.getauthstate.md) | Gets authentication state for a request. Returned by auth interceptor. | diff --git a/docs/development/core/server/kibana-plugin-core-server.routeconfigoptions.md b/docs/development/core/server/kibana-plugin-core-server.routeconfigoptions.md index 5a6103dfc57d4..fee6124f8d866 100644 --- a/docs/development/core/server/kibana-plugin-core-server.routeconfigoptions.md +++ b/docs/development/core/server/kibana-plugin-core-server.routeconfigoptions.md @@ -19,5 +19,6 @@ export interface RouteConfigOptions | [authRequired](./kibana-plugin-core-server.routeconfigoptions.authrequired.md) | boolean | 'optional' | Defines authentication mode for a route: - true. A user has to have valid credentials to access a resource - false. A user can access a resource without any credentials. - 'optional'. A user can access a resource if has valid credentials or no credentials at all. Can be useful when we grant access to a resource but want to identify a user if possible.Defaults to true if an auth mechanism is registered. | | [body](./kibana-plugin-core-server.routeconfigoptions.body.md) | Method extends 'get' | 'options' ? undefined : RouteConfigOptionsBody | Additional body options [RouteConfigOptionsBody](./kibana-plugin-core-server.routeconfigoptionsbody.md). | | [tags](./kibana-plugin-core-server.routeconfigoptions.tags.md) | readonly string[] | Additional metadata tag strings to attach to the route. | +| [timeout](./kibana-plugin-core-server.routeconfigoptions.timeout.md) | number | Timeouts for processing durations. Response timeout is in milliseconds. Default value: 2 minutes | | [xsrfRequired](./kibana-plugin-core-server.routeconfigoptions.xsrfrequired.md) | Method extends 'get' ? never : boolean | Defines xsrf protection requirements for a route: - true. Requires an incoming POST/PUT/DELETE request to contain kbn-xsrf header. - false. Disables xsrf protection.Set to true by default | diff --git a/docs/development/core/server/kibana-plugin-core-server.routeconfigoptions.timeout.md b/docs/development/core/server/kibana-plugin-core-server.routeconfigoptions.timeout.md new file mode 100644 index 0000000000000..479fcf883ec4d --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.routeconfigoptions.timeout.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [RouteConfigOptions](./kibana-plugin-core-server.routeconfigoptions.md) > [timeout](./kibana-plugin-core-server.routeconfigoptions.timeout.md) + +## RouteConfigOptions.timeout property + +Timeouts for processing durations. Response timeout is in milliseconds. Default value: 2 minutes + +Signature: + +```typescript +timeout?: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsdeletebynamespaceoptions.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsdeletebynamespaceoptions.md index 3fac0d889c6ce..ba81a3e8c32d0 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectsdeletebynamespaceoptions.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsdeletebynamespaceoptions.md @@ -15,5 +15,5 @@ export interface SavedObjectsDeleteByNamespaceOptions extends SavedObjectsBaseOp | Property | Type | Description | | --- | --- | --- | -| [refresh](./kibana-plugin-core-server.savedobjectsdeletebynamespaceoptions.refresh.md) | MutatingOperationRefreshSetting | The Elasticsearch Refresh setting for this operation | +| [refresh](./kibana-plugin-core-server.savedobjectsdeletebynamespaceoptions.refresh.md) | boolean | The Elasticsearch supports only boolean flag for this operation | diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsdeletebynamespaceoptions.refresh.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsdeletebynamespaceoptions.refresh.md index c67866a5553a0..52b562e8e22b7 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectsdeletebynamespaceoptions.refresh.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsdeletebynamespaceoptions.refresh.md @@ -4,10 +4,10 @@ ## SavedObjectsDeleteByNamespaceOptions.refresh property -The Elasticsearch Refresh setting for this operation +The Elasticsearch supports only boolean flag for this operation Signature: ```typescript -refresh?: MutatingOperationRefreshSetting; +refresh?: boolean; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.searchresponse._scroll_id.md b/docs/development/core/server/kibana-plugin-core-server.searchresponse._scroll_id.md new file mode 100644 index 0000000000000..a9dd0e76475fd --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.searchresponse._scroll_id.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SearchResponse](./kibana-plugin-core-server.searchresponse.md) > [\_scroll\_id](./kibana-plugin-core-server.searchresponse._scroll_id.md) + +## SearchResponse.\_scroll\_id property + +Signature: + +```typescript +_scroll_id?: string; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.searchresponse._shards.md b/docs/development/core/server/kibana-plugin-core-server.searchresponse._shards.md new file mode 100644 index 0000000000000..e090ad20e8bc8 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.searchresponse._shards.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SearchResponse](./kibana-plugin-core-server.searchresponse.md) > [\_shards](./kibana-plugin-core-server.searchresponse._shards.md) + +## SearchResponse.\_shards property + +Signature: + +```typescript +_shards: ShardsResponse; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.searchresponse.aggregations.md b/docs/development/core/server/kibana-plugin-core-server.searchresponse.aggregations.md new file mode 100644 index 0000000000000..686e6f2aa05e9 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.searchresponse.aggregations.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SearchResponse](./kibana-plugin-core-server.searchresponse.md) > [aggregations](./kibana-plugin-core-server.searchresponse.aggregations.md) + +## SearchResponse.aggregations property + +Signature: + +```typescript +aggregations?: any; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.searchresponse.hits.md b/docs/development/core/server/kibana-plugin-core-server.searchresponse.hits.md new file mode 100644 index 0000000000000..1629e77425525 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.searchresponse.hits.md @@ -0,0 +1,28 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SearchResponse](./kibana-plugin-core-server.searchresponse.md) > [hits](./kibana-plugin-core-server.searchresponse.hits.md) + +## SearchResponse.hits property + +Signature: + +```typescript +hits: { + total: number; + max_score: number; + hits: Array<{ + _index: string; + _type: string; + _id: string; + _score: number; + _source: T; + _version?: number; + _explanation?: Explanation; + fields?: any; + highlight?: any; + inner_hits?: any; + matched_queries?: string[]; + sort?: string[]; + }>; + }; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.searchresponse.md b/docs/development/core/server/kibana-plugin-core-server.searchresponse.md new file mode 100644 index 0000000000000..b53cbf0d87f24 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.searchresponse.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SearchResponse](./kibana-plugin-core-server.searchresponse.md) + +## SearchResponse interface + + +Signature: + +```typescript +export interface SearchResponse +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [\_scroll\_id](./kibana-plugin-core-server.searchresponse._scroll_id.md) | string | | +| [\_shards](./kibana-plugin-core-server.searchresponse._shards.md) | ShardsResponse | | +| [aggregations](./kibana-plugin-core-server.searchresponse.aggregations.md) | any | | +| [hits](./kibana-plugin-core-server.searchresponse.hits.md) | {
total: number;
max_score: number;
hits: Array<{
_index: string;
_type: string;
_id: string;
_score: number;
_source: T;
_version?: number;
_explanation?: Explanation;
fields?: any;
highlight?: any;
inner_hits?: any;
matched_queries?: string[];
sort?: string[];
}>;
} | | +| [timed\_out](./kibana-plugin-core-server.searchresponse.timed_out.md) | boolean | | +| [took](./kibana-plugin-core-server.searchresponse.took.md) | number | | + diff --git a/docs/development/core/server/kibana-plugin-core-server.searchresponse.timed_out.md b/docs/development/core/server/kibana-plugin-core-server.searchresponse.timed_out.md new file mode 100644 index 0000000000000..a3488117cd874 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.searchresponse.timed_out.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SearchResponse](./kibana-plugin-core-server.searchresponse.md) > [timed\_out](./kibana-plugin-core-server.searchresponse.timed_out.md) + +## SearchResponse.timed\_out property + +Signature: + +```typescript +timed_out: boolean; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.searchresponse.took.md b/docs/development/core/server/kibana-plugin-core-server.searchresponse.took.md new file mode 100644 index 0000000000000..8c9c0b0f7c420 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.searchresponse.took.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SearchResponse](./kibana-plugin-core-server.searchresponse.md) > [took](./kibana-plugin-core-server.searchresponse.took.md) + +## SearchResponse.took property + +Signature: + +```typescript +took: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.shardsinfo.failed.md b/docs/development/core/server/kibana-plugin-core-server.shardsinfo.failed.md new file mode 100644 index 0000000000000..a47fc1263be41 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.shardsinfo.failed.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ShardsInfo](./kibana-plugin-core-server.shardsinfo.md) > [failed](./kibana-plugin-core-server.shardsinfo.failed.md) + +## ShardsInfo.failed property + +Signature: + +```typescript +failed: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.shardsinfo.md b/docs/development/core/server/kibana-plugin-core-server.shardsinfo.md new file mode 100644 index 0000000000000..9eafe3792c14a --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.shardsinfo.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ShardsInfo](./kibana-plugin-core-server.shardsinfo.md) + +## ShardsInfo interface + + +Signature: + +```typescript +export interface ShardsInfo +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [failed](./kibana-plugin-core-server.shardsinfo.failed.md) | number | | +| [skipped](./kibana-plugin-core-server.shardsinfo.skipped.md) | number | | +| [successful](./kibana-plugin-core-server.shardsinfo.successful.md) | number | | +| [total](./kibana-plugin-core-server.shardsinfo.total.md) | number | | + diff --git a/docs/development/core/server/kibana-plugin-core-server.shardsinfo.skipped.md b/docs/development/core/server/kibana-plugin-core-server.shardsinfo.skipped.md new file mode 100644 index 0000000000000..0c87831edd6ca --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.shardsinfo.skipped.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ShardsInfo](./kibana-plugin-core-server.shardsinfo.md) > [skipped](./kibana-plugin-core-server.shardsinfo.skipped.md) + +## ShardsInfo.skipped property + +Signature: + +```typescript +skipped: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.shardsinfo.successful.md b/docs/development/core/server/kibana-plugin-core-server.shardsinfo.successful.md new file mode 100644 index 0000000000000..c927adb39932a --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.shardsinfo.successful.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ShardsInfo](./kibana-plugin-core-server.shardsinfo.md) > [successful](./kibana-plugin-core-server.shardsinfo.successful.md) + +## ShardsInfo.successful property + +Signature: + +```typescript +successful: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.shardsinfo.total.md b/docs/development/core/server/kibana-plugin-core-server.shardsinfo.total.md new file mode 100644 index 0000000000000..820c8a70fd222 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.shardsinfo.total.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ShardsInfo](./kibana-plugin-core-server.shardsinfo.md) > [total](./kibana-plugin-core-server.shardsinfo.total.md) + +## ShardsInfo.total property + +Signature: + +```typescript +total: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.shardsresponse.failed.md b/docs/development/core/server/kibana-plugin-core-server.shardsresponse.failed.md new file mode 100644 index 0000000000000..7f7a173af2e58 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.shardsresponse.failed.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ShardsResponse](./kibana-plugin-core-server.shardsresponse.md) > [failed](./kibana-plugin-core-server.shardsresponse.failed.md) + +## ShardsResponse.failed property + +Signature: + +```typescript +failed: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.shardsresponse.md b/docs/development/core/server/kibana-plugin-core-server.shardsresponse.md new file mode 100644 index 0000000000000..722ffd8efdb57 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.shardsresponse.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ShardsResponse](./kibana-plugin-core-server.shardsresponse.md) + +## ShardsResponse interface + + +Signature: + +```typescript +export interface ShardsResponse +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [failed](./kibana-plugin-core-server.shardsresponse.failed.md) | number | | +| [skipped](./kibana-plugin-core-server.shardsresponse.skipped.md) | number | | +| [successful](./kibana-plugin-core-server.shardsresponse.successful.md) | number | | +| [total](./kibana-plugin-core-server.shardsresponse.total.md) | number | | + diff --git a/docs/development/core/server/kibana-plugin-core-server.shardsresponse.skipped.md b/docs/development/core/server/kibana-plugin-core-server.shardsresponse.skipped.md new file mode 100644 index 0000000000000..b01c3501fe022 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.shardsresponse.skipped.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ShardsResponse](./kibana-plugin-core-server.shardsresponse.md) > [skipped](./kibana-plugin-core-server.shardsresponse.skipped.md) + +## ShardsResponse.skipped property + +Signature: + +```typescript +skipped: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.shardsresponse.successful.md b/docs/development/core/server/kibana-plugin-core-server.shardsresponse.successful.md new file mode 100644 index 0000000000000..23c6ff0519ed7 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.shardsresponse.successful.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ShardsResponse](./kibana-plugin-core-server.shardsresponse.md) > [successful](./kibana-plugin-core-server.shardsresponse.successful.md) + +## ShardsResponse.successful property + +Signature: + +```typescript +successful: number; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.shardsresponse.total.md b/docs/development/core/server/kibana-plugin-core-server.shardsresponse.total.md new file mode 100644 index 0000000000000..e669f6216a10f --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.shardsresponse.total.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ShardsResponse](./kibana-plugin-core-server.shardsresponse.md) > [total](./kibana-plugin-core-server.shardsresponse.total.md) + +## ShardsResponse.total property + +Signature: + +```typescript +total: number; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.connecttoquerystate.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.connecttoquerystate.md index a6731e5ef8de1..7c937b39cda87 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.connecttoquerystate.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.connecttoquerystate.md @@ -9,9 +9,10 @@ Helper to setup two-way syncing of global data and a state container Signature: ```typescript -connectToQueryState: ({ timefilter: { timefilter }, filterManager, state$, }: Pick, stateContainer: BaseStateContainer, syncConfig: { +connectToQueryState: ({ timefilter: { timefilter }, filterManager, queryString, state$, }: Pick, stateContainer: BaseStateContainer, syncConfig: { time?: boolean; refreshInterval?: boolean; filters?: FilterStateStore | boolean; + query?: boolean; }) => () => void ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.esfilters.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.esfilters.md index 37142cf1794c3..bc34d4113f847 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.esfilters.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.esfilters.md @@ -52,5 +52,6 @@ esFilters: { convertRangeFilterToTimeRangeString: typeof convertRangeFilterToTimeRangeString; mapAndFlattenFilters: (filters: import("../common").Filter[]) => import("../common").Filter[]; extractTimeFilter: typeof extractTimeFilter; + extractTimeRange: typeof extractTimeRange; } ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystate.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystate.md index cc489a0cb0367..021d808afecb5 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystate.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystate.md @@ -17,6 +17,7 @@ export interface QueryState | Property | Type | Description | | --- | --- | --- | | [filters](./kibana-plugin-plugins-data-public.querystate.filters.md) | Filter[] | | +| [query](./kibana-plugin-plugins-data-public.querystate.query.md) | Query | | | [refreshInterval](./kibana-plugin-plugins-data-public.querystate.refreshinterval.md) | RefreshInterval | | | [time](./kibana-plugin-plugins-data-public.querystate.time.md) | TimeRange | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystate.query.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystate.query.md new file mode 100644 index 0000000000000..b0ac376a358dc --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystate.query.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [QueryState](./kibana-plugin-plugins-data-public.querystate.md) > [query](./kibana-plugin-plugins-data-public.querystate.query.md) + +## QueryState.query property + +Signature: + +```typescript +query?: Query; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.syncquerystatewithurl.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.syncquerystatewithurl.md index f6f8bed8cb914..1aafa022f9690 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.syncquerystatewithurl.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.syncquerystatewithurl.md @@ -9,7 +9,7 @@ Helper to setup syncing of global data with the URL Signature: ```typescript -syncQueryStateWithUrl: (query: Pick, kbnUrlStateStorage: IKbnUrlStateStorage) => { +syncQueryStateWithUrl: (query: Pick, kbnUrlStateStorage: IKbnUrlStateStorage) => { stop: () => void; hasInheritedQueryFromUrl: boolean; } diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.isearchsetup.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.isearchsetup.md index 3afba80064f08..d9749bc44f45a 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.isearchsetup.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.isearchsetup.md @@ -14,6 +14,6 @@ export interface ISearchSetup | Property | Type | Description | | --- | --- | --- | -| [registerSearchStrategy](./kibana-plugin-plugins-data-server.isearchsetup.registersearchstrategy.md) | TRegisterSearchStrategy | Extension point exposed for other plugins to register their own search strategies. | +| [registerSearchStrategy](./kibana-plugin-plugins-data-server.isearchsetup.registersearchstrategy.md) | (name: string, strategy: ISearchStrategy) => void | Extension point exposed for other plugins to register their own search strategies. | | [usage](./kibana-plugin-plugins-data-server.isearchsetup.usage.md) | SearchUsage | Used internally for telemetry | diff --git a/docs/management/alerting/alerts-and-actions-intro.asciidoc b/docs/management/alerting/alerts-and-actions-intro.asciidoc index efc6a670af3e9..429d7915cc1c3 100644 --- a/docs/management/alerting/alerts-and-actions-intro.asciidoc +++ b/docs/management/alerting/alerts-and-actions-intro.asciidoc @@ -4,9 +4,10 @@ beta[] -The *Alerts and Actions* UI lets you <> in a space, and provides tools to <> so that alerts can trigger actions like notification, indexing, and ticketing. +The *Alerts and Actions* UI lets you <> in a space, and provides tools to <> so that alerts can trigger actions like notification, indexing, and ticketing. -To manage alerting and connectors, open the menu, then go to *Stack Management > {kib} > Alerts and Actions*. +To manage alerting and connectors, open the menu, +then go to *Stack Management > Alerts and Insights > Alerts and Actions*. [role="screenshot"] image:management/alerting/images/alerts-and-actions-ui.png[Example alert listing in the Alerts and Actions UI] @@ -14,12 +15,12 @@ image:management/alerting/images/alerts-and-actions-ui.png[Example alert listing [NOTE] ============================================================================ Similar to dashboards, alerts and connectors reside in a <>. -The *Alerts and Actions* UI only shows alerts and connectors for the current space. +The *Alerts and Actions* UI only shows alerts and connectors for the current space. ============================================================================ [NOTE] ============================================================================ {es} also offers alerting capabilities through Watcher, which -can be managed through the <>. See +can be managed through the <>. See <> for more information. -============================================================================ \ No newline at end of file +============================================================================ diff --git a/docs/management/index-lifecycle-policies/add-policy-to-index.asciidoc b/docs/management/index-lifecycle-policies/add-policy-to-index.asciidoc index eb014a5165048..0fec62d895754 100644 --- a/docs/management/index-lifecycle-policies/add-policy-to-index.asciidoc +++ b/docs/management/index-lifecycle-policies/add-policy-to-index.asciidoc @@ -2,17 +2,16 @@ [[adding-policy-to-index]] === Adding a policy to an index -To add a lifecycle policy to an index and view the status for indices -managed by a policy, open the menu, then go to *Stack Management > {es} > Index Management*. This page lists your -{es} indices, which you can filter by lifecycle status and lifecycle phase. +To add a lifecycle policy to an index and view the status for indices +managed by a policy, open the menu, then go to *Stack Management > Data > Index Management*. +This page lists your +{es} indices, which you can filter by lifecycle status and lifecycle phase. To add a policy, select the index name and then select *Manage Index > Add lifecycle policy*. -You’ll see the policy name, the phase the index is in, the current -action, and if any errors occurred performing that action. +You’ll see the policy name, the phase the index is in, the current +action, and if any errors occurred performing that action. To remove a policy from an index, select *Manage Index > Remove lifecycle policy*. [role="screenshot"] image::images/index_management_add_policy.png[][UI for adding a policy to an index] - - diff --git a/docs/management/index-lifecycle-policies/example-index-lifecycle-policy.asciidoc b/docs/management/index-lifecycle-policies/example-index-lifecycle-policy.asciidoc index 69e74d6538e4f..0097bf8c648f0 100644 --- a/docs/management/index-lifecycle-policies/example-index-lifecycle-policy.asciidoc +++ b/docs/management/index-lifecycle-policies/example-index-lifecycle-policy.asciidoc @@ -3,7 +3,7 @@ [[example-using-index-lifecycle-policy]] === Tutorial: Use {ilm-init} to manage {filebeat} time-based indices -With {ilm} ({ilm-init}), you can create policies that perform actions automatically +With {ilm} ({ilm-init}), you can create policies that perform actions automatically on indices as they age and grow. {ilm-init} policies help you to manage performance, resilience, and retention of your data during its lifecycle. This tutorial shows you how to use {kib}’s *Index Lifecycle Policies* to modify and create {ilm-init} @@ -59,7 +59,7 @@ output as described in {filebeat-ref}/filebeat-getting-started.html[Getting Star {filebeat} includes a default {ilm-init} policy that enables rollover. {ilm-init} is enabled automatically if you’re using the default `filebeat.yml` and index template. -To view the default policy in {kib}, open the menu, go to * Stack Management > {es} > Index Lifecycle Policies*, +To view the default policy in {kib}, open the menu, go to *Stack Management > Data > Index Lifecycle Policies*, search for _filebeat_, and choose the _filebeat-version_ policy. This policy initiates the rollover action when the index size reaches 50GB or @@ -114,7 +114,7 @@ If meeting a specific retention time period is most important, you can create a custom policy. For this option, you will use {filebeat} daily indices without rollover. -. To create a custom policy, open the menu, go to *Stack Management > {es} > Index Lifecycle Policies*, then click +. To create a custom policy, open the menu, go to *Stack Management > Data > Index Lifecycle Policies*, then click *Create policy*. . Activate the warm phase and configure it as follows: @@ -156,7 +156,7 @@ image::images/tutorial-ilm-custom-policy.png["Modify the custom policy to add a [role="screenshot"] image::images/tutorial-ilm-delete-phase-creation.png["Delete phase"] -. To configure the index to use the new policy, open the menu, then go to *Stack Management > {es} > Index Lifecycle +. To configure the index to use the new policy, open the menu, then go to *Stack Management > Data > Index Lifecycle Policies*. .. Find your {ilm-init} policy. diff --git a/docs/management/ingest-pipelines/ingest-pipelines.asciidoc b/docs/management/ingest-pipelines/ingest-pipelines.asciidoc index 8c259dae256d4..da2d3b8accac2 100644 --- a/docs/management/ingest-pipelines/ingest-pipelines.asciidoc +++ b/docs/management/ingest-pipelines/ingest-pipelines.asciidoc @@ -7,7 +7,7 @@ pipelines that perform common transformations and enrichments on your data. For example, you might remove a field, rename an existing field, or set a new field. -You’ll find *Ingest Node Pipelines* in *Management > Elasticsearch*. With this feature, you can: +You’ll find *Ingest Node Pipelines* in *Stack Management > Ingest*. With this feature, you can: * View a list of your pipelines and drill down into details. * Create a pipeline that defines a series of tasks, known as processors. @@ -23,7 +23,7 @@ image:management/ingest-pipelines/images/ingest-pipeline-list.png["Ingest node p The minimum required permissions to access *Ingest Node Pipelines* are the `manage_pipeline` and `cluster:monitor/nodes/info` cluster privileges. -You can add these privileges in *Management > Security > Roles*. +You can add these privileges in *Stack Management > Security > Roles*. [role="screenshot"] image:management/ingest-pipelines/images/ingest-pipeline-privileges.png["Privileges required for Ingest Node Pipelines"] diff --git a/docs/management/managing-beats.asciidoc b/docs/management/managing-beats.asciidoc index d5a9c52feae23..678e160b99af0 100644 --- a/docs/management/managing-beats.asciidoc +++ b/docs/management/managing-beats.asciidoc @@ -4,7 +4,8 @@ include::{asciidoc-dir}/../../shared/discontinued.asciidoc[tag=cm-discontinued] -To use the Central Management UI, open the menu, go to *Stack Management > {beats} > Central Management*, then define and +To use {beats} Central Management UI, open the menu, go to *Stack Management > Ingest > +{beats} Central Management*, then define and manage configurations in a central location in {kib} and quickly deploy configuration changes to all {beats} running across your enterprise. For more about central management, see the related {beats} documentation: @@ -17,8 +18,8 @@ about central management, see the related {beats} documentation: This feature requires an Elastic license that includes {beats} central management. -Don't have a license? You can start a 30-day trial. Open the menu, go to -*Stack Management > Elasticsearch > License Management*. At the end of the trial +Don't have a license? You can start a 30-day trial. Open the menu, +go to *Stack Management > Stack > License Management*. At the end of the trial period, you can purchase a subscription to keep using central management. For more information, see https://www.elastic.co/subscriptions and <>. diff --git a/docs/management/managing-ccr.asciidoc b/docs/management/managing-ccr.asciidoc index 2df9addf74919..67193b3b5a037 100644 --- a/docs/management/managing-ccr.asciidoc +++ b/docs/management/managing-ccr.asciidoc @@ -7,7 +7,7 @@ remote clusters on a local cluster. {ref}/xpack-ccr.html[Cross-cluster replicati is commonly used to provide remote backups for disaster recovery and for geo-proximite copies of data. -To get started, open the menu, then go to *Stack Management > Elasticsearch > Cross-Cluster Replication*. +To get started, open the menu, then go to *Stack Management > Data > Cross-Cluster Replication*. [role="screenshot"] image::images/cross-cluster-replication-list-view.png[][Cross-cluster replication list view] diff --git a/docs/management/managing-indices.asciidoc b/docs/management/managing-indices.asciidoc index 4fc4ac1d37429..24cd094c877c6 100644 --- a/docs/management/managing-indices.asciidoc +++ b/docs/management/managing-indices.asciidoc @@ -13,7 +13,7 @@ the amount of bookkeeping when working with indices. Instead of manually setting up your indices, you can create them automatically from a template, ensuring that your settings, mappings, and aliases are consistently defined. -To manage your indices, open the menu, then go to *Stack Management > {es} > Index Management*. +To manage your indices, open the menu, then go to *Stack Management > Data > Index Management*. [role="screenshot"] image::images/management_index_labels.png[Index Management UI] @@ -130,17 +130,17 @@ Alternatively, you can click the *Load JSON* link and define the mapping as JSON [source,js] ---------------------------------- -{ +{ "properties": { "geo": { - "properties": { - "coordinates": { - "type": "geo_point" - } - } - } - } -} + "properties": { + "coordinates": { + "type": "geo_point" + } + } + } + } +} ---------------------------------- You can create additional mapping configurations in the *Dynamic templates* and diff --git a/docs/management/managing-licenses.asciidoc b/docs/management/managing-licenses.asciidoc index 99cfd12eeade9..25ae29036f656 100644 --- a/docs/management/managing-licenses.asciidoc +++ b/docs/management/managing-licenses.asciidoc @@ -7,7 +7,7 @@ with no expiration date. For the full list of features, refer to If you want to try out the full set of features, you can activate a free 30-day trial. To view the status of your license, start a trial, or install a new -license, open the menu, then go to *Stack Management > {es} > License Management*. +license, open the menu, then go to *Stack Management > Stack > License Management*. NOTE: You can start a trial only if your cluster has not already activated a trial license for the current major product version. For example, if you have diff --git a/docs/management/managing-remote-clusters.asciidoc b/docs/management/managing-remote-clusters.asciidoc index 8ccd27b65aed6..83895838efec6 100644 --- a/docs/management/managing-remote-clusters.asciidoc +++ b/docs/management/managing-remote-clusters.asciidoc @@ -6,7 +6,7 @@ connection from your cluster to other clusters. This functionality is required for {ref}/xpack-ccr.html[cross-cluster replication] and {ref}/modules-cross-cluster-search.html[cross-cluster search]. -To get started, open the menu, then go to *Stack Management > {es} > Remote Clusters*. +To get started, open the menu, then go to *Stack Management > Data > Remote Clusters*. [role="screenshot"] image::images/remote-clusters-list-view.png[Remote Clusters list view, including Add a remote cluster button] diff --git a/docs/management/rollups/create_and_manage_rollups.asciidoc b/docs/management/rollups/create_and_manage_rollups.asciidoc index bbdc382d04b38..831b536f8c1cb 100644 --- a/docs/management/rollups/create_and_manage_rollups.asciidoc +++ b/docs/management/rollups/create_and_manage_rollups.asciidoc @@ -8,7 +8,7 @@ by an index pattern, and then rolls it into a new index. Rollup indices are a go compactly store months or years of historical data for use in visualizations and reports. -To get started, open the menu, then go to *Stack Management > {es} > Rollup Jobs*. With this UI, +To get started, open the menu, then go to *Stack Management > Data > Rollup Jobs*. With this UI, you can: * <> @@ -130,8 +130,9 @@ Your next step is to visualize your rolled up data in a vertical bar chart. Most visualizations support rolled up data, with the exception of Timelion and Vega visualizations. -. Create the rollup index pattern in *Management > Index Patterns* so you can -select your rolled up data for visualizations. Click *Create index pattern*, and select *Rollup index pattern* from the dropdown. +. Go to *Stack Management > {kib} > Index Patterns*. + +. Click *Create index pattern*, and select *Rollup index pattern* from the dropdown. + [role="screenshot"] image::images/management-rollup-index-pattern.png[][Create rollup index pattern] @@ -144,7 +145,9 @@ is `rollup_logstash,kibana_sample_data_logs`. In this index pattern, `rollup_log matches the rolled up index pattern and `kibana_sample_data_logs` matches the index pattern for raw data. -. Go to *Visualize* and create a vertical bar chart. Choose `rollup_logstash,kibana_sample_data_logs` +. Go to *Visualize* and create a vertical bar chart. + +. Choose `rollup_logstash,kibana_sample_data_logs` as your source to see both the raw and rolled up data. + [role="screenshot"] diff --git a/docs/management/snapshot-restore/index.asciidoc b/docs/management/snapshot-restore/index.asciidoc index a64b74069f978..1bf62522e245c 100644 --- a/docs/management/snapshot-restore/index.asciidoc +++ b/docs/management/snapshot-restore/index.asciidoc @@ -8,7 +8,7 @@ Snapshots are important because they provide a copy of your data in case something goes wrong. If you need to roll back to an older version of your data, you can restore a snapshot from the repository. -To get started, open the menu, then go to *Stack Management > {es} > Snapshot and Restore*. +To get started, open the menu, then go to *Stack Management > Data > Snapshot and Restore*. With this UI, you can: * Register a repository for storing your snapshots @@ -191,7 +191,7 @@ your master and data nodes. You can do this in one of two ways: Use *Snapshot and Restore* to register the repository where your snapshots will live. -. Open the menu, then go to *Stack Management > {es} > Snapshot and Restore*. +. Open the menu, then go to *Stack Management > Data > Snapshot and Restore*. . Click *Register a repository* in either the introductory message or *Repository view*. . Enter a name for your repository, for example, `my_backup`. . Select *Shared file system*. diff --git a/docs/management/upgrade-assistant/index.asciidoc b/docs/management/upgrade-assistant/index.asciidoc index ab6d0790ffa3f..c5fd6a3a555a1 100644 --- a/docs/management/upgrade-assistant/index.asciidoc +++ b/docs/management/upgrade-assistant/index.asciidoc @@ -2,50 +2,50 @@ [[upgrade-assistant]] == Upgrade Assistant -The Upgrade Assistant helps you prepare for your upgrade to the next major {es} version. -For example, if you are using 6.8, the Upgrade Assistant helps you to upgrade to 7.0. -To access the assistant, open the menu, then go to *Stack Management > {es} > Upgrade Assistant*. +The Upgrade Assistant helps you prepare for your upgrade to the next major {es} version. +For example, if you are using 6.8, the Upgrade Assistant helps you to upgrade to 7.0. +To access the assistant, open the menu, then go to *Stack Management > Stack > Upgrade Assistant*. -The assistant identifies the deprecated settings in your cluster and indices -and guides you through the process of resolving issues, including reindexing. +The assistant identifies the deprecated settings in your cluster and indices +and guides you through the process of resolving issues, including reindexing. -Before you upgrade, make sure that you are using the latest released minor -version of {es} to see the most up-to-date deprecation issues. +Before you upgrade, make sure that you are using the latest released minor +version of {es} to see the most up-to-date deprecation issues. For example, if you want to upgrade to to 7.0, make sure that you are using 6.8. [float] === Reindexing -The *Indices* page lists the indices that are incompatible with the next +The *Indices* page lists the indices that are incompatible with the next major version of {es}. You can initiate a reindex to resolve the issues. [role="screenshot"] image::images/management-upgrade-assistant-9.0.png[] -For a preview of how the data will change during the reindex, select the -index name. A warning appears if the index requires destructive changes. -Back up your index, then proceed with the reindex by accepting each breaking change. +For a preview of how the data will change during the reindex, select the +index name. A warning appears if the index requires destructive changes. +Back up your index, then proceed with the reindex by accepting each breaking change. -You can follow the progress as the Upgrade Assistant makes the index read-only, -creates a new index, reindexes the documents, and creates an alias that points -from the old index to the new one. +You can follow the progress as the Upgrade Assistant makes the index read-only, +creates a new index, reindexes the documents, and creates an alias that points +from the old index to the new one. -If the reindexing fails or is cancelled, the changes are rolled back, the -new index is deleted, and the original index becomes writable. An error +If the reindexing fails or is cancelled, the changes are rolled back, the +new index is deleted, and the original index becomes writable. An error message explains the reason for the failure. -You can reindex multiple indices at a time, but keep an eye on the -{es} metrics, including CPU usage, memory pressure, and disk usage. If a -metric is so high it affects query performance, cancel the reindex and +You can reindex multiple indices at a time, but keep an eye on the +{es} metrics, including CPU usage, memory pressure, and disk usage. If a +metric is so high it affects query performance, cancel the reindex and continue by reindexing fewer indices at a time. Additional considerations: * If you use {alert-features}, when you reindex the internal indices -(`.watches`), the {watcher} process pauses and no alerts are triggered. +(`.watches`), the {watcher} process pauses and no alerts are triggered. * If you use {ml-features}, when you reindex the internal indices (`.ml-state`), -the {ml} jobs pause and models are not trained or updated. +the {ml} jobs pause and models are not trained or updated. * If you use {security-features}, before you reindex the internal indices (`.security*`), it is a good idea to create a temporary superuser account in the diff --git a/docs/management/watcher-ui/index.asciidoc b/docs/management/watcher-ui/index.asciidoc index fa3e0cce04fff..fbe5fcd5cd3a5 100644 --- a/docs/management/watcher-ui/index.asciidoc +++ b/docs/management/watcher-ui/index.asciidoc @@ -8,7 +8,8 @@ Watches are helpful for analyzing mission-critical and business-critical streaming data. For example, you might watch application logs for performance outages or audit access logs for security threats. -To get started with the Watcher UI, open then menu, then go to *Stack Management > {es} > Watcher*. +To get started with the Watcher UI, open then menu, +then go to *Stack Management > Alerts and Insights > Watcher*. With this UI, you can: * <> @@ -238,6 +239,3 @@ Refer to these examples for creating an advanced watch: * {ref}/watch-cluster-status.html[Watch the status of an {es} cluster] * {ref}/watching-meetup-data.html[Watch event data] - - - diff --git a/docs/maps/trouble-shooting.asciidoc b/docs/maps/trouble-shooting.asciidoc index cfc47cf6f0e4f..1c53fbd55ea4b 100644 --- a/docs/maps/trouble-shooting.asciidoc +++ b/docs/maps/trouble-shooting.asciidoc @@ -20,6 +20,20 @@ image::maps/images/inspector.png[] [float] === Solutions to common problems +[float] +==== Index not listed when adding layer + +* Verify your geospatial data is correctly mapped as {ref}/geo-point.html[geo_point] or {ref}/geo-shape.html[geo_shape]. + ** Run `GET myIndexPatternTitle/_field_caps?fields=myGeoFieldName` in <>, replacing `myIndexPatternTitle` and `myGeoFieldName` with your index pattern title and geospatial field name. + ** Ensure response specifies `type` as `geo_point` or `geo_shape`. +* Verify your geospatial data is correctly mapped in your <>. + ** Open your index pattern in <>. + ** Ensure your geospatial field type is `geo_point` or `geo_shape`. + ** Ensure your geospatial field is searchable and aggregatable. + ** If your geospatial field type does not match your Elasticsearch mapping, click the *Refresh* button to refresh the field list from Elasticsearch. +* Index patterns with thousands of fields can exceed the default maximum payload size. +Increase <> for large index patterns. + [float] ==== Features are not displayed diff --git a/docs/settings/reporting-settings.asciidoc b/docs/settings/reporting-settings.asciidoc index c83cd068eff5b..b31ae76d28052 100644 --- a/docs/settings/reporting-settings.asciidoc +++ b/docs/settings/reporting-settings.asciidoc @@ -21,7 +21,7 @@ You can configure `xpack.reporting` settings in your `kibana.yml` to: | Set to `false` to disable the {report-features}. | `xpack.reporting.encryptionKey` - | Set to any text string. By default, {kib} will generate a random key when it + | Set to an alphanumeric, at least 32 characters long text string. By default, {kib} will generate a random key when it starts, which will cause pending reports to fail after restart. Configure this setting to preserve the same key across multiple restarts and multiple instances of {kib}. diff --git a/docs/setup/production.asciidoc b/docs/setup/production.asciidoc index afb4b37df6a28..23dbb3346b7ef 100644 --- a/docs/setup/production.asciidoc +++ b/docs/setup/production.asciidoc @@ -167,7 +167,7 @@ These can be used to automatically update the list of hosts as a cluster is resi Kibana has a default maximum memory limit of 1.4 GB, and in most cases, we recommend leaving this unconfigured. In some scenarios, such as large reporting jobs, it may make sense to tweak limits to meet more specific requirements. -You can modify this limit by setting `--max-old-space-size` in the `node.options` config file that can be found inside `kibana/config` folder or any other configured with the environment variable `KIBANA_PATH_CONF` (for example in debian based system would be `/etc/kibana`). +You can modify this limit by setting `--max-old-space-size` in the `node.options` config file that can be found inside `kibana/config` folder or any other configured with the environment variable `KBN_PATH_CONF` (for example in debian based system would be `/etc/kibana`). The option accepts a limit in MB: -------- diff --git a/docs/spaces/index.asciidoc b/docs/spaces/index.asciidoc index bbc213dc2050e..9e505b8bfe045 100644 --- a/docs/spaces/index.asciidoc +++ b/docs/spaces/index.asciidoc @@ -116,7 +116,8 @@ interface. You can create a custom experience for users by configuring the {kib} landing page on a per-space basis. The landing page can route users to a specific dashboard, application, or saved object as they enter each space. -To configure the landing page, use the default route setting in < Advanced settings>>. +To configure the landing page, use the default route setting in +< {kib} > Advanced settings>>. For example, you might set the default route to `/app/kibana#/dashboards`. [role="screenshot"] diff --git a/docs/user/introduction.asciidoc b/docs/user/introduction.asciidoc index 6438098ad2c60..ff936fb4d5569 100644 --- a/docs/user/introduction.asciidoc +++ b/docs/user/introduction.asciidoc @@ -4,9 +4,9 @@ What is Kibana? ++++ -**_Explore and visualize your data and manage all things Elastic Stack._** +**_Visualize and analyze your data and manage all things Elastic Stack._** -Whether you’re a user or admin, {kib} makes your data actionable by providing +Whether you’re an analyst or an admin, {kib} makes your data actionable by providing three key functions. Kibana is: * **An open-source analytics and visualization platform.** @@ -24,20 +24,20 @@ image::images/intro-kibana.png[] [float] [[get-data-into-kibana]] -=== Getting data into {kib} +=== Add data {kib} is designed to use {es} as a data source. Think of Elasticsearch as the engine that stores and processes the data, with {kib} sitting on top. -From the home page, {kib} provides these options for getting data in: +From the home page, {kib} provides these options for adding data: +* Import data using the +https://www.elastic.co/blog/importing-csv-and-log-data-into-elasticsearch-with-file-data-visualizer[File Data visualizer]. * Set up a data flow to Elasticsearch using our built-in tutorials. -(If a tutorial doesn’t exist for your data, go to the +If a tutorial doesn’t exist for your data, go to the {beats-ref}/beats-reference.html[Beats overview] to learn about other data shippers -in the {beats} family.) +in the {beats} family. * <> and take {kib} for a test drive without loading data yourself. -* Import static data using the -https://www.elastic.co/blog/importing-csv-and-log-data-into-elasticsearch-with-file-data-visualizer[file upload feature]. * Index your data into Elasticsearch with {ref}/getting-started-index.html[REST APIs] or https://www.elastic.co/guide/en/elasticsearch/client/index.html[client libraries]. + @@ -47,9 +47,9 @@ image::images/intro-data-tutorial.png[Ways to get data in from the home page] {kib} uses an <> to tell it which {es} indices to explore. -If you add sample data or run a built-in tutorial, you get an index pattern for free, +If you add upload a file, run a built-in tutorial, or add sample data, you get an index pattern for free, and are good to start exploring. If you load your own data, you can create -an index pattern in <>. +an index pattern in <>. [float] [[explore-and-query]] @@ -84,14 +84,14 @@ image::images/intro-dashboard.png[] {kib} also offers these visualization features: * <> allows you to display your data in -line charts, bar graphs, pie charts, histograms, and tables -(just to name a few). It's also home to Lens, the drag-and-drop interface. +charts, graphs, and tables +(just to name a few). It's also home to Lens. Visualize supports the ability to add interactive -controls to your dashboard, and filter dashboard content in real time. +controls to your dashboard, filter dashboard content in real time, and add your own images and logos for your brand. * <> gives you the ability to present your data in a visually compelling, pixel-perfect report. Give your data the “wow” factor -needed to impress your CEO or to captivate people with a big-screen display. +needed to impress your CEO or to captivate coworkers with a big-screen display. * <> enables you to ask (and answer) meaningful questions of your location-based data. Maps supports multiple @@ -99,7 +99,7 @@ layers and data sources, mapping of individual geo points and shapes, and dynamic client-side styling. * <> allows you to combine -an infinite number of aggregations to display complex data in a meaningful way. +an infinite number of aggregations to display complex data. With TSVB, you can analyze multiple index patterns and customize every aspect of your visualization. Choose your own date format and color gradients, and easily switch your data view between time series, metric, @@ -129,7 +129,7 @@ dashboards in one space, but full access to all of Kibana’s features in anothe [[manage-all-things-stack]] === Manage all things Elastic Stack -<> provides guided processes for managing all +<> provides guided processes for managing all things Elastic Stack — indices, clusters, licenses, UI settings, index patterns, and more. Want to update your {es} indices? Set user roles and privileges? Turn on dark mode? Kibana has UIs for all that. @@ -162,4 +162,5 @@ You can also <> — no code, no addi infrastructure required. Our <> and in-product guidance can -help you get up and running, faster. Use our Help menu if you have questions or feedback. +help you get up and running, faster. Click the help icon image:images/intro-help-icon.png[] +in the top navigation bar for help with questions or to provide feedback. diff --git a/docs/user/introduction/images/intro-data-tutorial.png b/docs/user/introduction/images/intro-data-tutorial.png index fd469919593af..2882a092fbb0b 100644 Binary files a/docs/user/introduction/images/intro-data-tutorial.png and b/docs/user/introduction/images/intro-data-tutorial.png differ diff --git a/docs/user/introduction/images/intro-help-icon.png b/docs/user/introduction/images/intro-help-icon.png new file mode 100644 index 0000000000000..7766434b8e364 Binary files /dev/null and b/docs/user/introduction/images/intro-help-icon.png differ diff --git a/docs/user/introduction/images/intro-kibana.png b/docs/user/introduction/images/intro-kibana.png index 1a59230f2f166..62c2c99826131 100644 Binary files a/docs/user/introduction/images/intro-kibana.png and b/docs/user/introduction/images/intro-kibana.png differ diff --git a/docs/user/introduction/images/intro-management.png b/docs/user/introduction/images/intro-management.png index 4f32bfa80c3fd..539deab2e3f34 100644 Binary files a/docs/user/introduction/images/intro-management.png and b/docs/user/introduction/images/intro-management.png differ diff --git a/docs/user/reporting/configuring-reporting.asciidoc b/docs/user/reporting/configuring-reporting.asciidoc index ca2d79bb2dec0..6a0c44cf4c2a4 100644 --- a/docs/user/reporting/configuring-reporting.asciidoc +++ b/docs/user/reporting/configuring-reporting.asciidoc @@ -23,7 +23,7 @@ reporting job metadata. To set a static encryption key for reporting, set the `xpack.reporting.encryptionKey` property in the `kibana.yml` -configuration file. You can use any text string as the encryption key. +configuration file. You can use any alphanumeric, at least 32 characters long text string as the encryption key. [source,yaml] -------------------------------------------------------------------------------- diff --git a/docs/user/reporting/index.asciidoc b/docs/user/reporting/index.asciidoc index e4e4b461ac2bd..4f4d59315fafa 100644 --- a/docs/user/reporting/index.asciidoc +++ b/docs/user/reporting/index.asciidoc @@ -94,7 +94,7 @@ image::user/reporting/images/preserve-layout-switch.png["Share"] [[manage-report-history]] == View and manage report history -For a list of your reports, open the menu, then go to *Stack Management > {kib} > Reporting*. +For a list of your reports, open the menu, then go to *Stack Management > Alerts and Insights > Reporting*. From this view, you can monitor the generation of a report and download reports that you previously generated. diff --git a/docs/user/security/rbac_tutorial.asciidoc b/docs/user/security/rbac_tutorial.asciidoc index d7299f814b43c..3a4b2202201e2 100644 --- a/docs/user/security/rbac_tutorial.asciidoc +++ b/docs/user/security/rbac_tutorial.asciidoc @@ -90,7 +90,7 @@ image::security/images/role-space-visualization.png["Associate space"] [float] ==== Create the developer user account with the proper roles -. Open the menu, then go to *Stack Management > Users*. +. Open the menu, then go to *Stack Management > Security > Users*. . Click **Create user**, then give the user the `dev-mortgage` and `monitoring-user` roles, which are required for *Stack Monitoring* users. diff --git a/examples/alerting_example/kibana.json b/examples/alerting_example/kibana.json index 6c04218ca45e2..a2691c5fdcab7 100644 --- a/examples/alerting_example/kibana.json +++ b/examples/alerting_example/kibana.json @@ -4,6 +4,6 @@ "kibanaVersion": "kibana", "server": true, "ui": true, - "requiredPlugins": ["triggers_actions_ui", "charts", "data", "alerts", "actions", "developerExamples"], + "requiredPlugins": ["triggers_actions_ui", "charts", "data", "alerts", "actions", "features", "developerExamples"], "optionalPlugins": [] } diff --git a/examples/alerting_example/server/plugin.ts b/examples/alerting_example/server/plugin.ts index cdb005feca35c..e74cad28f77f4 100644 --- a/examples/alerting_example/server/plugin.ts +++ b/examples/alerting_example/server/plugin.ts @@ -18,20 +18,65 @@ */ import { Plugin, CoreSetup } from 'kibana/server'; +import { i18n } from '@kbn/i18n'; import { PluginSetupContract as AlertingSetup } from '../../../x-pack/plugins/alerts/server'; +import { PluginSetupContract as FeaturesPluginSetup } from '../../../x-pack/plugins/features/server'; import { alertType as alwaysFiringAlert } from './alert_types/always_firing'; import { alertType as peopleInSpaceAlert } from './alert_types/astros'; +import { INDEX_THRESHOLD_ID } from '../../../x-pack/plugins/alerting_builtins/server'; +import { ALERTING_EXAMPLE_APP_ID } from '../common/constants'; // this plugin's dependendencies export interface AlertingExampleDeps { alerts: AlertingSetup; + features: FeaturesPluginSetup; } export class AlertingExamplePlugin implements Plugin { - public setup(core: CoreSetup, { alerts }: AlertingExampleDeps) { + public setup(core: CoreSetup, { alerts, features }: AlertingExampleDeps) { alerts.registerType(alwaysFiringAlert); alerts.registerType(peopleInSpaceAlert); + + features.registerFeature({ + id: ALERTING_EXAMPLE_APP_ID, + name: i18n.translate('alertsExample.featureRegistry.alertsExampleFeatureName', { + defaultMessage: 'Alerts Example', + }), + app: [], + management: { + insightsAndAlerting: ['triggersActions'], + }, + alerting: [alwaysFiringAlert.id, peopleInSpaceAlert.id, INDEX_THRESHOLD_ID], + privileges: { + all: { + alerting: { + all: [alwaysFiringAlert.id, peopleInSpaceAlert.id, INDEX_THRESHOLD_ID], + }, + savedObject: { + all: [], + read: [], + }, + management: { + insightsAndAlerting: ['triggersActions'], + }, + ui: [], + }, + read: { + alerting: { + read: [alwaysFiringAlert.id, peopleInSpaceAlert.id, INDEX_THRESHOLD_ID], + }, + savedObject: { + all: [], + read: [], + }, + management: { + insightsAndAlerting: ['triggersActions'], + }, + ui: [], + }, + }, + }); } public start() {} diff --git a/examples/state_containers_examples/public/with_data_services/components/app.tsx b/examples/state_containers_examples/public/with_data_services/components/app.tsx index 04bdb53efa502..d007cfd97edca 100644 --- a/examples/state_containers_examples/public/with_data_services/components/app.tsx +++ b/examples/state_containers_examples/public/with_data_services/components/app.tsx @@ -17,7 +17,7 @@ * under the License. */ -import React, { useEffect, useRef, useState, useCallback } from 'react'; +import React, { useEffect, useRef, useState } from 'react'; import { History } from 'history'; import { FormattedMessage, I18nProvider } from '@kbn/i18n/react'; import { Router } from 'react-router-dom'; @@ -85,16 +85,9 @@ const App = ({ navigation, data, history, kbnUrlStateStorage }: StateDemoAppDeps useGlobalStateSyncing(data.query, kbnUrlStateStorage); useAppStateSyncing(appStateContainer, data.query, kbnUrlStateStorage); - const onQuerySubmit = useCallback( - ({ query }) => { - appStateContainer.set({ ...appState, query }); - }, - [appStateContainer, appState] - ); - const indexPattern = useIndexPattern(data); if (!indexPattern) - return
No index pattern found. Please create an intex patter before loading...
; + return
No index pattern found. Please create an index patter before loading...
; // Render the application DOM. // Note that `navigation.ui.TopNavMenu` is a stateful component exported on the `navigation` plugin's start contract. @@ -107,8 +100,6 @@ const App = ({ navigation, data, history, kbnUrlStateStorage }: StateDemoAppDeps showSearchBar={true} indexPatterns={[indexPattern]} useDefaultBehaviors={true} - onQuerySubmit={onQuerySubmit} - query={appState.query} showSaveQuery={true} /> @@ -200,7 +191,7 @@ function useAppStateSyncing( const stopSyncingQueryAppStateWithStateContainer = connectToQueryState( query, appStateContainer, - { filters: esFilters.FilterStateStore.APP_STATE } + { filters: esFilters.FilterStateStore.APP_STATE, query: true } ); // sets up syncing app state container with url diff --git a/package.json b/package.json index 2f3f95854df04..51a41cbbab9ff 100644 --- a/package.json +++ b/package.json @@ -41,8 +41,6 @@ "kbn": "node scripts/kbn", "es": "node scripts/es", "test": "grunt test", - "test:karma": "grunt test:karma", - "test:karma:debug": "grunt test:karmaDebug", "test:jest": "node scripts/jest", "test:jest_integration": "node scripts/jest_integration", "test:mocha": "node scripts/mocha", @@ -300,6 +298,7 @@ "@elastic/makelogs": "^6.0.0", "@kbn/dev-utils": "1.0.0", "@kbn/es": "1.0.0", + "@kbn/es-archiver": "1.0.0", "@kbn/eslint-import-resolver-kibana": "2.0.0", "@kbn/eslint-plugin-eslint": "1.0.0", "@kbn/expect": "1.0.0", @@ -316,6 +315,7 @@ "@types/accept": "3.1.1", "@types/angular": "^1.6.56", "@types/angular-mocks": "^1.7.0", + "@types/archiver": "^3.1.0", "@types/babel__core": "^7.1.2", "@types/bluebird": "^3.1.1", "@types/boom": "^7.2.0", @@ -397,6 +397,7 @@ "@types/testing-library__react-hooks": "^3.1.0", "@types/type-detect": "^4.0.1", "@types/uuid": "^3.4.4", + "@types/vinyl": "^2.0.4", "@types/vinyl-fs": "^2.4.11", "@types/zen-observable": "^0.8.0", "@typescript-eslint/eslint-plugin": "^2.34.0", @@ -432,7 +433,7 @@ "eslint-plugin-node": "^11.0.0", "eslint-plugin-prefer-object-spread": "^1.2.1", "eslint-plugin-prettier": "^3.1.3", - "eslint-plugin-react": "^7.17.0", + "eslint-plugin-react": "^7.20.3", "eslint-plugin-react-hooks": "^4.0.4", "eslint-plugin-react-perf": "^3.2.3", "exit-hook": "^2.2.0", @@ -444,7 +445,6 @@ "grunt-available-tasks": "^0.6.3", "grunt-cli": "^1.2.0", "grunt-contrib-watch": "^1.1.0", - "grunt-karma": "^3.0.2", "grunt-peg": "^2.0.1", "grunt-run": "0.8.1", "gulp-babel": "^8.0.0", @@ -460,19 +460,12 @@ "jest-cli": "^25.5.4", "jest-environment-jsdom-thirteen": "^1.0.1", "jest-raw-loader": "^1.0.1", - "jimp": "^0.9.6", + "jimp": "^0.14.0", "json5": "^1.0.1", - "karma": "5.0.2", - "karma-chrome-launcher": "2.2.0", - "karma-coverage": "1.1.2", - "karma-firefox-launcher": "1.1.0", - "karma-ie-launcher": "1.0.0", - "karma-junit-reporter": "1.2.0", - "karma-mocha": "2.0.0", - "karma-safari-launcher": "1.0.0", "license-checker": "^16.0.0", "listr": "^0.14.1", "load-grunt-config": "^3.0.1", + "load-json-file": "^6.2.0", "mocha": "^7.1.1", "mock-fs": "^4.12.0", "mock-http-server": "1.3.0", diff --git a/packages/kbn-dev-utils/package.json b/packages/kbn-dev-utils/package.json index b307bd41bb4dd..83a7a7607816c 100644 --- a/packages/kbn-dev-utils/package.json +++ b/packages/kbn-dev-utils/package.json @@ -20,6 +20,7 @@ "normalize-path": "^3.0.0", "moment": "^2.24.0", "rxjs": "^6.5.5", + "strip-ansi": "^6.0.0", "tree-kill": "^1.2.2", "tslib": "^2.0.0" }, diff --git a/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts b/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts index b38a27fdc1b48..b0378ab6c5cd5 100644 --- a/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts +++ b/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts @@ -29,6 +29,8 @@ interface Config { buildId: string; } +export type CiStatsMetrics = Array<{ group: string; id: string; value: number }>; + function parseConfig(log: ToolingLog) { const configJson = process.env.KIBANA_CI_STATS_CONFIG; if (!configJson) { @@ -84,7 +86,7 @@ export class CiStatsReporter { return !!this.config; } - async metrics(metrics: Array<{ group: string; id: string; value: number }>) { + async metrics(metrics: CiStatsMetrics) { if (!this.config) { return; } diff --git a/packages/kbn-dev-utils/src/index.ts b/packages/kbn-dev-utils/src/index.ts index 582526f939e42..798746d159f60 100644 --- a/packages/kbn-dev-utils/src/index.ts +++ b/packages/kbn-dev-utils/src/index.ts @@ -19,7 +19,7 @@ export { withProcRunner, ProcRunner } from './proc_runner'; export * from './tooling_log'; -export { createAbsolutePathSerializer } from './serializers'; +export * from './serializers'; export { CA_CERT_PATH, ES_KEY_PATH, diff --git a/packages/kbn-dev-utils/src/run/run_with_commands.test.ts b/packages/kbn-dev-utils/src/run/run_with_commands.test.ts index eb7708998751c..f6759b218bf32 100644 --- a/packages/kbn-dev-utils/src/run/run_with_commands.test.ts +++ b/packages/kbn-dev-utils/src/run/run_with_commands.test.ts @@ -61,9 +61,7 @@ it('extends the context using extendContext()', async () => { expect(context.flags).toMatchInlineSnapshot(` Object { - "_": Array [ - "foo", - ], + "_": Array [], "debug": false, "help": false, "quiet": false, diff --git a/packages/kbn-dev-utils/src/run/run_with_commands.ts b/packages/kbn-dev-utils/src/run/run_with_commands.ts index 9fb069e4b2d35..ca56a17b545a7 100644 --- a/packages/kbn-dev-utils/src/run/run_with_commands.ts +++ b/packages/kbn-dev-utils/src/run/run_with_commands.ts @@ -91,6 +91,13 @@ export class RunWithCommands { const commandFlagOptions = mergeFlagOptions(this.options.globalFlags, command.flags); const commandFlags = getFlags(process.argv.slice(2), commandFlagOptions); + // strip command name plus "help" if we're actually executing the fake "help" command + if (isHelpCommand) { + commandFlags._.splice(0, 2); + } else { + commandFlags._.splice(0, 1); + } + const commandHelp = getCommandLevelHelp({ usage: this.options.usage, globalFlagHelp: this.options.globalFlags?.help, @@ -115,7 +122,7 @@ export class RunWithCommands { log, flags: commandFlags, procRunner, - addCleanupTask: cleanup.add, + addCleanupTask: cleanup.add.bind(cleanup), }; const extendedContext = { diff --git a/packages/kbn-dev-utils/src/serializers/absolute_path_serializer.ts b/packages/kbn-dev-utils/src/serializers/absolute_path_serializer.ts index af55622c76198..884614c8b9551 100644 --- a/packages/kbn-dev-utils/src/serializers/absolute_path_serializer.ts +++ b/packages/kbn-dev-utils/src/serializers/absolute_path_serializer.ts @@ -21,7 +21,7 @@ import { REPO_ROOT } from '../repo_root'; export function createAbsolutePathSerializer(rootPath: string = REPO_ROOT) { return { - serialize: (value: string) => value.replace(rootPath, '').replace(/\\/g, '/'), test: (value: any) => typeof value === 'string' && value.startsWith(rootPath), + serialize: (value: string) => value.replace(rootPath, '').replace(/\\/g, '/'), }; } diff --git a/src/legacy/core_plugins/apm_oss/index.d.ts b/packages/kbn-dev-utils/src/serializers/any_instance_serizlizer.ts similarity index 81% rename from src/legacy/core_plugins/apm_oss/index.d.ts rename to packages/kbn-dev-utils/src/serializers/any_instance_serizlizer.ts index 86fe4e0350dce..c5cc095e9ee82 100644 --- a/src/legacy/core_plugins/apm_oss/index.d.ts +++ b/packages/kbn-dev-utils/src/serializers/any_instance_serizlizer.ts @@ -17,6 +17,9 @@ * under the License. */ -export interface ApmOssPlugin { - indexPatterns: string[]; +export function createAnyInstanceSerializer(Class: Function, name?: string) { + return { + test: (v: any) => v instanceof Class, + serialize: () => `<${name ?? Class.name}>`, + }; } diff --git a/packages/kbn-dev-utils/src/serializers/index.ts b/packages/kbn-dev-utils/src/serializers/index.ts index 3b49e243058df..e645a3be3fe5d 100644 --- a/packages/kbn-dev-utils/src/serializers/index.ts +++ b/packages/kbn-dev-utils/src/serializers/index.ts @@ -17,4 +17,7 @@ * under the License. */ -export { createAbsolutePathSerializer } from './absolute_path_serializer'; +export * from './absolute_path_serializer'; +export * from './strip_ansi_serializer'; +export * from './recursive_serializer'; +export * from './any_instance_serizlizer'; diff --git a/packages/kbn-dev-utils/src/serializers/recursive_serializer.ts b/packages/kbn-dev-utils/src/serializers/recursive_serializer.ts new file mode 100644 index 0000000000000..537ae4972c842 --- /dev/null +++ b/packages/kbn-dev-utils/src/serializers/recursive_serializer.ts @@ -0,0 +1,29 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export function createRecursiveSerializer(test: (v: any) => boolean, print: (v: any) => string) { + return { + test: (v: any) => test(v), + serialize: (v: any, ...rest: any[]) => { + const replacement = print(v); + const printer = rest.pop()!; + return printer(replacement, ...rest); + }, + }; +} diff --git a/packages/kbn-dev-utils/src/serializers/strip_ansi_serializer.ts b/packages/kbn-dev-utils/src/serializers/strip_ansi_serializer.ts new file mode 100644 index 0000000000000..4a2151c06f34f --- /dev/null +++ b/packages/kbn-dev-utils/src/serializers/strip_ansi_serializer.ts @@ -0,0 +1,29 @@ +/* + * 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 stripAnsi from 'strip-ansi'; + +import { createRecursiveSerializer } from './recursive_serializer'; + +export function createStripAnsiSerializer() { + return createRecursiveSerializer( + (v) => typeof v === 'string' && stripAnsi(v) !== v, + (v) => stripAnsi(v) + ); +} diff --git a/packages/kbn-es-archiver/package.json b/packages/kbn-es-archiver/package.json new file mode 100644 index 0000000000000..13b5662519b19 --- /dev/null +++ b/packages/kbn-es-archiver/package.json @@ -0,0 +1,17 @@ +{ + "name": "@kbn/es-archiver", + "version": "1.0.0", + "license": "Apache-2.0", + "main": "target/index.js", + "scripts": { + "kbn:bootstrap": "tsc", + "kbn:watch": "tsc --watch" + }, + "dependencies": { + "@kbn/dev-utils": "1.0.0", + "elasticsearch": "^16.7.0" + }, + "devDependencies": { + "@types/elasticsearch": "^5.0.33" + } +} \ No newline at end of file diff --git a/src/es_archiver/actions/edit.ts b/packages/kbn-es-archiver/src/actions/edit.ts similarity index 97% rename from src/es_archiver/actions/edit.ts rename to packages/kbn-es-archiver/src/actions/edit.ts index afa51a3b96477..1194637b1ff89 100644 --- a/src/es_archiver/actions/edit.ts +++ b/packages/kbn-es-archiver/src/actions/edit.ts @@ -24,7 +24,7 @@ import { promisify } from 'util'; import globby from 'globby'; import { ToolingLog } from '@kbn/dev-utils'; -import { createPromiseFromStreams } from '../../legacy/utils'; +import { createPromiseFromStreams } from '../lib/streams'; const unlinkAsync = promisify(Fs.unlink); diff --git a/src/es_archiver/actions/empty_kibana_index.ts b/packages/kbn-es-archiver/src/actions/empty_kibana_index.ts similarity index 100% rename from src/es_archiver/actions/empty_kibana_index.ts rename to packages/kbn-es-archiver/src/actions/empty_kibana_index.ts diff --git a/src/es_archiver/actions/index.ts b/packages/kbn-es-archiver/src/actions/index.ts similarity index 100% rename from src/es_archiver/actions/index.ts rename to packages/kbn-es-archiver/src/actions/index.ts diff --git a/src/es_archiver/actions/load.ts b/packages/kbn-es-archiver/src/actions/load.ts similarity index 99% rename from src/es_archiver/actions/load.ts rename to packages/kbn-es-archiver/src/actions/load.ts index 03de8f39a7c04..efb1fe9f9ea54 100644 --- a/src/es_archiver/actions/load.ts +++ b/packages/kbn-es-archiver/src/actions/load.ts @@ -23,7 +23,7 @@ import { Readable } from 'stream'; import { ToolingLog, KbnClient } from '@kbn/dev-utils'; import { Client } from 'elasticsearch'; -import { createPromiseFromStreams, concatStreamProviders } from '../../legacy/utils'; +import { createPromiseFromStreams, concatStreamProviders } from '../lib/streams'; import { isGzip, diff --git a/src/es_archiver/actions/rebuild_all.ts b/packages/kbn-es-archiver/src/actions/rebuild_all.ts similarity index 97% rename from src/es_archiver/actions/rebuild_all.ts rename to packages/kbn-es-archiver/src/actions/rebuild_all.ts index dfbd51300e04d..470a566a6eef0 100644 --- a/src/es_archiver/actions/rebuild_all.ts +++ b/packages/kbn-es-archiver/src/actions/rebuild_all.ts @@ -23,7 +23,7 @@ import { Readable, Writable } from 'stream'; import { fromNode } from 'bluebird'; import { ToolingLog } from '@kbn/dev-utils'; -import { createPromiseFromStreams } from '../../legacy/utils'; +import { createPromiseFromStreams } from '../lib/streams'; import { prioritizeMappings, readDirectory, diff --git a/src/es_archiver/actions/save.ts b/packages/kbn-es-archiver/src/actions/save.ts similarity index 96% rename from src/es_archiver/actions/save.ts rename to packages/kbn-es-archiver/src/actions/save.ts index 7a3a9dd97c0ab..2f87cabadee6c 100644 --- a/src/es_archiver/actions/save.ts +++ b/packages/kbn-es-archiver/src/actions/save.ts @@ -23,7 +23,7 @@ import { Readable, Writable } from 'stream'; import { Client } from 'elasticsearch'; import { ToolingLog } from '@kbn/dev-utils'; -import { createListStream, createPromiseFromStreams } from '../../legacy/utils'; +import { createListStream, createPromiseFromStreams } from '../lib/streams'; import { createStats, createGenerateIndexRecordsStream, diff --git a/src/es_archiver/actions/unload.ts b/packages/kbn-es-archiver/src/actions/unload.ts similarity index 97% rename from src/es_archiver/actions/unload.ts rename to packages/kbn-es-archiver/src/actions/unload.ts index 130a6b542b218..ae23ef21fb79f 100644 --- a/src/es_archiver/actions/unload.ts +++ b/packages/kbn-es-archiver/src/actions/unload.ts @@ -23,7 +23,7 @@ import { Readable, Writable } from 'stream'; import { Client } from 'elasticsearch'; import { ToolingLog, KbnClient } from '@kbn/dev-utils'; -import { createPromiseFromStreams } from '../../legacy/utils'; +import { createPromiseFromStreams } from '../lib/streams'; import { isGzip, createStats, diff --git a/packages/kbn-es-archiver/src/cli.ts b/packages/kbn-es-archiver/src/cli.ts new file mode 100644 index 0000000000000..1745bd862b434 --- /dev/null +++ b/packages/kbn-es-archiver/src/cli.ts @@ -0,0 +1,244 @@ +/* + * 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. + */ + +/** *********************************************************** + * + * Run `node scripts/es_archiver --help` for usage information + * + *************************************************************/ + +import Path from 'path'; +import Url from 'url'; +import readline from 'readline'; + +import { RunWithCommands, createFlagError } from '@kbn/dev-utils'; +import { readConfigFile } from '@kbn/test'; +import legacyElasticsearch from 'elasticsearch'; + +import { EsArchiver } from './es_archiver'; + +const resolveConfigPath = (v: string) => Path.resolve(process.cwd(), v); +const defaultConfigPath = resolveConfigPath('test/functional/config.js'); + +export function runCli() { + new RunWithCommands({ + description: 'CLI to manage archiving/restoring data in elasticsearch', + globalFlags: { + string: ['es-url', 'kibana-url', 'dir', 'config'], + help: ` + --config path to an FTR config file that sets --es-url, --kibana-url, and --dir + default: ${defaultConfigPath} + --es-url url for Elasticsearch, prefer the --config flag + --kibana-url url for Kibana, prefer the --config flag + --dir where arechives are stored, prefer the --config flag + `, + }, + async extendContext({ log, flags, addCleanupTask }) { + const configPath = flags.config || defaultConfigPath; + if (typeof configPath !== 'string') { + throw createFlagError('--config must be a string'); + } + const config = await readConfigFile(log, Path.resolve(configPath)); + + let esUrl = flags['es-url']; + if (esUrl && typeof esUrl !== 'string') { + throw createFlagError('--es-url must be a string'); + } + if (!esUrl && config) { + esUrl = Url.format(config.get('servers.elasticsearch')); + } + if (!esUrl) { + throw createFlagError('--es-url or --config must be defined'); + } + + let kibanaUrl = flags['kibana-url']; + if (kibanaUrl && typeof kibanaUrl !== 'string') { + throw createFlagError('--kibana-url must be a string'); + } + if (!kibanaUrl && config) { + kibanaUrl = Url.format(config.get('servers.kibana')); + } + if (!kibanaUrl) { + throw createFlagError('--kibana-url or --config must be defined'); + } + + let dir = flags.dir; + if (dir && typeof dir !== 'string') { + throw createFlagError('--dir must be a string'); + } + if (!dir && config) { + dir = Path.resolve(config.get('esArchiver.directory')); + } + if (!dir) { + throw createFlagError('--dir or --config must be defined'); + } + + const client = new legacyElasticsearch.Client({ + host: esUrl, + log: flags.verbose ? 'trace' : [], + }); + addCleanupTask(() => client.close()); + + const esArchiver = new EsArchiver({ + log, + client, + dataDir: dir, + kibanaUrl, + }); + + return { + esArchiver, + }; + }, + }) + .command({ + name: 'save', + usage: 'save [name] [...indices]', + description: ` + archive the [indices ...] into the --dir with [name] + + Example: + Save all [logstash-*] indices from http://localhost:9200 to [snapshots/my_test_data] directory + + WARNING: If the [my_test_data] snapshot exists it will be deleted! + + $ node scripts/es_archiver save my_test_data logstash-* --dir snapshots + `, + flags: { + boolean: ['raw'], + help: ` + --raw don't gzip the archives + `, + }, + async run({ flags, esArchiver }) { + const [name, ...indices] = flags._; + if (!name) { + throw createFlagError('missing [name] argument'); + } + if (!indices.length) { + throw createFlagError('missing [...indices] arguments'); + } + + const raw = flags.raw; + if (typeof raw !== 'boolean') { + throw createFlagError('--raw does not take a value'); + } + + await esArchiver.save(name, indices, { raw }); + }, + }) + .command({ + name: 'load', + usage: 'load [name]', + description: ` + load the archive in --dir with [name] + + Example: + Load the [my_test_data] snapshot from the archive directory and elasticsearch instance defined + in the [test/functional/config.js] config file + + WARNING: If the indices exist already they will be deleted! + + $ node scripts/es_archiver load my_test_data --config test/functional/config.js + `, + flags: { + boolean: ['use-create'], + help: ` + --use-create use create instead of index for loading documents + `, + }, + async run({ flags, esArchiver }) { + const [name] = flags._; + if (!name) { + throw createFlagError('missing [name] argument'); + } + if (flags._.length > 1) { + throw createFlagError(`unknown extra arguments: [${flags._.slice(1).join(', ')}]`); + } + + const useCreate = flags['use-create']; + if (typeof useCreate !== 'boolean') { + throw createFlagError('--use-create does not take a value'); + } + + await esArchiver.load(name, { useCreate }); + }, + }) + .command({ + name: 'unload', + usage: 'unload [name]', + description: 'remove indices created by the archive in --dir with [name]', + async run({ flags, esArchiver }) { + const [name] = flags._; + if (!name) { + throw createFlagError('missing [name] argument'); + } + if (flags._.length > 1) { + throw createFlagError(`unknown extra arguments: [${flags._.slice(1).join(', ')}]`); + } + + await esArchiver.unload(name); + }, + }) + .command({ + name: 'edit', + usage: 'edit [prefix]', + description: + 'extract the archives under the prefix, wait for edits to be completed, and then recompress the archives', + async run({ flags, esArchiver }) { + const [prefix] = flags._; + if (!prefix) { + throw createFlagError('missing [prefix] argument'); + } + if (flags._.length > 1) { + throw createFlagError(`unknown extra arguments: [${flags._.slice(1).join(', ')}]`); + } + + await esArchiver.edit(prefix, async () => { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + + await new Promise((resolveInput) => { + rl.question(`Press enter when you're done`, () => { + rl.close(); + resolveInput(); + }); + }); + }); + }, + }) + .command({ + name: 'empty-kibana-index', + description: + '[internal] Delete any Kibana indices, and initialize the Kibana index as Kibana would do on startup.', + async run({ esArchiver }) { + await esArchiver.emptyKibanaIndex(); + }, + }) + .command({ + name: 'rebuild-all', + description: '[internal] read and write all archives in --dir to remove any inconsistencies', + async run({ esArchiver }) { + await esArchiver.rebuildAll(); + }, + }) + .execute(); +} diff --git a/src/es_archiver/es_archiver.ts b/packages/kbn-es-archiver/src/es_archiver.ts similarity index 100% rename from src/es_archiver/es_archiver.ts rename to packages/kbn-es-archiver/src/es_archiver.ts diff --git a/src/es_archiver/index.ts b/packages/kbn-es-archiver/src/index.ts similarity index 97% rename from src/es_archiver/index.ts rename to packages/kbn-es-archiver/src/index.ts index f7a579a98a42d..c00d457c939ce 100644 --- a/src/es_archiver/index.ts +++ b/packages/kbn-es-archiver/src/index.ts @@ -18,3 +18,4 @@ */ export { EsArchiver } from './es_archiver'; +export * from './cli'; diff --git a/src/es_archiver/lib/__tests__/stats.ts b/packages/kbn-es-archiver/src/lib/__tests__/stats.ts similarity index 100% rename from src/es_archiver/lib/__tests__/stats.ts rename to packages/kbn-es-archiver/src/lib/__tests__/stats.ts diff --git a/src/es_archiver/lib/archives/__tests__/format.ts b/packages/kbn-es-archiver/src/lib/archives/__tests__/format.ts similarity index 96% rename from src/es_archiver/lib/archives/__tests__/format.ts rename to packages/kbn-es-archiver/src/lib/archives/__tests__/format.ts index f3829273ea808..044a0e82d9df2 100644 --- a/src/es_archiver/lib/archives/__tests__/format.ts +++ b/packages/kbn-es-archiver/src/lib/archives/__tests__/format.ts @@ -22,11 +22,7 @@ import { createGunzip } from 'zlib'; import expect from '@kbn/expect'; -import { - createListStream, - createPromiseFromStreams, - createConcatStream, -} from '../../../../legacy/utils'; +import { createListStream, createPromiseFromStreams, createConcatStream } from '../../streams'; import { createFormatArchiveStreams } from '../format'; diff --git a/src/es_archiver/lib/archives/__tests__/parse.ts b/packages/kbn-es-archiver/src/lib/archives/__tests__/parse.ts similarity index 97% rename from src/es_archiver/lib/archives/__tests__/parse.ts rename to packages/kbn-es-archiver/src/lib/archives/__tests__/parse.ts index 50cbdfe06f361..25b8fe46a81fc 100644 --- a/src/es_archiver/lib/archives/__tests__/parse.ts +++ b/packages/kbn-es-archiver/src/lib/archives/__tests__/parse.ts @@ -22,11 +22,7 @@ import { createGzip } from 'zlib'; import expect from '@kbn/expect'; -import { - createConcatStream, - createListStream, - createPromiseFromStreams, -} from '../../../../legacy/utils'; +import { createConcatStream, createListStream, createPromiseFromStreams } from '../../streams'; import { createParseArchiveStreams } from '../parse'; @@ -109,7 +105,7 @@ describe('esArchiver createParseArchiveStreams', () => { Buffer.from('{"a": 2}\n\n'), ]), ...createParseArchiveStreams({ gzip: false }), - createConcatStream(), + createConcatStream([]), ] as [Readable, ...Writable[]]); throw new Error('should have failed'); } catch (err) { @@ -172,7 +168,7 @@ describe('esArchiver createParseArchiveStreams', () => { await createPromiseFromStreams([ createListStream([Buffer.from('{"a": 1}')]), ...createParseArchiveStreams({ gzip: true }), - createConcatStream(), + createConcatStream([]), ] as [Readable, ...Writable[]]); throw new Error('should have failed'); } catch (err) { diff --git a/src/es_archiver/lib/archives/constants.ts b/packages/kbn-es-archiver/src/lib/archives/constants.ts similarity index 100% rename from src/es_archiver/lib/archives/constants.ts rename to packages/kbn-es-archiver/src/lib/archives/constants.ts diff --git a/src/es_archiver/lib/archives/filenames.ts b/packages/kbn-es-archiver/src/lib/archives/filenames.ts similarity index 100% rename from src/es_archiver/lib/archives/filenames.ts rename to packages/kbn-es-archiver/src/lib/archives/filenames.ts diff --git a/src/es_archiver/lib/archives/format.ts b/packages/kbn-es-archiver/src/lib/archives/format.ts similarity index 94% rename from src/es_archiver/lib/archives/format.ts rename to packages/kbn-es-archiver/src/lib/archives/format.ts index ac18147ad6948..3cd698c3f82c3 100644 --- a/src/es_archiver/lib/archives/format.ts +++ b/packages/kbn-es-archiver/src/lib/archives/format.ts @@ -21,7 +21,7 @@ import { createGzip, Z_BEST_COMPRESSION } from 'zlib'; import { PassThrough } from 'stream'; import stringify from 'json-stable-stringify'; -import { createMapStream, createIntersperseStream } from '../../../legacy/utils'; +import { createMapStream, createIntersperseStream } from '../streams'; import { RECORD_SEPARATOR } from './constants'; export function createFormatArchiveStreams({ gzip = false }: { gzip?: boolean } = {}) { diff --git a/src/es_archiver/lib/archives/index.ts b/packages/kbn-es-archiver/src/lib/archives/index.ts similarity index 100% rename from src/es_archiver/lib/archives/index.ts rename to packages/kbn-es-archiver/src/lib/archives/index.ts diff --git a/src/es_archiver/lib/archives/parse.ts b/packages/kbn-es-archiver/src/lib/archives/parse.ts similarity index 87% rename from src/es_archiver/lib/archives/parse.ts rename to packages/kbn-es-archiver/src/lib/archives/parse.ts index 1d650815f9358..9236a618aa01a 100644 --- a/src/es_archiver/lib/archives/parse.ts +++ b/packages/kbn-es-archiver/src/lib/archives/parse.ts @@ -19,8 +19,12 @@ import { createGunzip } from 'zlib'; import { PassThrough } from 'stream'; -import { createFilterStream } from '../../../legacy/utils/streams/filter_stream'; -import { createSplitStream, createReplaceStream, createMapStream } from '../../../legacy/utils'; +import { + createFilterStream, + createSplitStream, + createReplaceStream, + createMapStream, +} from '../streams'; import { RECORD_SEPARATOR } from './constants'; diff --git a/src/es_archiver/lib/directory.ts b/packages/kbn-es-archiver/src/lib/directory.ts similarity index 100% rename from src/es_archiver/lib/directory.ts rename to packages/kbn-es-archiver/src/lib/directory.ts diff --git a/src/es_archiver/lib/docs/__tests__/generate_doc_records_stream.ts b/packages/kbn-es-archiver/src/lib/docs/__tests__/generate_doc_records_stream.ts similarity index 97% rename from src/es_archiver/lib/docs/__tests__/generate_doc_records_stream.ts rename to packages/kbn-es-archiver/src/lib/docs/__tests__/generate_doc_records_stream.ts index 03599cdc9fbcf..2214f7ae9f2ea 100644 --- a/src/es_archiver/lib/docs/__tests__/generate_doc_records_stream.ts +++ b/packages/kbn-es-archiver/src/lib/docs/__tests__/generate_doc_records_stream.ts @@ -21,11 +21,7 @@ import sinon from 'sinon'; import expect from '@kbn/expect'; import { delay } from 'bluebird'; -import { - createListStream, - createPromiseFromStreams, - createConcatStream, -} from '../../../../legacy/utils'; +import { createListStream, createPromiseFromStreams, createConcatStream } from '../../streams'; import { createGenerateDocRecordsStream } from '../generate_doc_records_stream'; import { Progress } from '../../progress'; diff --git a/src/es_archiver/lib/docs/__tests__/index_doc_records_stream.ts b/packages/kbn-es-archiver/src/lib/docs/__tests__/index_doc_records_stream.ts similarity index 99% rename from src/es_archiver/lib/docs/__tests__/index_doc_records_stream.ts rename to packages/kbn-es-archiver/src/lib/docs/__tests__/index_doc_records_stream.ts index 35b068a691090..2b8eac5c27122 100644 --- a/src/es_archiver/lib/docs/__tests__/index_doc_records_stream.ts +++ b/packages/kbn-es-archiver/src/lib/docs/__tests__/index_doc_records_stream.ts @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import { delay } from 'bluebird'; -import { createListStream, createPromiseFromStreams } from '../../../../legacy/utils'; +import { createListStream, createPromiseFromStreams } from '../../streams'; import { Progress } from '../../progress'; import { createIndexDocRecordsStream } from '../index_doc_records_stream'; diff --git a/src/es_archiver/lib/docs/__tests__/stubs.ts b/packages/kbn-es-archiver/src/lib/docs/__tests__/stubs.ts similarity index 100% rename from src/es_archiver/lib/docs/__tests__/stubs.ts rename to packages/kbn-es-archiver/src/lib/docs/__tests__/stubs.ts diff --git a/src/es_archiver/lib/docs/generate_doc_records_stream.ts b/packages/kbn-es-archiver/src/lib/docs/generate_doc_records_stream.ts similarity index 100% rename from src/es_archiver/lib/docs/generate_doc_records_stream.ts rename to packages/kbn-es-archiver/src/lib/docs/generate_doc_records_stream.ts diff --git a/src/es_archiver/lib/docs/index.ts b/packages/kbn-es-archiver/src/lib/docs/index.ts similarity index 100% rename from src/es_archiver/lib/docs/index.ts rename to packages/kbn-es-archiver/src/lib/docs/index.ts diff --git a/src/es_archiver/lib/docs/index_doc_records_stream.ts b/packages/kbn-es-archiver/src/lib/docs/index_doc_records_stream.ts similarity index 100% rename from src/es_archiver/lib/docs/index_doc_records_stream.ts rename to packages/kbn-es-archiver/src/lib/docs/index_doc_records_stream.ts diff --git a/src/es_archiver/lib/index.ts b/packages/kbn-es-archiver/src/lib/index.ts similarity index 100% rename from src/es_archiver/lib/index.ts rename to packages/kbn-es-archiver/src/lib/index.ts diff --git a/src/es_archiver/lib/indices/__tests__/create_index_stream.ts b/packages/kbn-es-archiver/src/lib/indices/__tests__/create_index_stream.ts similarity index 98% rename from src/es_archiver/lib/indices/__tests__/create_index_stream.ts rename to packages/kbn-es-archiver/src/lib/indices/__tests__/create_index_stream.ts index c90497eded88c..27c28b2229aec 100644 --- a/src/es_archiver/lib/indices/__tests__/create_index_stream.ts +++ b/packages/kbn-es-archiver/src/lib/indices/__tests__/create_index_stream.ts @@ -21,11 +21,7 @@ import expect from '@kbn/expect'; import sinon from 'sinon'; import Chance from 'chance'; -import { - createPromiseFromStreams, - createConcatStream, - createListStream, -} from '../../../../legacy/utils'; +import { createPromiseFromStreams, createConcatStream, createListStream } from '../../streams'; import { createCreateIndexStream } from '../create_index_stream'; diff --git a/src/es_archiver/lib/indices/__tests__/delete_index_stream.ts b/packages/kbn-es-archiver/src/lib/indices/__tests__/delete_index_stream.ts similarity index 99% rename from src/es_archiver/lib/indices/__tests__/delete_index_stream.ts rename to packages/kbn-es-archiver/src/lib/indices/__tests__/delete_index_stream.ts index 1c989ba158a29..551b744415c83 100644 --- a/src/es_archiver/lib/indices/__tests__/delete_index_stream.ts +++ b/packages/kbn-es-archiver/src/lib/indices/__tests__/delete_index_stream.ts @@ -19,7 +19,7 @@ import sinon from 'sinon'; -import { createListStream, createPromiseFromStreams } from '../../../../legacy/utils'; +import { createListStream, createPromiseFromStreams } from '../../streams'; import { createDeleteIndexStream } from '../delete_index_stream'; diff --git a/src/es_archiver/lib/indices/__tests__/generate_index_records_stream.ts b/packages/kbn-es-archiver/src/lib/indices/__tests__/generate_index_records_stream.ts similarity index 97% rename from src/es_archiver/lib/indices/__tests__/generate_index_records_stream.ts rename to packages/kbn-es-archiver/src/lib/indices/__tests__/generate_index_records_stream.ts index fe927483da7b0..cb3746c015dad 100644 --- a/src/es_archiver/lib/indices/__tests__/generate_index_records_stream.ts +++ b/packages/kbn-es-archiver/src/lib/indices/__tests__/generate_index_records_stream.ts @@ -20,11 +20,7 @@ import sinon from 'sinon'; import expect from '@kbn/expect'; -import { - createListStream, - createPromiseFromStreams, - createConcatStream, -} from '../../../../legacy/utils'; +import { createListStream, createPromiseFromStreams, createConcatStream } from '../../streams'; import { createStubClient, createStubStats } from './stubs'; diff --git a/src/es_archiver/lib/indices/__tests__/stubs.ts b/packages/kbn-es-archiver/src/lib/indices/__tests__/stubs.ts similarity index 100% rename from src/es_archiver/lib/indices/__tests__/stubs.ts rename to packages/kbn-es-archiver/src/lib/indices/__tests__/stubs.ts diff --git a/src/es_archiver/lib/indices/create_index_stream.ts b/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts similarity index 100% rename from src/es_archiver/lib/indices/create_index_stream.ts rename to packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts diff --git a/src/es_archiver/lib/indices/delete_index.ts b/packages/kbn-es-archiver/src/lib/indices/delete_index.ts similarity index 100% rename from src/es_archiver/lib/indices/delete_index.ts rename to packages/kbn-es-archiver/src/lib/indices/delete_index.ts diff --git a/src/es_archiver/lib/indices/delete_index_stream.ts b/packages/kbn-es-archiver/src/lib/indices/delete_index_stream.ts similarity index 100% rename from src/es_archiver/lib/indices/delete_index_stream.ts rename to packages/kbn-es-archiver/src/lib/indices/delete_index_stream.ts diff --git a/src/es_archiver/lib/indices/generate_index_records_stream.ts b/packages/kbn-es-archiver/src/lib/indices/generate_index_records_stream.ts similarity index 100% rename from src/es_archiver/lib/indices/generate_index_records_stream.ts rename to packages/kbn-es-archiver/src/lib/indices/generate_index_records_stream.ts diff --git a/src/es_archiver/lib/indices/index.ts b/packages/kbn-es-archiver/src/lib/indices/index.ts similarity index 100% rename from src/es_archiver/lib/indices/index.ts rename to packages/kbn-es-archiver/src/lib/indices/index.ts diff --git a/src/es_archiver/lib/indices/kibana_index.ts b/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts similarity index 98% rename from src/es_archiver/lib/indices/kibana_index.ts rename to packages/kbn-es-archiver/src/lib/indices/kibana_index.ts index 1867f24d6f9ed..79e758f09ccf0 100644 --- a/src/es_archiver/lib/indices/kibana_index.ts +++ b/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts @@ -75,7 +75,7 @@ export async function migrateKibanaIndex({ }, } as any); - return await kbnClient.savedObjects.migrate(); + await kbnClient.savedObjects.migrate(); } /** diff --git a/src/es_archiver/lib/progress.ts b/packages/kbn-es-archiver/src/lib/progress.ts similarity index 100% rename from src/es_archiver/lib/progress.ts rename to packages/kbn-es-archiver/src/lib/progress.ts diff --git a/src/es_archiver/lib/records/__tests__/filter_records_stream.ts b/packages/kbn-es-archiver/src/lib/records/__tests__/filter_records_stream.ts similarity index 95% rename from src/es_archiver/lib/records/__tests__/filter_records_stream.ts rename to packages/kbn-es-archiver/src/lib/records/__tests__/filter_records_stream.ts index f4f9f32e239ea..b23ff2e4e52ac 100644 --- a/src/es_archiver/lib/records/__tests__/filter_records_stream.ts +++ b/packages/kbn-es-archiver/src/lib/records/__tests__/filter_records_stream.ts @@ -20,11 +20,7 @@ import Chance from 'chance'; import expect from '@kbn/expect'; -import { - createListStream, - createPromiseFromStreams, - createConcatStream, -} from '../../../../legacy/utils'; +import { createListStream, createPromiseFromStreams, createConcatStream } from '../../streams'; import { createFilterRecordsStream } from '../filter_records_stream'; diff --git a/src/es_archiver/lib/records/filter_records_stream.ts b/packages/kbn-es-archiver/src/lib/records/filter_records_stream.ts similarity index 100% rename from src/es_archiver/lib/records/filter_records_stream.ts rename to packages/kbn-es-archiver/src/lib/records/filter_records_stream.ts diff --git a/src/es_archiver/lib/records/index.ts b/packages/kbn-es-archiver/src/lib/records/index.ts similarity index 100% rename from src/es_archiver/lib/records/index.ts rename to packages/kbn-es-archiver/src/lib/records/index.ts diff --git a/src/es_archiver/lib/stats.ts b/packages/kbn-es-archiver/src/lib/stats.ts similarity index 100% rename from src/es_archiver/lib/stats.ts rename to packages/kbn-es-archiver/src/lib/stats.ts diff --git a/packages/kbn-es-archiver/src/lib/streams.ts b/packages/kbn-es-archiver/src/lib/streams.ts new file mode 100644 index 0000000000000..a90afbe0c4d25 --- /dev/null +++ b/packages/kbn-es-archiver/src/lib/streams.ts @@ -0,0 +1,20 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export * from '../../../../src/legacy/utils/streams'; diff --git a/packages/kbn-es-archiver/tsconfig.json b/packages/kbn-es-archiver/tsconfig.json new file mode 100644 index 0000000000000..6ffa64d91fba0 --- /dev/null +++ b/packages/kbn-es-archiver/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "./target", + "declaration": true, + "sourceMap": true, + "target": "ES2019" + }, + "include": [ + "src/**/*" + ] +} diff --git a/packages/kbn-es-archiver/yarn.lock b/packages/kbn-es-archiver/yarn.lock new file mode 120000 index 0000000000000..3f82ebc9cdbae --- /dev/null +++ b/packages/kbn-es-archiver/yarn.lock @@ -0,0 +1 @@ +../../yarn.lock \ No newline at end of file diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js index 6cb2f3d2901d3..baf5baaf916aa 100755 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js @@ -28,13 +28,9 @@ exports.getWebpackConfig = function (kibanaPath, projectRoot, config) { const alias = { // Kibana defaults https://github.com/elastic/kibana/blob/6998f074542e8c7b32955db159d15661aca253d7/src/legacy/ui/ui_bundler_env.js#L30-L36 ui: fromKibana('src/legacy/ui/public'), - test_harness: fromKibana('src/test_harness/public'), // Dev defaults for test bundle https://github.com/elastic/kibana/blob/6998f074542e8c7b32955db159d15661aca253d7/src/core_plugins/tests_bundle/index.js#L73-L78 ng_mock$: fromKibana('src/test_utils/public/ng_mock'), - 'angular-mocks$': fromKibana( - 'src/legacy/core_plugins/tests_bundle/webpackShims/angular-mocks.js' - ), fixtures: fromKibana('src/fixtures'), test_utils: fromKibana('src/test_utils/public'), }; diff --git a/packages/kbn-optimizer/src/cli.ts b/packages/kbn-optimizer/src/cli.ts index 9d3f4b88a258f..542dc7255f22f 100644 --- a/packages/kbn-optimizer/src/cli.ts +++ b/packages/kbn-optimizer/src/cli.ts @@ -116,7 +116,7 @@ run( log.warning('Unable to initialize CiStatsReporter from env'); } - update$ = update$.pipe(reportOptimizerStats(reporter, config)); + update$ = update$.pipe(reportOptimizerStats(reporter, config, log)); } await update$.pipe(logOptimizerState(log, config)).toPromise(); diff --git a/packages/kbn-optimizer/src/log_optimizer_state.ts b/packages/kbn-optimizer/src/log_optimizer_state.ts index 20d98f74dbe86..e8bc6debf971e 100644 --- a/packages/kbn-optimizer/src/log_optimizer_state.ts +++ b/packages/kbn-optimizer/src/log_optimizer_state.ts @@ -104,7 +104,7 @@ export function logOptimizerState(log: ToolingLog, config: OptimizerConfig) { } if (state.phase === 'running' || state.phase === 'initializing') { - return true; + return; } if (state.phase === 'issue') { @@ -119,7 +119,7 @@ export function logOptimizerState(log: ToolingLog, config: OptimizerConfig) { } } log.indent(-4); - return true; + return; } if (state.phase === 'success') { @@ -135,7 +135,7 @@ export function logOptimizerState(log: ToolingLog, config: OptimizerConfig) { ); } - return true; + return; } throw new Error(`unhandled optimizer message: ${inspect(update)}`); diff --git a/packages/kbn-optimizer/src/report_optimizer_stats.ts b/packages/kbn-optimizer/src/report_optimizer_stats.ts index 5057c717efcc3..eff2bce0b827e 100644 --- a/packages/kbn-optimizer/src/report_optimizer_stats.ts +++ b/packages/kbn-optimizer/src/report_optimizer_stats.ts @@ -21,7 +21,7 @@ import Fs from 'fs'; import Path from 'path'; import { materialize, mergeMap, dematerialize } from 'rxjs/operators'; -import { CiStatsReporter } from '@kbn/dev-utils'; +import { CiStatsReporter, CiStatsMetrics, ToolingLog } from '@kbn/dev-utils'; import { OptimizerUpdate$ } from './run_optimizer'; import { OptimizerState, OptimizerConfig } from './optimizer'; @@ -67,7 +67,11 @@ const getFiles = (dir: string, parent?: string) => return true; }); -export function reportOptimizerStats(reporter: CiStatsReporter, config: OptimizerConfig) { +export function reportOptimizerStats( + reporter: CiStatsReporter, + config: OptimizerConfig, + log: ToolingLog +) { return pipeClosure((update$: OptimizerUpdate$) => { let lastState: OptimizerState | undefined; return update$.pipe( @@ -98,10 +102,18 @@ export function reportOptimizerStats(reporter: CiStatsReporter, config: Optimize const miscFiles = outputFiles.filter( (f) => f !== entry && !asyncChunks.includes(f) ); + + if (asyncChunks.length) { + log.verbose(bundle.id, 'async chunks', asyncChunks); + } + if (miscFiles.length) { + log.verbose(bundle.id, 'misc files', asyncChunks); + } + const sumSize = (files: Entry[]) => files.reduce((acc: number, f) => acc + f.stats!.size, 0); - return [ + const metrics: CiStatsMetrics = [ { group: `@kbn/optimizer bundle module count`, id: bundle.id, @@ -123,6 +135,10 @@ export function reportOptimizerStats(reporter: CiStatsReporter, config: Optimize value: sumSize(miscFiles), }, ]; + + log.info(bundle.id, 'metrics', metrics); + + return metrics; }) ) ); diff --git a/packages/kbn-plugin-generator/README.md b/packages/kbn-plugin-generator/README.md index 95de0e93fd075..6ad665f9b87f8 100644 --- a/packages/kbn-plugin-generator/README.md +++ b/packages/kbn-plugin-generator/README.md @@ -71,10 +71,6 @@ Generated plugins receive a handful of scripts that can be used during developme Build a distributable archive of your plugin. - - `yarn test:karma` - - Run the browser tests in a real web browser. - - `yarn test:mocha` Run the server tests using mocha. diff --git a/packages/kbn-plugin-helpers/README.md b/packages/kbn-plugin-helpers/README.md index 4c648fd9bde8c..d7ed3106c1ceb 100644 --- a/packages/kbn-plugin-helpers/README.md +++ b/packages/kbn-plugin-helpers/README.md @@ -30,7 +30,6 @@ $ plugin-helpers help start Start kibana and have it include this plugin build [options] [files...] Build a distributable archive test Run the server and browser tests - test:karma [options] Run the browser tests in a real web browser test:mocha [files...] Run the server tests using mocha Options: diff --git a/packages/kbn-plugin-helpers/src/cli.ts b/packages/kbn-plugin-helpers/src/cli.ts index b894f854a484f..18ddc62cba8a6 100644 --- a/packages/kbn-plugin-helpers/src/cli.ts +++ b/packages/kbn-plugin-helpers/src/cli.ts @@ -62,25 +62,6 @@ program })) ); -program - .command('test') - .description('Run the server and browser tests') - .on('--help', docs('test/all')) - .action(createCommanderAction('testAll')); - -program - .command('test:karma') - .description('Run the browser tests in a real web browser') - .option('--dev', 'Enable dev mode, keeps the test server running') - .option('-p, --plugins ', "Manually specify which plugins' test bundles to run") - .on('--help', docs('test/karma')) - .action( - createCommanderAction('testKarma', (command) => ({ - dev: Boolean(command.dev), - plugins: command.plugins, - })) - ); - program .command('test:mocha [files...]') .description('Run the server tests using mocha') diff --git a/packages/kbn-plugin-helpers/src/lib/tasks.ts b/packages/kbn-plugin-helpers/src/lib/tasks.ts index 7817838760a2e..bd86bb670ff39 100644 --- a/packages/kbn-plugin-helpers/src/lib/tasks.ts +++ b/packages/kbn-plugin-helpers/src/lib/tasks.ts @@ -19,23 +19,17 @@ import { buildTask } from '../tasks/build'; import { startTask } from '../tasks/start'; -import { testAllTask } from '../tasks/test/all'; -import { testKarmaTask } from '../tasks/test/karma'; import { testMochaTask } from '../tasks/test/mocha'; // define a tasks interface that we can extend in the tests export interface Tasks { build: typeof buildTask; start: typeof startTask; - testAll: typeof testAllTask; - testKarma: typeof testKarmaTask; testMocha: typeof testMochaTask; } export const tasks: Tasks = { build: buildTask, start: startTask, - testAll: testAllTask, - testKarma: testKarmaTask, testMocha: testMochaTask, }; diff --git a/packages/kbn-plugin-helpers/src/tasks/test/all/README.md b/packages/kbn-plugin-helpers/src/tasks/test/all/README.md deleted file mode 100644 index 4f5a72ac0d523..0000000000000 --- a/packages/kbn-plugin-helpers/src/tasks/test/all/README.md +++ /dev/null @@ -1,3 +0,0 @@ -Runs both the mocha and karma tests, in that order. - -This is just a simple caller to both `test/mocha` and `test/karma` \ No newline at end of file diff --git a/packages/kbn-plugin-helpers/src/tasks/test/karma/README.md b/packages/kbn-plugin-helpers/src/tasks/test/karma/README.md deleted file mode 100644 index 8d921e8312344..0000000000000 --- a/packages/kbn-plugin-helpers/src/tasks/test/karma/README.md +++ /dev/null @@ -1,60 +0,0 @@ -writing tests -============= - -Browser tests are written just like server tests, they are just executed differently. - - - place tests near the code they test, in `__tests__` directories throughout - the public directory - - - Use the same bdd-style `describe()` and `it()` - api to define the suites and cases of your tests. - - ```js - describe('some portion of your code', function () { - it('should do this thing', function () { - expect(true).to.be(false); - }); - }); - ``` - - -starting the test runner -======================== - -Under the covers this command uses the `test:karma` task from kibana. This will execute -your tasks once and exit when complete. - -When run with the `--dev` option, the command uses the `test:karma:debug` task from kibana. -This task sets-up a test runner that will watch your code for changes and rebuild your -tests when necessary. You access the test runner through a browser that it starts itself -(via Karma). - -If your plugin consists of a number of internal plugins, you may wish to keep the tests -isolated to a specific plugin or plugins, instead of executing all of the tests. To do this, -use `--plugins` and passing the plugins you would like to test. Multiple plugins can be -specified by separating them with commas. - - -running the tests -================= - -Once the test runner has started you a new browser window should be opened and you should -see a message saying "connected". Next to that is a "DEBUG" button. This button will open -an interactive version of your tests that you can refresh, inspects, and otherwise debug -while you write your tests. - - -focus on the task at hand -========================= - -To limit the tests that run you can either: - - 1. use the ?grep= query string to filter the test cases/suites by name - 2. Click the suite title or (play) button next to test output - 3. Add `.only` to your `describe()` or `it()` calls: - - ```js - describe.only('suite name', function () { - // ... - }); - ``` diff --git a/packages/kbn-plugin-helpers/src/tasks/test/karma/test_karma_task.ts b/packages/kbn-plugin-helpers/src/tasks/test/karma/test_karma_task.ts deleted file mode 100644 index 2fe8134209894..0000000000000 --- a/packages/kbn-plugin-helpers/src/tasks/test/karma/test_karma_task.ts +++ /dev/null @@ -1,42 +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 { execFileSync } from 'child_process'; - -import { TaskContext } from '../../../lib'; -import { winCmd } from '../../../lib/win_cmd'; - -export function testKarmaTask({ plugin, options }: TaskContext) { - options = options || {}; - - const kbnServerArgs = ['--kbnServer.plugin-path=' + plugin.root]; - - if (options.plugins) { - kbnServerArgs.push('--kbnServer.tests_bundle.pluginId=' + options.plugins); - } else { - kbnServerArgs.push('--kbnServer.tests_bundle.pluginId=' + plugin.id); - } - - const task = options.dev ? 'test:karma:debug' : 'test:karma'; - const args = [task].concat(kbnServerArgs); - execFileSync(winCmd('yarn'), args, { - cwd: plugin.kibanaRoot, - stdio: ['ignore', 1, 2], - }); -} diff --git a/src/dev/build/tasks/os_packages/docker_generator/index.js b/packages/kbn-pm/index.d.ts similarity index 96% rename from src/dev/build/tasks/os_packages/docker_generator/index.js rename to packages/kbn-pm/index.d.ts index 9e0bbf51f9a56..aa55df9215c2f 100644 --- a/src/dev/build/tasks/os_packages/docker_generator/index.js +++ b/packages/kbn-pm/index.d.ts @@ -17,4 +17,4 @@ * under the License. */ -export * from './run'; +export * from './src/index'; diff --git a/packages/kbn-pm/tsconfig.json b/packages/kbn-pm/tsconfig.json index bfb13ee8dcf8a..c13a9243c50aa 100644 --- a/packages/kbn-pm/tsconfig.json +++ b/packages/kbn-pm/tsconfig.json @@ -1,6 +1,7 @@ { "extends": "../../tsconfig.json", "include": [ + "./index.d.ts", "./src/**/*.ts", "./dist/*.d.ts", ], diff --git a/packages/kbn-spec-to-console/README.md b/packages/kbn-spec-to-console/README.md index 526ceef43e3cd..0328dec791320 100644 --- a/packages/kbn-spec-to-console/README.md +++ b/packages/kbn-spec-to-console/README.md @@ -23,10 +23,10 @@ At the root of the Kibana repository, run the following commands: ```sh # OSS -yarn spec_to_console -g "/rest-api-spec/src/main/resources/rest-api-spec/api/*" -d "src/plugins/console/server/lib/spec_definitions/json" +yarn spec_to_console -g "/rest-api-spec/src/main/resources/rest-api-spec/api/*" -d "src/plugins/console/server/lib/spec_definitions/json/generated" # X-pack -yarn spec_to_console -g "/x-pack/plugin/src/test/resources/rest-api-spec/api/*" -d "x-pack/plugins/console_extensions/server/lib/spec_definitions/json" +yarn spec_to_console -g "/x-pack/plugin/src/test/resources/rest-api-spec/api/*" -d "x-pack/plugins/console_extensions/server/lib/spec_definitions/json/generated" ``` ### Information used in Console that is not available in the REST spec diff --git a/packages/kbn-test/src/failed_tests_reporter/__fixtures__/cypress_report.xml b/packages/kbn-test/src/failed_tests_reporter/__fixtures__/cypress_report.xml new file mode 100644 index 0000000000000..ed0e154552caa --- /dev/null +++ b/packages/kbn-test/src/failed_tests_reporter/__fixtures__/cypress_report.xml @@ -0,0 +1,50 @@ + + + + + + + + + ...` + +You can fix this problem by: + - Passing `{force: true}` which disables all error checking + - Passing `{waitForAnimations: false}` which disables waiting on animations + - Passing `{animationDistanceThreshold: 20}` which decreases the sensitivity + +https://on.cypress.io/element-is-animating + +Because this error occurred during a `after each` hook we are skipping the remaining tests in the current suite: `timeline flyout button` + at cypressErr (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:146621:16) + at cypressErrByPath (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:146630:10) + at Object.throwErrByPath (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:146593:11) + at Object.ensureElementIsNotAnimating (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:137560:24) + at ensureNotAnimating (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:127434:13) + at runAllChecks (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:127522:9) + at retryActionability (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:127542:16) + at tryCatcher (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:9065:23) + at Function.Promise.attempt.Promise.try (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:6339:29) + at tryFn (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:140680:21) + at whenStable (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:140715:12) + at http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:140259:16 + at tryCatcher (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:9065:23) + at Promise._settlePromiseFromHandler (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:7000:31) + at Promise._settlePromise (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:7057:18) + at Promise._settlePromise0 (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:7102:10)]]> + + + diff --git a/packages/kbn-test/src/failed_tests_reporter/__fixtures__/index.ts b/packages/kbn-test/src/failed_tests_reporter/__fixtures__/index.ts index 02b6b5f064218..11d6cb6a2b47b 100644 --- a/packages/kbn-test/src/failed_tests_reporter/__fixtures__/index.ts +++ b/packages/kbn-test/src/failed_tests_reporter/__fixtures__/index.ts @@ -21,5 +21,5 @@ const Fs = jest.requireActual('fs'); export const FTR_REPORT = Fs.readFileSync(require.resolve('./ftr_report.xml'), 'utf8'); export const JEST_REPORT = Fs.readFileSync(require.resolve('./jest_report.xml'), 'utf8'); -export const KARMA_REPORT = Fs.readFileSync(require.resolve('./karma_report.xml'), 'utf8'); export const MOCHA_REPORT = Fs.readFileSync(require.resolve('./mocha_report.xml'), 'utf8'); +export const CYPRESS_REPORT = Fs.readFileSync(require.resolve('./cypress_report.xml'), 'utf8'); diff --git a/packages/kbn-test/src/failed_tests_reporter/__fixtures__/karma_report.xml b/packages/kbn-test/src/failed_tests_reporter/__fixtures__/karma_report.xml deleted file mode 100644 index 5c4bdb9f50adf..0000000000000 --- a/packages/kbn-test/src/failed_tests_reporter/__fixtures__/karma_report.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - Error: expected 7069 to be below 64 - at Assertion.__kbnBundles__.tests../packages/kbn-expect/expect.js.Assertion.assert (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:13671:11) - at Assertion.__kbnBundles__.tests../packages/kbn-expect/expect.js.Assertion.lessThan.Assertion.below (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:13891:8) - at Function.lessThan (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:14078:15) - at _callee3$ (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:158985:60) - at tryCatch (webpack://%5Bname%5D/./node_modules/regenerator-runtime/runtime.js?:62:40) - at Generator.invoke [as _invoke] (webpack://%5Bname%5D/./node_modules/regenerator-runtime/runtime.js?:288:22) - at Generator.prototype.<computed> [as next] (webpack://%5Bname%5D/./node_modules/regenerator-runtime/runtime.js?:114:21) - at asyncGeneratorStep (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:158772:103) - at _next (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:158774:194) - - - - - - - - - diff --git a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts index f8f279151e07f..505e898c62adf 100644 --- a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts +++ b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts @@ -39,7 +39,7 @@ jest.mock('fs', () => { }; }); -import { FTR_REPORT, JEST_REPORT, MOCHA_REPORT, KARMA_REPORT } from './__fixtures__'; +import { FTR_REPORT, JEST_REPORT, MOCHA_REPORT, CYPRESS_REPORT } from './__fixtures__'; import { parseTestReport } from './test_report'; import { addMessagesToReport } from './add_messages_to_report'; @@ -270,77 +270,64 @@ it('rewrites mocha reports with minimal changes', async () => { `); }); -it('rewrites karma reports with minimal changes', async () => { +it('rewrites cypress reports with minimal changes', async () => { const xml = await addMessagesToReport({ - report: await parseTestReport(KARMA_REPORT), messages: [ { - name: - 'CoordinateMapsVisualizationTest CoordinateMapsVisualization - basics should initialize OK', - classname: 'Browser Unit Tests.CoordinateMapsVisualizationTest', - message: 'foo bar', + classname: '"after each" hook for "toggles open the timeline"', + name: 'timeline flyout button "after each" hook for "toggles open the timeline"', + message: 'Some extra content\n', }, ], + report: await parseTestReport(CYPRESS_REPORT), log, - reportPath: Path.resolve(__dirname, './__fixtures__/karma_report.xml'), + reportPath: Path.resolve(__dirname, './__fixtures__/cypress_report.xml'), }); - expect(createPatch('karma.xml', KARMA_REPORT, xml, { context: 0 })).toMatchInlineSnapshot(` - Index: karma.xml + expect(createPatch('cypress.xml', CYPRESS_REPORT, xml, { context: 0 })).toMatchInlineSnapshot(` + Index: cypress.xml =================================================================== - --- karma.xml [object Object] - +++ karma.xml - @@ -1,5 +1,5 @@ - -‹?xml version="1.0"?› + --- cypress.xml [object Object] + +++ cypress.xml + @@ -1,25 +1,16 @@ + -‹?xml version="1.0" encoding="UTF-8"?› +‹?xml version="1.0" encoding="utf-8"?› - ‹testsuite name="Chrome 75.0.3770 (Mac OS X 10.14.5)" package="" timestamp="2019-07-02T19:53:21" id="0" hostname="spalger.lan" tests="648" errors="0" failures="4" time="1.759"› - ‹properties› - ‹property name="browser.fullName" value="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"/› - ‹/properties› - @@ -7,27 +7,31 @@ - ‹testcase name="Vis-Editor-Agg-Params plugin directive should hide custom label parameter" time="0" classname="Browser Unit Tests.Vis-Editor-Agg-Params plugin directive"› - ‹skipped/› - ‹/testcase› - ‹testcase name="CoordinateMapsVisualizationTest CoordinateMapsVisualization - basics should initialize OK" time="0.265" classname="Browser Unit Tests.CoordinateMapsVisualizationTest"› - - ‹failure type=""›Error: expected 7069 to be below 64 - - at Assertion.__kbnBundles__.tests../packages/kbn-expect/expect.js.Assertion.assert (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:13671:11) - - at Assertion.__kbnBundles__.tests../packages/kbn-expect/expect.js.Assertion.lessThan.Assertion.below (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:13891:8) - - at Function.lessThan (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:14078:15) - - at _callee3$ (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:158985:60) - + ‹failure type=""›‹![CDATA[Error: expected 7069 to be below 64 - + at Assertion.__kbnBundles__.tests../packages/kbn-expect/expect.js.Assertion.assert (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:13671:11) - + at Assertion.__kbnBundles__.tests../packages/kbn-expect/expect.js.Assertion.lessThan.Assertion.below (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:13891:8) - + at Function.lessThan (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:14078:15) - + at _callee3$ (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:158985:60) - at tryCatch (webpack://%5Bname%5D/./node_modules/regenerator-runtime/runtime.js?:62:40) - at Generator.invoke [as _invoke] (webpack://%5Bname%5D/./node_modules/regenerator-runtime/runtime.js?:288:22) - - at Generator.prototype.<computed> [as next] (webpack://%5Bname%5D/./node_modules/regenerator-runtime/runtime.js?:114:21) - - at asyncGeneratorStep (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:158772:103) - - at _next (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:158774:194) - -‹/failure› - + at Generator.prototype.‹computed› [as next] (webpack://%5Bname%5D/./node_modules/regenerator-runtime/runtime.js?:114:21) - + at asyncGeneratorStep (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:158772:103) - + at _next (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:158774:194) - +]]›‹/failure› - + ‹system-out›Failed Tests Reporter: - + - foo bar - + - +‹/system-out› - ‹/testcase› - ‹testcase name="CoordinateMapsVisualizationTest CoordinateMapsVisualization - basics should toggle to Heatmap OK" time="0.055" classname="Browser Unit Tests.CoordinateMapsVisualizationTest"/› - ‹testcase name="VegaParser._parseSchema should warn on vega-lite version too new to be supported" time="0.001" classname="Browser Unit Tests.VegaParser·_parseSchema"/› - ‹system-out› - - ‹![CDATA[Chrome 75.0.3770 (Mac OS X 10.14.5) LOG: 'ready to load tests for shard 1 of 4' - + Chrome 75.0.3770 (Mac OS X 10.14.5) LOG: 'ready to load tests for shard 1 of 4' - ,Chrome 75.0.3770 (Mac OS X 10.14.5) WARN: 'Unmatched GET to http://localhost:9876/api/interpreter/fns' - ... + ‹testsuites name="Mocha Tests" time="16.198" tests="2" failures="1"› + - ‹testsuite name="Root Suite" timestamp="2020-07-22T15:06:26" tests="0" file="cypress/integration/timeline_flyout_button.spec.ts" failures="0" time="0"› + - ‹/testsuite› + + ‹testsuite name="Root Suite" timestamp="2020-07-22T15:06:26" tests="0" file="cypress/integration/timeline_flyout_button.spec.ts" failures="0" time="0"/› + ‹testsuite name="timeline flyout button" timestamp="2020-07-22T15:06:26" tests="2" failures="1" time="16.198"› + - ‹testcase name="timeline flyout button toggles open the timeline" time="8.099" classname="toggles open the timeline"› + - ‹/testcase› + + ‹testcase name="timeline flyout button toggles open the timeline" time="8.099" classname="toggles open the timeline"/› + ‹testcase name="timeline flyout button "after each" hook for "toggles open the timeline"" time="8.099" classname=""after each" hook for "toggles open the timeline""› + - ‹failure message="Timed out retrying: \`cy.click()\` could not be issued because this element is currently animating: + + ‹failure message="Timed out retrying: \`cy.click()\` could not be issued because this element is currently animating: \`<button class="euiButtonEmpty euiButtonEmpty--text" type="button" data-test-subj="timeline-new"›...</button›\` You can fix this problem by: - Passing \`{force: true}\` which disables all error checking - Passing \`{waitForAnimations: false}\` which disables waiting on animations - Passing \`{animationDistanceThreshold: 20}\` which decreases the sensitivity https://on.cypress.io/element-is-animating Because this error occurred during a \`after each\` hook we are skipping the remaining tests in the current suite: \`timeline flyout button\`" type="CypressError"›‹![CDATA[Failed Tests Reporter: + + - Some extra content - -]]› - + - ‹/system-out› - ‹system-err/› - -‹/testsuite› - +‹/testsuite› + -\`<button class="euiButtonEmpty euiButtonEmpty--text" type="button" data-test-subj="timeline-new">...</button>\` + + -You can fix this problem by: + - - Passing \`{force: true}\` which disables all error checking + - - Passing \`{waitForAnimations: false}\` which disables waiting on animations + - - Passing \`{animationDistanceThreshold: 20}\` which decreases the sensitivity + +CypressError: Timed out retrying: \`cy.click()\` could not be issued because this element is currently animating: + + -https://on.cypress.io/element-is-animating + - + -Because this error occurred during a \`after each\` hook we are skipping the remaining tests in the current suite: \`timeline flyout button\`" type="CypressError"›‹![CDATA[CypressError: Timed out retrying: \`cy.click()\` could not be issued because this element is currently animating: + - + \`‹button class="euiButtonEmpty euiButtonEmpty--text" type="button" data-test-subj="timeline-new"›...‹/button›\` + + You can fix this problem by: + - Passing \`{force: true}\` which disables all error checking + @@ -46,5 +37,5 @@ + at Promise._settlePromise (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:7057:18) + at Promise._settlePromise0 (http://elastic:changeme@localhost:61141/__cypress/runner/cypress_runner.js:7102:10)]]›‹/failure› + ‹/testcase› + ‹/testsuite› + -‹/testsuites› + +‹/testsuites› \\ No newline at end of file `); diff --git a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts index 6bc7556db8a47..27bf8a9c7549d 100644 --- a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts +++ b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts @@ -59,10 +59,14 @@ export async function addMessagesToReport(options: { log.info(`${classname} - ${name}:${messageList}`); const output = `Failed Tests Reporter:${messageList}\n\n`; - if (!testCase['system-out']) { - testCase['system-out'] = [output]; + if (typeof testCase.failure[0] === 'object' && testCase.failure[0].$.message) { + // failure with "messages" ignore the system-out on jenkins + // so we instead extend the failure message + testCase.failure[0]._ = output + testCase.failure[0]._; + } else if (!testCase['system-out']) { + testCase['system-out'] = [{ _: output }]; } else if (typeof testCase['system-out'][0] === 'string') { - testCase['system-out'][0] = output + String(testCase['system-out'][0]); + testCase['system-out'][0] = { _: output + testCase['system-out'][0] }; } else { testCase['system-out'][0]._ = output + testCase['system-out'][0]._; } diff --git a/packages/kbn-test/src/failed_tests_reporter/get_failures.test.ts b/packages/kbn-test/src/failed_tests_reporter/get_failures.test.ts index 23d9805727f32..f570ed36111b3 100644 --- a/packages/kbn-test/src/failed_tests_reporter/get_failures.test.ts +++ b/packages/kbn-test/src/failed_tests_reporter/get_failures.test.ts @@ -19,7 +19,7 @@ import { getFailures } from './get_failures'; import { parseTestReport } from './test_report'; -import { FTR_REPORT, JEST_REPORT, KARMA_REPORT, MOCHA_REPORT } from './__fixtures__'; +import { FTR_REPORT, JEST_REPORT, MOCHA_REPORT } from './__fixtures__'; it('discovers failures in ftr report', async () => { const failures = getFailures(await parseTestReport(FTR_REPORT)); @@ -85,31 +85,6 @@ it('discovers failures in jest report', async () => { `); }); -it('discovers failures in karma report', async () => { - const failures = getFailures(await parseTestReport(KARMA_REPORT)); - expect(failures).toMatchInlineSnapshot(` - Array [ - Object { - "classname": "Browser Unit Tests.CoordinateMapsVisualizationTest", - "failure": "Error: expected 7069 to be below 64 - at Assertion.__kbnBundles__.tests../packages/kbn-expect/expect.js.Assertion.assert (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:13671:11) - at Assertion.__kbnBundles__.tests../packages/kbn-expect/expect.js.Assertion.lessThan.Assertion.below (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:13891:8) - at Function.lessThan (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:14078:15) - at _callee3$ (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:158985:60) - at tryCatch (webpack://%5Bname%5D/./node_modules/regenerator-runtime/runtime.js?:62:40) - at Generator.invoke [as _invoke] (webpack://%5Bname%5D/./node_modules/regenerator-runtime/runtime.js?:288:22) - at Generator.prototype. [as next] (webpack://%5Bname%5D/./node_modules/regenerator-runtime/runtime.js?:114:21) - at asyncGeneratorStep (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:158772:103) - at _next (http://localhost:5610/bundles/tests.bundle.js?shards=4&shard_num=1:158774:194) - ", - "likelyIrrelevant": false, - "name": "CoordinateMapsVisualizationTest CoordinateMapsVisualization - basics should initialize OK", - "time": "0.265", - }, - ] - `); -}); - it('discovers failures in mocha report', async () => { const failures = getFailures(await parseTestReport(MOCHA_REPORT)); expect(failures).toMatchInlineSnapshot(` diff --git a/packages/kbn-test/src/failed_tests_reporter/report_metadata.test.ts b/packages/kbn-test/src/failed_tests_reporter/report_metadata.test.ts index 729d80ddfcb44..c079084965609 100644 --- a/packages/kbn-test/src/failed_tests_reporter/report_metadata.test.ts +++ b/packages/kbn-test/src/failed_tests_reporter/report_metadata.test.ts @@ -19,7 +19,7 @@ import { getReportMessageIter } from './report_metadata'; import { parseTestReport } from './test_report'; -import { FTR_REPORT, JEST_REPORT, KARMA_REPORT, MOCHA_REPORT } from './__fixtures__'; +import { FTR_REPORT, JEST_REPORT, MOCHA_REPORT } from './__fixtures__'; it('reads messages and screenshots from metadata-json properties', async () => { const ftrReport = await parseTestReport(FTR_REPORT); @@ -43,7 +43,4 @@ it('reads messages and screenshots from metadata-json properties', async () => { const mochaReport = await parseTestReport(MOCHA_REPORT); expect(Array.from(getReportMessageIter(mochaReport))).toMatchInlineSnapshot(`Array []`); - - const karmaReport = await parseTestReport(KARMA_REPORT); - expect(Array.from(getReportMessageIter(karmaReport))).toMatchInlineSnapshot(`Array []`); }); diff --git a/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts b/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts index 8a951ac969199..3dfb1ea44d9e7 100644 --- a/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts +++ b/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts @@ -72,6 +72,7 @@ export function runFailedTestsReporterCli() { } const patterns = flags._.length ? flags._ : DEFAULT_PATTERNS; + log.info('Searching for reports at', patterns); const reportPaths = await globby(patterns, { absolute: true, }); @@ -80,6 +81,7 @@ export function runFailedTestsReporterCli() { throw createFailError(`Unable to find any junit reports with patterns [${patterns}]`); } + log.info('found', reportPaths.length, 'junit reports', reportPaths); const newlyCreatedIssues: Array<{ failure: TestFailure; newIssue: GithubIssueMini; diff --git a/packages/kbn-test/src/failed_tests_reporter/test_report.ts b/packages/kbn-test/src/failed_tests_reporter/test_report.ts index 43d84163462d3..9907ca8b89ca5 100644 --- a/packages/kbn-test/src/failed_tests_reporter/test_report.ts +++ b/packages/kbn-test/src/failed_tests_reporter/test_report.ts @@ -70,7 +70,7 @@ export interface TestCase { } export interface FailedTestCase extends TestCase { - failure: Array; + failure: Array; } /** diff --git a/packages/kbn-test/src/functional_test_runner/index.ts b/packages/kbn-test/src/functional_test_runner/index.ts index cf65ceb51df8e..b13c311350ff6 100644 --- a/packages/kbn-test/src/functional_test_runner/index.ts +++ b/packages/kbn-test/src/functional_test_runner/index.ts @@ -18,6 +18,6 @@ */ export { FunctionalTestRunner } from './functional_test_runner'; -export { readConfigFile } from './lib'; +export { readConfigFile, Config } from './lib'; export { runFtrCli } from './cli'; export * from './lib/docker_servers'; diff --git a/packages/kbn-ui-shared-deps/theme.ts b/packages/kbn-ui-shared-deps/theme.ts index 4b2758516fc26..a810e1de0a21f 100644 --- a/packages/kbn-ui-shared-deps/theme.ts +++ b/packages/kbn-ui-shared-deps/theme.ts @@ -24,7 +24,7 @@ const globals: any = typeof window === 'undefined' ? {} : window; export type Theme = typeof LightTheme; // in the Kibana app we can rely on this global being defined, but in -// some cases (like jest, or karma tests) the global is undefined +// some cases (like jest) the global is undefined export const tag: string = globals.__kbnThemeTag__ || 'v7light'; export const version = tag.startsWith('v7') ? 7 : 8; export const darkMode = tag.endsWith('dark'); diff --git a/renovate.json5 b/renovate.json5 index ae32043daaf5f..57d0fcb9f8ce2 100644 --- a/renovate.json5 +++ b/renovate.json5 @@ -1,9 +1,3 @@ -/** - * PLEASE DO NOT MODIFY - * - * This file is automatically generated by running `node scripts/build_renovate_config` - * - */ { extends: [ 'config:base', @@ -11,11 +5,6 @@ includePaths: [ 'package.json', 'x-pack/package.json', - 'x-pack/legacy/plugins/*/package.json', - 'packages/*/package.json', - 'examples/*/package.json', - 'test/plugin_functional/plugins/*/package.json', - 'test/interpreter_functional/plugins/*/package.json', ], baseBranches: [ 'master', @@ -38,8 +27,7 @@ ], }, separateMajorMinor: false, - masterIssue: true, - masterIssueApproval: true, + masterIssue: false, rangeStrategy: 'bump', npm: { lockFileMaintenance: { @@ -48,1068 +36,12 @@ packageRules: [ { groupSlug: '@elastic/charts', - groupName: '@elastic/charts related packages', - packageNames: [ - '@elastic/charts', - '@types/elastic__charts', - ], - reviewers: [ - 'markov00', - ], - masterIssueApproval: false, - }, - { - groupSlug: '@reach/router', - groupName: '@reach/router related packages', - packageNames: [ - '@reach/router', - '@types/reach__router', - ], - }, - { - groupSlug: '@testing-library/dom', - groupName: '@testing-library/dom related packages', - packageNames: [ - '@testing-library/dom', - '@types/testing-library__dom', - ], - }, - { - groupSlug: 'angular', - groupName: 'angular related packages', - packagePatterns: [ - '(\\b|_)angular(\\b|_)', - ], - }, - { - groupSlug: 'api-documenter', - groupName: 'api-documenter related packages', - packageNames: [ - '@microsoft/api-documenter', - '@types/microsoft__api-documenter', - '@microsoft/api-extractor', - '@types/microsoft__api-extractor', - ], - enabled: false, - }, - { - groupSlug: 'archiver', - groupName: 'archiver related packages', - packageNames: [ - 'archiver', - '@types/archiver', - ], - }, - { - groupSlug: 'babel', - groupName: 'babel related packages', - packagePatterns: [ - '(\\b|_)babel(\\b|_)', - ], - packageNames: [ - 'core-js', - '@types/core-js', - '@babel/preset-react', - '@types/babel__preset-react', - '@babel/preset-typescript', - '@types/babel__preset-typescript', - ], - }, - { - groupSlug: 'base64-js', - groupName: 'base64-js related packages', - packageNames: [ - 'base64-js', - '@types/base64-js', - ], - }, - { - groupSlug: 'bluebird', - groupName: 'bluebird related packages', - packageNames: [ - 'bluebird', - '@types/bluebird', - ], - }, - { - groupSlug: 'browserslist-useragent', - groupName: 'browserslist-useragent related packages', - packageNames: [ - 'browserslist-useragent', - '@types/browserslist-useragent', - ], - }, - { - groupSlug: 'chance', - groupName: 'chance related packages', - packageNames: [ - 'chance', - '@types/chance', - ], - }, - { - groupSlug: 'cheerio', - groupName: 'cheerio related packages', - packageNames: [ - 'cheerio', - '@types/cheerio', - ], - }, - { - groupSlug: 'chroma-js', - groupName: 'chroma-js related packages', - packageNames: [ - 'chroma-js', - '@types/chroma-js', - ], - }, - { - groupSlug: 'chromedriver', - groupName: 'chromedriver related packages', - packageNames: [ - 'chromedriver', - '@types/chromedriver', - ], - }, - { - groupSlug: 'classnames', - groupName: 'classnames related packages', - packageNames: [ - 'classnames', - '@types/classnames', - ], - }, - { - groupSlug: 'cmd-shim', - groupName: 'cmd-shim related packages', - packageNames: [ - 'cmd-shim', - '@types/cmd-shim', - ], - }, - { - groupSlug: 'color', - groupName: 'color related packages', - packageNames: [ - 'color', - '@types/color', - ], - }, - { - groupSlug: 'cpy', - groupName: 'cpy related packages', - packageNames: [ - 'cpy', - '@types/cpy', - ], - }, - { - groupSlug: 'cytoscape', - groupName: 'cytoscape related packages', - packageNames: [ - 'cytoscape', - '@types/cytoscape', - ], - }, - { - groupSlug: 'd3', - groupName: 'd3 related packages', - packagePatterns: [ - '(\\b|_)d3(\\b|_)', - ], - }, - { - groupSlug: 'dedent', - groupName: 'dedent related packages', - packageNames: [ - 'dedent', - '@types/dedent', - ], - }, - { - groupSlug: 'deep-freeze-strict', - groupName: 'deep-freeze-strict related packages', - packageNames: [ - 'deep-freeze-strict', - '@types/deep-freeze-strict', - ], - }, - { - groupSlug: 'delete-empty', - groupName: 'delete-empty related packages', - packageNames: [ - 'delete-empty', - '@types/delete-empty', - ], - }, - { - groupSlug: 'dragselect', - groupName: 'dragselect related packages', - packageNames: [ - 'dragselect', - '@types/dragselect', - ], - labels: [ - 'release_note:skip', - 'Team:Operations', - 'renovate', - 'v8.0.0', - 'v7.10.0', - ':ml', - ], - }, - { - groupSlug: 'elasticsearch', - groupName: 'elasticsearch related packages', - packageNames: [ - 'elasticsearch', - '@types/elasticsearch', - ], - }, - { - groupSlug: 'eslint', - groupName: 'eslint related packages', - packagePatterns: [ - '(\\b|_)eslint(\\b|_)', - ], - }, - { - groupSlug: 'estree', - groupName: 'estree related packages', - packageNames: [ - 'estree', - '@types/estree', - ], - }, - { - groupSlug: 'fancy-log', - groupName: 'fancy-log related packages', - packageNames: [ - 'fancy-log', - '@types/fancy-log', - ], - }, - { - groupSlug: 'fetch-mock', - groupName: 'fetch-mock related packages', - packageNames: [ - 'fetch-mock', - '@types/fetch-mock', - ], - }, - { - groupSlug: 'file-saver', - groupName: 'file-saver related packages', - packageNames: [ - 'file-saver', - '@types/file-saver', - ], - }, - { - groupSlug: 'flot', - groupName: 'flot related packages', - packageNames: [ - 'flot', - '@types/flot', - ], - }, - { - groupSlug: 'geojson', - groupName: 'geojson related packages', - packageNames: [ - 'geojson', - '@types/geojson', - ], - }, - { - groupSlug: 'getopts', - groupName: 'getopts related packages', - packageNames: [ - 'getopts', - '@types/getopts', - ], - }, - { - groupSlug: 'getos', - groupName: 'getos related packages', - packageNames: [ - 'getos', - '@types/getos', - ], - }, - { - groupSlug: 'git-url-parse', - groupName: 'git-url-parse related packages', - packageNames: [ - 'git-url-parse', - '@types/git-url-parse', - ], - }, - { - groupSlug: 'glob', - groupName: 'glob related packages', - packageNames: [ - 'glob', - '@types/glob', - ], - }, - { - groupSlug: 'globby', - groupName: 'globby related packages', - packageNames: [ - 'globby', - '@types/globby', - ], - }, - { - groupSlug: 'graphql', - groupName: 'graphql related packages', - packagePatterns: [ - '(\\b|_)graphql(\\b|_)', - '(\\b|_)apollo(\\b|_)', - ], - }, - { - groupSlug: 'grunt', - groupName: 'grunt related packages', - packagePatterns: [ - '(\\b|_)grunt(\\b|_)', - ], - }, - { - groupSlug: 'gulp', - groupName: 'gulp related packages', - packagePatterns: [ - '(\\b|_)gulp(\\b|_)', - ], - }, - { - groupSlug: 'hapi', - groupName: 'hapi related packages', - packagePatterns: [ - '(\\b|_)hapi(\\b|_)', - ], - packageNames: [ - 'hapi', - '@types/hapi', - 'joi', - '@types/joi', - 'boom', - '@types/boom', - 'hoek', - '@types/hoek', - 'h2o2', - '@types/h2o2', - '@elastic/good', - '@types/elastic__good', - 'good-squeeze', - '@types/good-squeeze', - 'inert', - '@types/inert', - 'accept', - '@types/accept', - ], - }, - { - groupSlug: 'has-ansi', - groupName: 'has-ansi related packages', - packageNames: [ - 'has-ansi', - '@types/has-ansi', - ], - }, - { - groupSlug: 'he', - groupName: 'he related packages', - packageNames: [ - 'he', - '@types/he', - ], - }, - { - groupSlug: 'history', - groupName: 'history related packages', - packageNames: [ - 'history', - '@types/history', - ], - }, - { - groupSlug: 'hjson', - groupName: 'hjson related packages', - packageNames: [ - 'hjson', - '@types/hjson', - ], - }, - { - groupSlug: 'inquirer', - groupName: 'inquirer related packages', - packageNames: [ - 'inquirer', - '@types/inquirer', - ], - }, - { - groupSlug: 'intl-relativeformat', - groupName: 'intl-relativeformat related packages', - packageNames: [ - 'intl-relativeformat', - '@types/intl-relativeformat', - ], - }, - { - groupSlug: 'jest', - groupName: 'jest related packages', - packagePatterns: [ - '(\\b|_)jest(\\b|_)', - ], - }, - { - groupSlug: 'jquery', - groupName: 'jquery related packages', - packageNames: [ - 'jquery', - '@types/jquery', - ], - }, - { - groupSlug: 'js-search', - groupName: 'js-search related packages', - packageNames: [ - 'js-search', - '@types/js-search', - ], - }, - { - groupSlug: 'js-yaml', - groupName: 'js-yaml related packages', - packageNames: [ - 'js-yaml', - '@types/js-yaml', - ], - }, - { - groupSlug: 'jsdom', - groupName: 'jsdom related packages', - packageNames: [ - 'jsdom', - '@types/jsdom', - ], - }, - { - groupSlug: 'json-stable-stringify', - groupName: 'json-stable-stringify related packages', - packageNames: [ - 'json-stable-stringify', - '@types/json-stable-stringify', - ], - }, - { - groupSlug: 'json5', - groupName: 'json5 related packages', - packageNames: [ - 'json5', - '@types/json5', - ], - }, - { - groupSlug: 'jsonwebtoken', - groupName: 'jsonwebtoken related packages', - packageNames: [ - 'jsonwebtoken', - '@types/jsonwebtoken', - ], - }, - { - groupSlug: 'jsts', - groupName: 'jsts related packages', - packageNames: [ - 'jsts', - '@types/jsts', - ], - allowedVersions: '^1.6.2', - }, - { - groupSlug: 'karma', - groupName: 'karma related packages', - packagePatterns: [ - '(\\b|_)karma(\\b|_)', - ], - }, - { - groupSlug: 'language server', - groupName: 'language server related packages', - packageNames: [ - 'vscode-jsonrpc', - '@types/vscode-jsonrpc', - 'vscode-languageserver', - '@types/vscode-languageserver', - 'vscode-languageserver-types', - '@types/vscode-languageserver-types', - ], - }, - { - groupSlug: 'license-checker', - groupName: 'license-checker related packages', - packageNames: [ - 'license-checker', - '@types/license-checker', - ], - }, - { - groupSlug: 'listr', - groupName: 'listr related packages', - packageNames: [ - 'listr', - '@types/listr', - ], - }, - { - groupSlug: 'lodash', - groupName: 'lodash related packages', - packageNames: [ - 'lodash', - '@types/lodash', - ], - }, - { - groupSlug: 'log-symbols', - groupName: 'log-symbols related packages', - packageNames: [ - 'log-symbols', - '@types/log-symbols', - ], - }, - { - groupSlug: 'lru-cache', - groupName: 'lru-cache related packages', - packageNames: [ - 'lru-cache', - '@types/lru-cache', - ], - }, - { - groupSlug: 'mapbox-gl', - groupName: 'mapbox-gl related packages', - packageNames: [ - 'mapbox-gl', - '@types/mapbox-gl', - ], - }, - { - groupSlug: 'markdown-it', - groupName: 'markdown-it related packages', - packageNames: [ - 'markdown-it', - '@types/markdown-it', - ], - }, - { - groupSlug: 'memoize-one', - groupName: 'memoize-one related packages', - packageNames: [ - 'memoize-one', - '@types/memoize-one', - ], - }, - { - groupSlug: 'mime', - groupName: 'mime related packages', - packageNames: [ - 'mime', - '@types/mime', - ], - }, - { - groupSlug: 'minimatch', - groupName: 'minimatch related packages', - packageNames: [ - 'minimatch', - '@types/minimatch', - ], - }, - { - groupSlug: 'mocha', - groupName: 'mocha related packages', - packagePatterns: [ - '(\\b|_)mocha(\\b|_)', - ], - }, - { - groupSlug: 'mock-fs', - groupName: 'mock-fs related packages', - packageNames: [ - 'mock-fs', - '@types/mock-fs', - ], - }, - { - groupSlug: 'moment', - groupName: 'moment related packages', - packagePatterns: [ - '(\\b|_)moment(\\b|_)', - ], - }, - { - groupSlug: 'mustache', - groupName: 'mustache related packages', - packageNames: [ - 'mustache', - '@types/mustache', - ], - }, - { - groupSlug: 'ncp', - groupName: 'ncp related packages', - packageNames: [ - 'ncp', - '@types/ncp', - ], - }, - { - groupSlug: 'nock', - groupName: 'nock related packages', - packageNames: [ - 'nock', - '@types/nock', - ], - }, - { - groupSlug: 'node', - groupName: 'node related packages', - packageNames: [ - 'node', - '@types/node', - ], - }, - { - groupSlug: 'node-fetch', - groupName: 'node-fetch related packages', - packageNames: [ - 'node-fetch', - '@types/node-fetch', - ], - }, - { - groupSlug: 'node-forge', - groupName: 'node-forge related packages', - packageNames: [ - 'node-forge', - '@types/node-forge', - ], - }, - { - groupSlug: 'node-sass', - groupName: 'node-sass related packages', - packageNames: [ - 'node-sass', - '@types/node-sass', - ], - }, - { - groupSlug: 'nodemailer', - groupName: 'nodemailer related packages', - packageNames: [ - 'nodemailer', - '@types/nodemailer', - ], - }, - { - groupSlug: 'normalize-path', - groupName: 'normalize-path related packages', - packageNames: [ - 'normalize-path', - '@types/normalize-path', - ], - }, - { - groupSlug: 'object-hash', - groupName: 'object-hash related packages', - packageNames: [ - 'object-hash', - '@types/object-hash', - ], - }, - { - groupSlug: 'opn', - groupName: 'opn related packages', - packageNames: [ - 'opn', - '@types/opn', - ], - }, - { - groupSlug: 'ora', - groupName: 'ora related packages', - packageNames: [ - 'ora', - '@types/ora', - ], - }, - { - groupSlug: 'papaparse', - groupName: 'papaparse related packages', - packageNames: [ - 'papaparse', - '@types/papaparse', - ], - }, - { - groupSlug: 'parse-link-header', - groupName: 'parse-link-header related packages', - packageNames: [ - 'parse-link-header', - '@types/parse-link-header', - ], - }, - { - groupSlug: 'pegjs', - groupName: 'pegjs related packages', - packageNames: [ - 'pegjs', - '@types/pegjs', - ], - }, - { - groupSlug: 'pngjs', - groupName: 'pngjs related packages', - packageNames: [ - 'pngjs', - '@types/pngjs', - ], - }, - { - groupSlug: 'podium', - groupName: 'podium related packages', - packageNames: [ - 'podium', - '@types/podium', - ], - }, - { - groupSlug: 'pretty-ms', - groupName: 'pretty-ms related packages', - packageNames: [ - 'pretty-ms', - '@types/pretty-ms', - ], - }, - { - groupSlug: 'proper-lockfile', - groupName: 'proper-lockfile related packages', - packageNames: [ - 'proper-lockfile', - '@types/proper-lockfile', - ], - }, - { - groupSlug: 'puppeteer', - groupName: 'puppeteer related packages', - packageNames: [ - 'puppeteer', - '@types/puppeteer', - ], - }, - { - groupSlug: 'react', - groupName: 'react related packages', - packagePatterns: [ - '(\\b|_)react(\\b|_)', - '(\\b|_)redux(\\b|_)', - '(\\b|_)enzyme(\\b|_)', - ], - packageNames: [ - 'ngreact', - '@types/ngreact', - 'recompose', - '@types/recompose', - 'prop-types', - '@types/prop-types', - 'typescript-fsa-reducers', - '@types/typescript-fsa-reducers', - 'reselect', - '@types/reselect', - ], - }, - { - groupSlug: 'read-pkg', - groupName: 'read-pkg related packages', - packageNames: [ - 'read-pkg', - '@types/read-pkg', - ], - }, - { - groupSlug: 'reduce-reducers', - groupName: 'reduce-reducers related packages', - packageNames: [ - 'reduce-reducers', - '@types/reduce-reducers', - ], - }, - { - groupSlug: 'request', - groupName: 'request related packages', - packageNames: [ - 'request', - '@types/request', - ], - }, - { - groupSlug: 'selenium-webdriver', - groupName: 'selenium-webdriver related packages', - packageNames: [ - 'selenium-webdriver', - '@types/selenium-webdriver', - ], - }, - { - groupSlug: 'semver', - groupName: 'semver related packages', - packageNames: [ - 'semver', - '@types/semver', - ], - }, - { - groupSlug: 'set-value', - groupName: 'set-value related packages', - packageNames: [ - 'set-value', - '@types/set-value', - ], - }, - { - groupSlug: 'sinon', - groupName: 'sinon related packages', - packageNames: [ - 'sinon', - '@types/sinon', - ], - }, - { - groupSlug: 'stats-lite', - groupName: 'stats-lite related packages', - packageNames: [ - 'stats-lite', - '@types/stats-lite', - ], - }, - { - groupSlug: 'storybook', - groupName: 'storybook related packages', - packagePatterns: [ - '(\\b|_)storybook(\\b|_)', - ], - }, - { - groupSlug: 'strip-ansi', - groupName: 'strip-ansi related packages', - packageNames: [ - 'strip-ansi', - '@types/strip-ansi', - ], - }, - { - groupSlug: 'strong-log-transformer', - groupName: 'strong-log-transformer related packages', - packageNames: [ - 'strong-log-transformer', - '@types/strong-log-transformer', - ], - }, - { - groupSlug: 'styled-components', - groupName: 'styled-components related packages', - packageNames: [ - 'styled-components', - '@types/styled-components', - ], - }, - { - groupSlug: 'supertest', - groupName: 'supertest related packages', - packageNames: [ - 'supertest', - '@types/supertest', - ], - }, - { - groupSlug: 'supertest-as-promised', - groupName: 'supertest-as-promised related packages', - packageNames: [ - 'supertest-as-promised', - '@types/supertest-as-promised', - ], - }, - { - groupSlug: 'tar', - groupName: 'tar related packages', - packageNames: [ - 'tar', - '@types/tar', - ], - }, - { - groupSlug: 'tar-fs', - groupName: 'tar-fs related packages', - packageNames: [ - 'tar-fs', - '@types/tar-fs', - ], - }, - { - groupSlug: 'tempy', - groupName: 'tempy related packages', - packageNames: [ - 'tempy', - '@types/tempy', - ], - }, - { - groupSlug: 'through2', - groupName: 'through2 related packages', - packageNames: [ - 'through2', - '@types/through2', - ], - }, - { - groupSlug: 'through2-map', - groupName: 'through2-map related packages', - packageNames: [ - 'through2-map', - '@types/through2-map', - ], - }, - { - groupSlug: 'tinycolor2', - groupName: 'tinycolor2 related packages', - packageNames: [ - 'tinycolor2', - '@types/tinycolor2', - ], - }, - { - groupSlug: 'type-detect', - groupName: 'type-detect related packages', - packageNames: [ - 'type-detect', - '@types/type-detect', - ], - }, - { - groupSlug: 'typescript', - groupName: 'typescript related packages', - packagePatterns: [ - '(\\b|_)ts(\\b|_)', - '(\\b|_)typescript(\\b|_)', - ], - packageNames: [ - 'tslib', - '@types/tslib', - ], - }, - { - groupSlug: 'use-resize-observer', - groupName: 'use-resize-observer related packages', - packageNames: [ - 'use-resize-observer', - '@types/use-resize-observer', - ], - }, - { - groupSlug: 'uuid', - groupName: 'uuid related packages', - packageNames: [ - 'uuid', - '@types/uuid', - ], - }, - { - groupSlug: 'vega', - groupName: 'vega related packages', - packagePatterns: [ - '(\\b|_)vega(\\b|_)', - ], - enabled: false, - }, - { - groupSlug: 'vinyl', - groupName: 'vinyl related packages', - packageNames: [ - 'vinyl', - '@types/vinyl', - ], - }, - { - groupSlug: 'vinyl-fs', - groupName: 'vinyl-fs related packages', - packageNames: [ - 'vinyl-fs', - '@types/vinyl-fs', - ], - }, - { - groupSlug: 'watchpack', - groupName: 'watchpack related packages', - packageNames: [ - 'watchpack', - '@types/watchpack', - ], - }, - { - groupSlug: 'webpack', - groupName: 'webpack related packages', - packagePatterns: [ - '(\\b|_)webpack(\\b|_)', - '(\\b|_)loader(\\b|_)', - '(\\b|_)acorn(\\b|_)', - '(\\b|_)terser(\\b|_)', - ], - packageNames: [ - 'mini-css-extract-plugin', - '@types/mini-css-extract-plugin', - 'chokidar', - '@types/chokidar', - ], - }, - { - groupSlug: 'write-pkg', - groupName: 'write-pkg related packages', - packageNames: [ - 'write-pkg', - '@types/write-pkg', - ], - }, - { - groupSlug: 'xml-crypto', - groupName: 'xml-crypto related packages', - packageNames: [ - 'xml-crypto', - '@types/xml-crypto', - ], - }, - { - groupSlug: 'xml2js', - groupName: 'xml2js related packages', - packageNames: [ - 'xml2js', - '@types/xml2js', - ], - }, - { - groupSlug: 'zen-observable', - groupName: 'zen-observable related packages', - packageNames: [ - 'zen-observable', - '@types/zen-observable', - ], + packageNames: ['@elastic/charts'], + reviewers: ['markov00'], }, { packagePatterns: [ - '^@kbn/.*', + '.*', ], enabled: false, }, diff --git a/scripts/es_archiver.js b/scripts/es_archiver.js index faa8d9131240d..88674ce9eafb3 100755 --- a/scripts/es_archiver.js +++ b/scripts/es_archiver.js @@ -18,4 +18,4 @@ */ require('../src/setup_node_env'); -require('../src/es_archiver/cli'); +require('@kbn/es-archiver').runCli(); diff --git a/src/cli/serve/read_keystore.js b/src/cli/serve/read_keystore.js index 962c708c0d8df..38d0e68bd5c4e 100644 --- a/src/cli/serve/read_keystore.js +++ b/src/cli/serve/read_keystore.js @@ -17,14 +17,13 @@ * under the License. */ -import path from 'path'; import { set } from '@elastic/safer-lodash-set'; import { Keystore } from '../../legacy/server/keystore'; -import { getDataPath } from '../../core/server/path'; +import { getKeystore } from '../../cli_keystore/get_keystore'; -export function readKeystore(dataPath = getDataPath()) { - const keystore = new Keystore(path.join(dataPath, 'kibana.keystore')); +export function readKeystore(keystorePath = getKeystore()) { + const keystore = new Keystore(keystorePath); keystore.load(); const keys = Object.keys(keystore.data); diff --git a/src/cli/serve/read_keystore.test.js b/src/cli/serve/read_keystore.test.js index b77e51fc3033a..e5407b257a909 100644 --- a/src/cli/serve/read_keystore.test.js +++ b/src/cli/serve/read_keystore.test.js @@ -40,11 +40,17 @@ describe('cli/serve/read_keystore', () => { }); }); - it('uses data path provided', () => { - const keystoreDir = '/foo/'; - const keystorePath = path.join(keystoreDir, 'kibana.keystore'); + it('uses data path if provided', () => { + const keystorePath = path.join('/foo/', 'kibana.keystore'); - readKeystore(keystoreDir); - expect(Keystore.mock.calls[0][0]).toEqual(keystorePath); + readKeystore(keystorePath); + expect(Keystore.mock.calls[0][0]).toContain(keystorePath); + }); + + it('uses the getKeystore path if not', () => { + readKeystore(); + // we test exact path scenarios in get_keystore.test.js - we use both + // deprecated and new to cover any older local environments + expect(Keystore.mock.calls[0][0]).toMatch(/data|config/); }); }); diff --git a/src/core/MIGRATION.md b/src/core/MIGRATION.md index f7acff14915a7..72945597758e2 100644 --- a/src/core/MIGRATION.md +++ b/src/core/MIGRATION.md @@ -1620,14 +1620,6 @@ If others are consuming your plugin's new platform contracts via the `ui/new_pla > Note: The `ui/new_platform` mock is only designed for use by old Jest tests. If you are writing new tests, you should structure your code and tests such that you don't need this mock. Instead, you should import the `core` mock directly and instantiate it. -#### What about karma tests? - -While our plan is to only provide first-class mocks for Jest tests, there are many legacy karma tests that cannot be quickly or easily converted to Jest -- particularly those which are still relying on mocking Angular services via `ngMock`. - -For these tests, we are maintaining a separate set of mocks. Files with a `.karma_mock.{js|ts|tsx}` extension will be loaded _globally_ before karma tests are run. - -It is important to note that this behavior is different from `jest.mock('ui/new_platform')`, which only mocks tests on an individual basis. If you encounter any failures in karma tests as a result of new platform migration efforts, you may need to add a `.karma_mock.js` file for the affected services, or add to the existing karma mock we are maintaining in `ui/new_platform`. - ### Provide Legacy Platform API to the New platform plugin #### On the server side diff --git a/src/core/MIGRATION_EXAMPLES.md b/src/core/MIGRATION_EXAMPLES.md index 6bb5a845ea2ab..d630fec652a37 100644 --- a/src/core/MIGRATION_EXAMPLES.md +++ b/src/core/MIGRATION_EXAMPLES.md @@ -27,6 +27,10 @@ APIs to their New Platform equivalents. - [Changes in structure compared to legacy](#changes-in-structure-compared-to-legacy) - [Remarks](#remarks) - [UiSettings](#uisettings) + - [Elasticsearch client](#elasticsearch-client) + - [Client API Changes](#client-api-changes) + - [Accessing the client from a route handler](#accessing-the-client-from-a-route-handler) + - [Creating a custom client](#creating-a-custom-client) ## Configuration @@ -1003,4 +1007,259 @@ setup(core: CoreSetup){ }, }) } -``` \ No newline at end of file +``` + +## Elasticsearch client + +The new elasticsearch client is a thin wrapper around `@elastic/elasticsearch`'s `Client` class. Even if the API +is quite close to the legacy client Kibana was previously using, there are some subtle changes to take into account +during migration. + +[Official documentation](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html) + +### Client API Changes + +The most significant changes for the consumers are the following: + +- internal / current user client accessors has been renamed and are now properties instead of functions + - `callAsInternalUser('ping')` -> `asInternalUser.ping()` + - `callAsCurrentUser('ping')` -> `asCurrentUser.ping()` + +- the API now reflects the `Client`'s instead of leveraging the string-based endpoint names the `LegacyAPICaller` was using + +before: + +```ts +const body = await client.callAsInternalUser('indices.get', { index: 'id' }); +``` + +after: + +```ts +const { body } = await client.asInternalUser.indices.get({ index: 'id' }); +``` + +- calling any ES endpoint now returns the whole response object instead of only the body payload + +before: + +```ts +const body = await legacyClient.callAsInternalUser('get', { id: 'id' }); +``` + +after: + +```ts +const { body } = await client.asInternalUser.get({ id: 'id' }); +``` + +Note that more information from the ES response is available: + +```ts +const { + body, // response payload + statusCode, // http status code of the response + headers, // response headers + warnings, // warnings returned from ES + meta // meta information about the request, such as request parameters, number of attempts and so on +} = await client.asInternalUser.get({ id: 'id' }); +``` + +- all API methods are now generic to allow specifying the response body type + +before: + +```ts +const body: GetResponse = await legacyClient.callAsInternalUser('get', { id: 'id' }); +``` + +after: + +```ts +// body is of type `GetResponse` +const { body } = await client.asInternalUser.get({ id: 'id' }); +// fallback to `Record` if unspecified +const { body } = await client.asInternalUser.get({ id: 'id' }); +``` + +- the returned error types changed + +There are no longer specific errors for every HTTP status code (such as `BadRequest` or `NotFound`). A generic +`ResponseError` with the specific `statusCode` is thrown instead. + +before: + +```ts +import { errors } from 'elasticsearch'; +try { + await legacyClient.callAsInternalUser('ping'); +} catch(e) { + if(e instanceof errors.NotFound) { + // do something + } +} +``` + +after: + +```ts +import { errors } from '@elastic/elasticsearch'; +try { + await client.asInternalUser.ping(); +} catch(e) { + if(e instanceof errors.ResponseError && e.statusCode === 404) { + // do something + } + // also possible, as all errors got a name property with the name of the class, + // so this slightly better in term of performances + if(e.name === 'ResponseError' && e.statusCode === 404) { + // do something + } +} +``` + +- the parameter property names changed from camelCase to snake_case + +Even if technically, the javascript client accepts both formats, the typescript definitions are only defining the snake_case +properties. + +before: + +```ts +legacyClient.callAsCurrentUser('get', { + id: 'id', + storedFields: ['some', 'fields'], +}) +``` + +after: + +```ts +client.asCurrentUser.get({ + id: 'id', + stored_fields: ['some', 'fields'], +}) +``` + +- the request abortion API changed + +All promises returned from the client API calls now have an `abort` method that can be used to cancel the request. + +before: + +```ts +const controller = new AbortController(); +legacyClient.callAsCurrentUser('ping', {}, { + signal: controller.signal, +}) +// later +controller.abort(); +``` + +after: + +```ts +const request = client.asCurrentUser.ping(); +// later +request.abort(); +``` + +- it is now possible to override headers when performing specific API calls. + +Note that doing so is strongly discouraged due to potential side effects with the ES service internal +behavior when scoping as the internal or as the current user. + +```ts +const request = client.asCurrentUser.ping({}, { + headers: { + authorization: 'foo', + custom: 'bar', + } +}); +``` + +Please refer to the [Breaking changes list](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/breaking-changes.html) +for more information about the changes between the legacy and new client. + +### Accessing the client from a route handler + +Apart from the API format change, accessing the client from within a route handler +did not change. As it was done for the legacy client, a preconfigured scoped client +bound to the request is accessible using `core` context provider: + +before: + +```ts +router.get( + { + path: '/my-route', + }, + async (context, req, res) => { + const { client } = context.core.elasticsearch.legacy; + // call as current user + const res = await client.callAsCurrentUser('ping'); + // call as internal user + const res2 = await client.callAsInternalUser('search', options); + return res.ok({ body: 'ok' }); + } +); +``` + +after: + +```ts +router.get( + { + path: '/my-route', + }, + async (context, req, res) => { + const { client } = context.core.elasticsearch; + // call as current user + const res = await client.asCurrentUser.ping(); + // call as internal user + const res2 = await client.asInternalUser.search(options); + return res.ok({ body: 'ok' }); + } +); +``` + +### Creating a custom client + +Note that the `plugins` option is now longer available on the new client. As the API is now exhaustive, adding custom +endpoints using plugins should no longer be necessary. + +The API to create custom clients did not change much: + +before: + +```ts +const customClient = coreStart.elasticsearch.legacy.createClient('my-custom-client', customConfig); +// do something with the client, such as +await customClient.callAsInternalUser('ping'); +// custom client are closable +customClient.close(); +``` + +after: + +```ts +const customClient = coreStart.elasticsearch.createClient('my-custom-client', customConfig); +// do something with the client, such as +await customClient.asInternalUser.ping(); +// custom client are closable +customClient.close(); +``` + +If, for any reasons, one still needs to reach an endpoint not listed on the client API, using `request.transport` +is still possible: + +```ts +const { body } = await client.asCurrentUser.transport.request({ + method: 'get', + path: '/my-custom-endpoint', + body: { my: 'payload'}, + querystring: { param: 'foo' } +}) +``` + +Remark: the new client creation API is now only available from the `start` contract of the elasticsearch service. diff --git a/src/core/public/core_app/core_app.ts b/src/core/public/core_app/core_app.ts index 04d58b7c3c65c..ef6ea0a0e1050 100644 --- a/src/core/public/core_app/core_app.ts +++ b/src/core/public/core_app/core_app.ts @@ -24,15 +24,19 @@ import { AppNavLinkStatus, AppMountParameters, } from '../application'; -import { HttpSetup, HttpStart } from '../http'; -import { CoreContext } from '../core_system'; -import { renderApp, setupUrlOverflowDetection } from './errors'; -import { NotificationsStart } from '../notifications'; -import { IUiSettingsClient } from '../ui_settings'; +import type { HttpSetup, HttpStart } from '../http'; +import type { CoreContext } from '../core_system'; +import type { NotificationsSetup, NotificationsStart } from '../notifications'; +import type { IUiSettingsClient } from '../ui_settings'; +import type { InjectedMetadataSetup } from '../injected_metadata'; +import { renderApp as renderErrorApp, setupUrlOverflowDetection } from './errors'; +import { renderApp as renderStatusApp } from './status'; interface SetupDeps { application: InternalApplicationSetup; http: HttpSetup; + injectedMetadata: InjectedMetadataSetup; + notifications: NotificationsSetup; } interface StartDeps { @@ -47,7 +51,7 @@ export class CoreApp { constructor(private readonly coreContext: CoreContext) {} - public setup({ http, application }: SetupDeps) { + public setup({ http, application, injectedMetadata, notifications }: SetupDeps) { application.register(this.coreContext.coreId, { id: 'error', title: 'App Error', @@ -56,7 +60,21 @@ export class CoreApp { // Do not use an async import here in order to ensure that network failures // cannot prevent the error UI from displaying. This UI is tiny so an async // import here is probably not useful anyways. - return renderApp(params, { basePath: http.basePath }); + return renderErrorApp(params, { basePath: http.basePath }); + }, + }); + + if (injectedMetadata.getAnonymousStatusPage()) { + http.anonymousPaths.register('/status'); + } + application.register(this.coreContext.coreId, { + id: 'status', + title: 'Server Status', + appRoute: '/status', + chromeless: true, + navLinkStatus: AppNavLinkStatus.hidden, + mount(params: AppMountParameters) { + return renderStatusApp(params, { http, notifications }); }, }); } diff --git a/src/core/public/core_app/status/components/__snapshots__/metric_tiles.test.tsx.snap b/src/core/public/core_app/status/components/__snapshots__/metric_tiles.test.tsx.snap new file mode 100644 index 0000000000000..2219e0d7609b8 --- /dev/null +++ b/src/core/public/core_app/status/components/__snapshots__/metric_tiles.test.tsx.snap @@ -0,0 +1,37 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`MetricTile correct displays a byte metric 1`] = ` + +`; + +exports[`MetricTile correct displays a float metric 1`] = ` + +`; + +exports[`MetricTile correct displays a time metric 1`] = ` + +`; + +exports[`MetricTile correct displays an untyped metric 1`] = ` + +`; diff --git a/src/core/public/core_app/status/components/__snapshots__/server_status.test.tsx.snap b/src/core/public/core_app/status/components/__snapshots__/server_status.test.tsx.snap new file mode 100644 index 0000000000000..0ed784ef680f7 --- /dev/null +++ b/src/core/public/core_app/status/components/__snapshots__/server_status.test.tsx.snap @@ -0,0 +1,67 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`ServerStatus renders correctly for green state 2`] = ` + + + + + + Green + + + + + +`; + +exports[`ServerStatus renders correctly for red state 2`] = ` + + + + + + Red + + + + + +`; diff --git a/src/legacy/core_plugins/status_page/public/components/__snapshots__/status_table.test.js.snap b/src/core/public/core_app/status/components/__snapshots__/status_table.test.tsx.snap similarity index 89% rename from src/legacy/core_plugins/status_page/public/components/__snapshots__/status_table.test.js.snap rename to src/core/public/core_app/status/components/__snapshots__/status_table.test.tsx.snap index 3379d6cd649c4..f5d3b837ce718 100644 --- a/src/legacy/core_plugins/status_page/public/components/__snapshots__/status_table.test.js.snap +++ b/src/core/public/core_app/status/components/__snapshots__/status_table.test.tsx.snap @@ -1,6 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`render 1`] = ` +exports[`StatusTable renders when statuses is provided 1`] = ` { - const component = shallow(); - expect(component).toMatchSnapshot(); -}); +describe('MetricTile', () => { + it('correct displays an untyped metric', () => { + const component = shallow(); + expect(component).toMatchSnapshot(); + }); -test('byte metric', () => { - const component = shallow(); - expect(component).toMatchSnapshot(); -}); + it('correct displays a byte metric', () => { + const component = shallow(); + expect(component).toMatchSnapshot(); + }); -test('float metric', () => { - const component = shallow(); - expect(component).toMatchSnapshot(); -}); + it('correct displays a float metric', () => { + const component = shallow(); + expect(component).toMatchSnapshot(); + }); -test('millisecond metric', () => { - const component = shallow(); - expect(component).toMatchSnapshot(); + it('correct displays a time metric', () => { + const component = shallow(); + expect(component).toMatchSnapshot(); + }); }); diff --git a/src/legacy/core_plugins/status_page/public/components/metric_tiles.js b/src/core/public/core_app/status/components/metric_tiles.tsx similarity index 50% rename from src/legacy/core_plugins/status_page/public/components/metric_tiles.js rename to src/core/public/core_app/status/components/metric_tiles.tsx index 6cde975875ad1..4b1b5fcbc633d 100644 --- a/src/legacy/core_plugins/status_page/public/components/metric_tiles.js +++ b/src/core/public/core_app/status/components/metric_tiles.tsx @@ -17,53 +17,43 @@ * under the License. */ -import formatNumber from '../lib/format_number'; -import React, { Component } from 'react'; -import { Metric as MetricPropType } from '../lib/prop_types'; -import PropTypes from 'prop-types'; +import React, { FunctionComponent } from 'react'; import { EuiFlexGrid, EuiFlexItem, EuiCard } from '@elastic/eui'; +import { formatNumber, Metric } from '../lib'; /* -Displays a metric with the correct format. -*/ -export class MetricTile extends Component { - static propTypes = { - metric: MetricPropType.isRequired, - }; - - formattedMetric() { - const { value, type } = this.props.metric; - - const metrics = [].concat(value); - return metrics - .map(function (metric) { - return formatNumber(metric, type); - }) - .join(', '); - } - - render() { - const { name } = this.props.metric; - - return ; - } -} + * Displays a metric with the correct format. + */ +export const MetricTile: FunctionComponent<{ metric: Metric }> = ({ metric }) => { + const { name } = metric; + return ( + + ); +}; /* -Wrapper component that simply maps each metric to MetricTile inside a FlexGroup -*/ -const MetricTiles = ({ metrics }) => ( + * Wrapper component that simply maps each metric to MetricTile inside a FlexGroup + */ +export const MetricTiles: FunctionComponent<{ metrics: Metric[] }> = ({ metrics }) => ( {metrics.map((metric) => ( - + ))} ); -MetricTiles.propTypes = { - metrics: PropTypes.arrayOf(MetricPropType).isRequired, +const formatMetric = ({ value, type }: Metric) => { + const metrics = Array.isArray(value) ? value : [value]; + return metrics.map((metric) => formatNumber(metric, type)).join(', '); }; -export default MetricTiles; +const formatMetricId = ({ name }: Metric) => { + return name.toLowerCase().replace(/[ ]+/g, '-'); +}; diff --git a/src/core/public/core_app/status/components/server_status.test.tsx b/src/core/public/core_app/status/components/server_status.test.tsx new file mode 100644 index 0000000000000..a37697b6ab4e6 --- /dev/null +++ b/src/core/public/core_app/status/components/server_status.test.tsx @@ -0,0 +1,58 @@ +/* + * 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 { mount } from 'enzyme'; +import { ServerStatus } from './server_status'; +import { FormattedStatus } from '../lib'; + +const getStatus = (parts: Partial = {}): FormattedStatus['state'] => ({ + id: 'green', + title: 'Green', + uiColor: 'secondary', + message: '', + ...parts, +}); + +describe('ServerStatus', () => { + it('renders correctly for green state', () => { + const status = getStatus(); + const component = mount(); + expect(component.find('EuiTitle').text()).toMatchInlineSnapshot(`"Kibana status is Green"`); + expect(component.find('EuiBadge')).toMatchSnapshot(); + }); + + it('renders correctly for red state', () => { + const status = getStatus({ + id: 'red', + title: 'Red', + }); + const component = mount(); + expect(component.find('EuiTitle').text()).toMatchInlineSnapshot(`"Kibana status is Red"`); + expect(component.find('EuiBadge')).toMatchSnapshot(); + }); + + it('displays the correct `name`', () => { + let component = mount(); + expect(component.find('EuiText').text()).toMatchInlineSnapshot(`"Localhost"`); + + component = mount(); + expect(component.find('EuiText').text()).toMatchInlineSnapshot(`"Kibana"`); + }); +}); diff --git a/src/legacy/core_plugins/status_page/public/components/server_status.js b/src/core/public/core_app/status/components/server_status.tsx similarity index 66% rename from src/legacy/core_plugins/status_page/public/components/server_status.js rename to src/core/public/core_app/status/components/server_status.tsx index 0c32109b94645..5baa97cfabeda 100644 --- a/src/legacy/core_plugins/status_page/public/components/server_status.js +++ b/src/core/public/core_app/status/components/server_status.tsx @@ -17,22 +17,34 @@ * under the License. */ -import React from 'react'; -import PropTypes from 'prop-types'; -import { State as StatePropType } from '../lib/prop_types'; +import React, { FunctionComponent } from 'react'; import { EuiText, EuiFlexGroup, EuiFlexItem, EuiTitle, EuiBadge } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; +import type { FormattedStatus } from '../lib'; -const ServerState = ({ name, serverState }) => ( +interface ServerStateProps { + name: string; + serverState: FormattedStatus['state']; +} + +export const ServerStatus: FunctionComponent = ({ name, serverState }) => ( -

+

{serverState.title}, + kibanaStatus: ( + + {serverState.title} + + ), }} />

@@ -45,10 +57,3 @@ const ServerState = ({ name, serverState }) => (
); - -ServerState.propTypes = { - name: PropTypes.string.isRequired, - serverState: StatePropType.isRequired, -}; - -export default ServerState; diff --git a/src/legacy/core_plugins/status_page/public/components/status_table.test.js b/src/core/public/core_app/status/components/status_table.test.tsx similarity index 67% rename from src/legacy/core_plugins/status_page/public/components/status_table.test.js rename to src/core/public/core_app/status/components/status_table.test.tsx index 303be0d17c79d..4e25d274463ea 100644 --- a/src/legacy/core_plugins/status_page/public/components/status_table.test.js +++ b/src/core/public/core_app/status/components/status_table.test.tsx @@ -19,20 +19,23 @@ import React from 'react'; import { shallow } from 'enzyme'; -import StatusTable from './status_table'; +import { StatusTable } from './status_table'; -const STATE = { +const state = { id: 'green', uiColor: 'secondary', message: 'Ready', + title: 'green', }; -test('render', () => { - const component = shallow(); - expect(component).toMatchSnapshot(); // eslint-disable-line -}); +describe('StatusTable', () => { + it('renders when statuses is provided', () => { + const component = shallow(); + expect(component).toMatchSnapshot(); + }); -test('render empty', () => { - const component = shallow(); - expect(component.isEmptyRender()).toBe(true); // eslint-disable-line + it('renders when statuses is not provided', () => { + const component = shallow(); + expect(component.isEmptyRender()).toBe(true); + }); }); diff --git a/src/core/public/core_app/status/components/status_table.tsx b/src/core/public/core_app/status/components/status_table.tsx new file mode 100644 index 0000000000000..c1d66cc779ccd --- /dev/null +++ b/src/core/public/core_app/status/components/status_table.tsx @@ -0,0 +1,67 @@ +/* + * 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, { FunctionComponent } from 'react'; +import { EuiBasicTable, EuiIcon } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import type { FormattedStatus } from '../lib'; + +interface StatusTableProps { + statuses?: FormattedStatus[]; +} + +const tableColumns = [ + { + field: 'state', + name: '', + render: (state: FormattedStatus['state']) => ( + + ), + width: '32px', + }, + { + field: 'id', + name: i18n.translate('core.statusPage.statusTable.columns.idHeader', { + defaultMessage: 'ID', + }), + }, + { + field: 'state', + name: i18n.translate('core.statusPage.statusTable.columns.statusHeader', { + defaultMessage: 'Status', + }), + render: (state: FormattedStatus['state']) => {state.message}, + }, +]; + +export const StatusTable: FunctionComponent = ({ statuses }) => { + if (!statuses) { + return null; + } + return ( + + columns={tableColumns} + items={statuses} + rowProps={({ state }) => ({ + className: `status-table-row-${state.uiColor}`, + })} + data-test-subj="statusBreakdown" + /> + ); +}; diff --git a/packages/kbn-plugin-helpers/src/tasks/test/all/index.ts b/src/core/public/core_app/status/index.ts similarity index 95% rename from packages/kbn-plugin-helpers/src/tasks/test/all/index.ts rename to src/core/public/core_app/status/index.ts index be8db50825fc9..938a037ae60e5 100644 --- a/packages/kbn-plugin-helpers/src/tasks/test/all/index.ts +++ b/src/core/public/core_app/status/index.ts @@ -17,4 +17,4 @@ * under the License. */ -export * from './test_all_task'; +export { renderApp } from './render_app'; diff --git a/src/legacy/core_plugins/status_page/public/lib/format_number.test.js b/src/core/public/core_app/status/lib/format_number.test.ts similarity index 61% rename from src/legacy/core_plugins/status_page/public/lib/format_number.test.js rename to src/core/public/core_app/status/lib/format_number.test.ts index f70377dcba241..a3b602d210b74 100644 --- a/src/legacy/core_plugins/status_page/public/lib/format_number.test.js +++ b/src/core/public/core_app/status/lib/format_number.test.ts @@ -17,7 +17,7 @@ * under the License. */ -import formatNumber from './format_number'; +import { formatNumber } from './format_number'; describe('format byte', () => { test('zero', () => { @@ -33,17 +33,17 @@ describe('format byte', () => { }); }); -describe('format ms', () => { +describe('format time', () => { test('zero', () => { - expect(formatNumber(0, 'ms')).toMatchInlineSnapshot(`"0.00 ms"`); + expect(formatNumber(0, 'time')).toMatchInlineSnapshot(`"0.00 ms"`); }); test('sub ms', () => { - expect(formatNumber(0.128, 'ms')).toMatchInlineSnapshot(`"0.13 ms"`); + expect(formatNumber(0.128, 'time')).toMatchInlineSnapshot(`"0.13 ms"`); }); test('many ms', () => { - expect(formatNumber(3030.284, 'ms')).toMatchInlineSnapshot(`"3030.28 ms"`); + expect(formatNumber(3030.284, 'time')).toMatchInlineSnapshot(`"3030.28 ms"`); }); }); @@ -60,3 +60,31 @@ describe('format integer', () => { expect(formatNumber(3030.284, 'integer')).toMatchInlineSnapshot(`"3030"`); }); }); + +describe('format float', () => { + test('zero', () => { + expect(formatNumber(0, 'float')).toMatchInlineSnapshot(`"0.00"`); + }); + + test('sub integer', () => { + expect(formatNumber(0.728, 'float')).toMatchInlineSnapshot(`"0.73"`); + }); + + test('many integer', () => { + expect(formatNumber(3030.284, 'float')).toMatchInlineSnapshot(`"3030.28"`); + }); +}); + +describe('format default', () => { + test('zero', () => { + expect(formatNumber(0)).toMatchInlineSnapshot(`"0.00"`); + }); + + test('sub integer', () => { + expect(formatNumber(0.464)).toMatchInlineSnapshot(`"0.46"`); + }); + + test('many integer', () => { + expect(formatNumber(6237.291)).toMatchInlineSnapshot(`"6237.29"`); + }); +}); diff --git a/src/legacy/core_plugins/status_page/public/lib/format_number.js b/src/core/public/core_app/status/lib/format_number.ts similarity index 78% rename from src/legacy/core_plugins/status_page/public/lib/format_number.js rename to src/core/public/core_app/status/lib/format_number.ts index 4a8be4fc48a15..bfd5a4746b4d9 100644 --- a/src/legacy/core_plugins/status_page/public/lib/format_number.js +++ b/src/core/public/core_app/status/lib/format_number.ts @@ -19,19 +19,25 @@ import numeral from '@elastic/numeral'; -export default function formatNumber(num, which) { - let format = '0.00'; +export type DataType = 'byte' | 'float' | 'integer' | 'time'; + +export function formatNumber(num: number, type?: DataType) { + let format: string; let postfix = ''; - switch (which) { + switch (type) { case 'byte': - format += ' b'; + format = '0.00 b'; break; - case 'ms': + case 'time': + format = '0.00'; postfix = ' ms'; break; case 'integer': format = '0'; break; + case 'float': + default: + format = '0.00'; } return numeral(num).format(format) + postfix; diff --git a/src/core/public/core_app/status/lib/index.ts b/src/core/public/core_app/status/lib/index.ts new file mode 100644 index 0000000000000..eaa4e2ae4821f --- /dev/null +++ b/src/core/public/core_app/status/lib/index.ts @@ -0,0 +1,21 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export { formatNumber, DataType } from './format_number'; +export { loadStatus, Metric, FormattedStatus, ProcessedServerResponse } from './load_status'; diff --git a/src/core/public/core_app/status/lib/load_status.test.ts b/src/core/public/core_app/status/lib/load_status.test.ts new file mode 100644 index 0000000000000..3a444a4448467 --- /dev/null +++ b/src/core/public/core_app/status/lib/load_status.test.ts @@ -0,0 +1,152 @@ +/* + * 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 { StatusResponse } from '../../../../types/status'; +import { httpServiceMock } from '../../../http/http_service.mock'; +import { notificationServiceMock } from '../../../notifications/notifications_service.mock'; +import { loadStatus } from './load_status'; + +const mockedResponse: StatusResponse = { + name: 'My computer', + uuid: 'uuid', + version: { + number: '8.0.0', + build_hash: '9007199254740991', + build_number: '12', + build_snapshot: 'XXXXXXXX', + }, + status: { + overall: { + id: 'overall', + state: 'yellow', + title: 'Yellow', + message: 'yellow', + uiColor: 'secondary', + }, + statuses: [ + { + id: 'plugin:1', + state: 'green', + title: 'Green', + message: 'Ready', + uiColor: 'secondary', + }, + { + id: 'plugin:2', + state: 'yellow', + title: 'Yellow', + message: 'Something is weird', + uiColor: 'warning', + }, + ], + }, + metrics: { + collection_interval_in_millis: 1000, + os: { + platform: 'darwin' as const, + platformRelease: 'test', + memory: { total_in_bytes: 1, free_in_bytes: 1, used_in_bytes: 1 }, + uptime_in_millis: 1, + load: { + '1m': 4.1, + '5m': 2.1, + '15m': 0.1, + }, + }, + process: { + memory: { + heap: { + size_limit: 1000000, + used_in_bytes: 100, + total_in_bytes: 0, + }, + resident_set_size_in_bytes: 1, + }, + event_loop_delay: 1, + pid: 1, + uptime_in_millis: 1, + }, + response_times: { + avg_in_millis: 4000, + max_in_millis: 8000, + }, + requests: { + disconnects: 1, + total: 400, + statusCodes: {}, + }, + concurrent_connections: 1, + }, +}; + +describe('response processing', () => { + let http: ReturnType; + let notifications: ReturnType; + + beforeEach(() => { + http = httpServiceMock.createSetupContract(); + http.get.mockResolvedValue(mockedResponse); + notifications = notificationServiceMock.createSetupContract(); + }); + + test('includes the name', async () => { + const data = await loadStatus({ http, notifications }); + expect(data.name).toEqual('My computer'); + }); + + test('includes the plugin statuses', async () => { + const data = await loadStatus({ http, notifications }); + expect(data.statuses).toEqual([ + { + id: 'plugin:1', + state: { id: 'green', title: 'Green', message: 'Ready', uiColor: 'secondary' }, + }, + { + id: 'plugin:2', + state: { id: 'yellow', title: 'Yellow', message: 'Something is weird', uiColor: 'warning' }, + }, + ]); + }); + + test('includes the serverState', async () => { + const data = await loadStatus({ http, notifications }); + expect(data.serverState).toEqual({ + id: 'yellow', + title: 'Yellow', + message: 'yellow', + uiColor: 'secondary', + }); + }); + + test('builds the metrics', async () => { + const data = await loadStatus({ http, notifications }); + const names = data.metrics.map((m) => m.name); + expect(names).toEqual([ + 'Heap total', + 'Heap used', + 'Load', + 'Response time avg', + 'Response time max', + 'Requests per second', + ]); + + const values = data.metrics.map((m) => m.value); + expect(values).toEqual([1000000, 100, [4.1, 2.1, 0.1], 4000, 8000, 400]); + }); +}); diff --git a/src/core/public/core_app/status/lib/load_status.ts b/src/core/public/core_app/status/lib/load_status.ts new file mode 100644 index 0000000000000..95efa0bb87ae6 --- /dev/null +++ b/src/core/public/core_app/status/lib/load_status.ts @@ -0,0 +1,153 @@ +/* + * 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 { i18n } from '@kbn/i18n'; +import type { UnwrapPromise } from '@kbn/utility-types'; +import type { ServerStatus, StatusResponse } from '../../../../types/status'; +import type { HttpSetup } from '../../../http'; +import type { NotificationsSetup } from '../../../notifications'; +import type { DataType } from '../lib'; + +export interface Metric { + name: string; + value: number | number[]; + type?: DataType; +} + +export interface FormattedStatus { + id: string; + state: { + id: string; + title: string; + message: string; + uiColor: string; + }; +} + +/** + * Returns an object of any keys that should be included for metrics. + */ +function formatMetrics({ metrics }: StatusResponse): Metric[] { + if (!metrics) { + return []; + } + + return [ + { + name: i18n.translate('core.statusPage.metricsTiles.columns.heapTotalHeader', { + defaultMessage: 'Heap total', + }), + value: metrics.process.memory.heap.size_limit, + type: 'byte', + }, + { + name: i18n.translate('core.statusPage.metricsTiles.columns.heapUsedHeader', { + defaultMessage: 'Heap used', + }), + value: metrics.process.memory.heap.used_in_bytes, + type: 'byte', + }, + { + name: i18n.translate('core.statusPage.metricsTiles.columns.loadHeader', { + defaultMessage: 'Load', + }), + value: [metrics.os.load['1m'], metrics.os.load['5m'], metrics.os.load['15m']], + type: 'time', + }, + { + name: i18n.translate('core.statusPage.metricsTiles.columns.resTimeAvgHeader', { + defaultMessage: 'Response time avg', + }), + value: metrics.response_times.avg_in_millis, + type: 'time', + }, + { + name: i18n.translate('core.statusPage.metricsTiles.columns.resTimeMaxHeader', { + defaultMessage: 'Response time max', + }), + value: metrics.response_times.max_in_millis, + type: 'time', + }, + { + name: i18n.translate('core.statusPage.metricsTiles.columns.requestsPerSecHeader', { + defaultMessage: 'Requests per second', + }), + value: (metrics.requests.total * 1000) / metrics.collection_interval_in_millis, + type: 'float', + }, + ]; +} + +/** + * Reformat the backend data to make the frontend views simpler. + */ +function formatStatus(status: ServerStatus): FormattedStatus { + return { + id: status.id, + state: { + id: status.state, + title: status.title, + message: status.message, + uiColor: status.uiColor, + }, + }; +} + +/** + * Get the status from the server API and format it for display. + */ +export async function loadStatus({ + http, + notifications, +}: { + http: HttpSetup; + notifications: NotificationsSetup; +}) { + let response: StatusResponse; + + try { + response = await http.get('/api/status'); + } catch (e) { + if ((e.response?.status ?? 0) >= 400) { + notifications.toasts.addDanger( + i18n.translate('core.statusPage.loadStatus.serverStatusCodeErrorMessage', { + defaultMessage: 'Failed to request server status with status code {responseStatus}', + values: { responseStatus: e.response?.status }, + }) + ); + } else { + notifications.toasts.addDanger( + i18n.translate('core.statusPage.loadStatus.serverIsDownErrorMessage', { + defaultMessage: 'Failed to request server status. Perhaps your server is down?', + }) + ); + } + throw e; + } + + return { + name: response.name, + version: response.version, + statuses: response.status.statuses.map(formatStatus), + serverState: formatStatus(response.status.overall).state, + metrics: formatMetrics(response), + }; +} + +export type ProcessedServerResponse = UnwrapPromise>; diff --git a/src/core/public/core_app/status/render_app.tsx b/src/core/public/core_app/status/render_app.tsx new file mode 100644 index 0000000000000..fdec85942b964 --- /dev/null +++ b/src/core/public/core_app/status/render_app.tsx @@ -0,0 +1,44 @@ +/* + * 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 ReactDOM from 'react-dom'; +import { I18nProvider } from '@kbn/i18n/react'; +import type { AppMountParameters } from '../../application'; +import type { HttpSetup } from '../../http'; +import type { NotificationsSetup } from '../../notifications'; +import { StatusApp } from './status_app'; + +interface Deps { + http: HttpSetup; + notifications: NotificationsSetup; +} + +export const renderApp = ({ element }: AppMountParameters, { http, notifications }: Deps) => { + ReactDOM.render( + + + , + element + ); + + return () => { + ReactDOM.unmountComponentAtNode(element); + }; +}; diff --git a/src/legacy/core_plugins/status_page/public/components/status_app.js b/src/core/public/core_app/status/status_app.tsx similarity index 67% rename from src/legacy/core_plugins/status_page/public/components/status_app.js rename to src/core/public/core_app/status/status_app.tsx index a6b0321e53a8f..5ead0d39d72c2 100644 --- a/src/legacy/core_plugins/status_page/public/components/status_app.js +++ b/src/core/public/core_app/status/status_app.tsx @@ -17,10 +17,7 @@ * under the License. */ -import loadStatus from '../lib/load_status'; - import React, { Component } from 'react'; -import PropTypes from 'prop-types'; import { EuiLoadingSpinner, EuiText, @@ -33,19 +30,25 @@ import { EuiFlexItem, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; +import { HttpSetup } from '../../http'; +import { NotificationsSetup } from '../../notifications'; +import { loadStatus, ProcessedServerResponse } from './lib'; +import { MetricTiles, StatusTable, ServerStatus } from './components'; + +interface StatusAppProps { + http: HttpSetup; + notifications: NotificationsSetup; +} -import MetricTiles from './metric_tiles'; -import StatusTable from './status_table'; -import ServerStatus from './server_status'; - -class StatusApp extends Component { - static propTypes = { - buildNum: PropTypes.number.isRequired, - buildSha: PropTypes.string.isRequired, - }; +interface StatusAppState { + loading: boolean; + fetchError: boolean; + data: ProcessedServerResponse | null; +} - constructor() { - super(); +export class StatusApp extends Component { + constructor(props: StatusAppProps) { + super(props); this.state = { loading: true, fetchError: false, @@ -53,18 +56,17 @@ class StatusApp extends Component { }; } - componentDidMount = async function () { - const data = await loadStatus(); - - if (data) { - this.setState({ loading: false, data: data }); - } else { - this.setState({ fetchError: true, loading: false }); + async componentDidMount() { + const { http, notifications } = this.props; + try { + const data = await loadStatus({ http, notifications }); + this.setState({ loading: false, fetchError: false, data }); + } catch (e) { + this.setState({ fetchError: true, loading: false, data: null }); } - }; + } render() { - const { buildNum, buildSha } = this.props; const { loading, fetchError, data } = this.state; // If we're still loading, return early with a spinner @@ -76,7 +78,7 @@ class StatusApp extends Component { return ( @@ -84,10 +86,11 @@ class StatusApp extends Component { } // Extract the items needed to render each component - const { metrics, statuses, serverState, name } = data; + const { metrics, statuses, serverState, name, version } = data!; + const { build_hash: buildHash, build_number: buildNumber } = version; return ( - + @@ -103,7 +106,7 @@ class StatusApp extends Component {

@@ -113,12 +116,12 @@ class StatusApp extends Component { -

+

{buildNum}, + buildNum: {buildNumber}, }} />

@@ -126,12 +129,12 @@ class StatusApp extends Component {
-

+

{buildSha}, + buildSha: {buildHash}, }} />

@@ -150,5 +153,3 @@ class StatusApp extends Component { ); } } - -export default StatusApp; diff --git a/src/core/public/core_system.ts b/src/core/public/core_system.ts index 00fabc2b6f2f1..e08841b0271d9 100644 --- a/src/core/public/core_system.ts +++ b/src/core/public/core_system.ts @@ -42,8 +42,8 @@ import { RenderingService } from './rendering'; import { SavedObjectsService } from './saved_objects'; import { ContextService } from './context'; import { IntegrationsService } from './integrations'; -import { InternalApplicationSetup, InternalApplicationStart } from './application/types'; import { CoreApp } from './core_app'; +import type { InternalApplicationSetup, InternalApplicationStart } from './application/types'; interface Params { rootDomElement: HTMLElement; @@ -180,7 +180,7 @@ export class CoreSystem { ]), }); const application = this.application.setup({ context, http, injectedMetadata }); - this.coreApp.setup({ application, http }); + this.coreApp.setup({ application, http, injectedMetadata, notifications }); const core: InternalCoreSetup = { application, diff --git a/src/core/public/doc_links/doc_links_service.ts b/src/core/public/doc_links/doc_links_service.ts index 70b25cb78787a..eb54983d0be13 100644 --- a/src/core/public/doc_links/doc_links_service.ts +++ b/src/core/public/doc_links/doc_links_service.ts @@ -112,7 +112,7 @@ export class DocLinksService { kibana: `${ELASTIC_WEBSITE_URL}guide/en/kibana/${DOC_LINK_VERSION}/index.html`, siem: { guide: `${ELASTIC_WEBSITE_URL}guide/en/security/${DOC_LINK_VERSION}/index.html`, - gettingStarted: `${ELASTIC_WEBSITE_URL}guide/en/security/${DOC_LINK_VERSION}/install-siem.html`, + gettingStarted: `${ELASTIC_WEBSITE_URL}guide/en/security/${DOC_LINK_VERSION}/index.html`, }, query: { luceneQuerySyntax: `${ELASTICSEARCH_DOCS}query-dsl-query-string-query.html#query-string-syntax`, 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 5caa9830a643d..e6b1c440519bd 100644 --- a/src/core/public/injected_metadata/injected_metadata_service.mock.ts +++ b/src/core/public/injected_metadata/injected_metadata_service.mock.ts @@ -26,6 +26,7 @@ const createSetupContractMock = () => { getKibanaBranch: jest.fn(), getCspConfig: jest.fn(), getLegacyMode: jest.fn(), + getAnonymousStatusPage: jest.fn(), getLegacyMetadata: jest.fn(), getPlugins: jest.fn(), getInjectedVar: jest.fn(), @@ -35,6 +36,7 @@ const createSetupContractMock = () => { setupContract.getCspConfig.mockReturnValue({ warnLegacyBrowsers: true }); setupContract.getKibanaVersion.mockReturnValue('kibanaVersion'); setupContract.getLegacyMode.mockReturnValue(true); + setupContract.getAnonymousStatusPage.mockReturnValue(false); setupContract.getLegacyMetadata.mockReturnValue({ app: { id: 'foo', diff --git a/src/core/public/injected_metadata/injected_metadata_service.ts b/src/core/public/injected_metadata/injected_metadata_service.ts index 75abdd6d87d5a..db4bfdf415bcc 100644 --- a/src/core/public/injected_metadata/injected_metadata_service.ts +++ b/src/core/public/injected_metadata/injected_metadata_service.ts @@ -68,6 +68,7 @@ export interface InjectedMetadataParams { }; uiPlugins: InjectedPluginMetadata[]; legacyMode: boolean; + anonymousStatusPage: boolean; legacyMetadata: { app: { id: string; @@ -120,6 +121,10 @@ export class InjectedMetadataService { return this.state.serverBasePath; }, + getAnonymousStatusPage: () => { + return this.state.anonymousStatusPage; + }, + getKibanaVersion: () => { return this.state.version; }, @@ -179,6 +184,7 @@ export interface InjectedMetadataSetup { getPlugins: () => InjectedPluginMetadata[]; /** Indicates whether or not we are rendering a known legacy app. */ getLegacyMode: () => boolean; + getAnonymousStatusPage: () => boolean; getLegacyMetadata: () => { app: { id: string; diff --git a/src/core/public/legacy/legacy_service.ts b/src/core/public/legacy/legacy_service.ts index d77676b350f93..78a9219f3d694 100644 --- a/src/core/public/legacy/legacy_service.ts +++ b/src/core/public/legacy/legacy_service.ts @@ -53,7 +53,7 @@ interface BootstrapModule { * The LegacyPlatformService is responsible for initializing * the legacy platform by injecting parts of the new platform * services into the legacy platform modules, like ui/modules, - * and then bootstrapping the ui/chrome or ui/test_harness to + * and then bootstrapping the ui/chrome or ~~ui/test_harness~~ to * setup either the app or browser tests. */ export class LegacyPlatformService { diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md index c811209dfa80f..9b421e0172df0 100644 --- a/src/core/public/public.api.md +++ b/src/core/public/public.api.md @@ -5,147 +5,35 @@ ```ts import { Action } from 'history'; +import { ApiResponse } from '@elastic/elasticsearch/lib/Transport'; import Boom from 'boom'; -import { BulkIndexDocumentsParams } from 'elasticsearch'; -import { CatAliasesParams } from 'elasticsearch'; -import { CatAllocationParams } from 'elasticsearch'; -import { CatCommonParams } from 'elasticsearch'; -import { CatFielddataParams } from 'elasticsearch'; -import { CatHealthParams } from 'elasticsearch'; -import { CatHelpParams } from 'elasticsearch'; -import { CatIndicesParams } from 'elasticsearch'; -import { CatRecoveryParams } from 'elasticsearch'; -import { CatSegmentsParams } from 'elasticsearch'; -import { CatShardsParams } from 'elasticsearch'; -import { CatSnapshotsParams } from 'elasticsearch'; -import { CatTasksParams } from 'elasticsearch'; -import { CatThreadPoolParams } from 'elasticsearch'; -import { ClearScrollParams } from 'elasticsearch'; -import { Client } from 'elasticsearch'; -import { ClusterAllocationExplainParams } from 'elasticsearch'; -import { ClusterGetSettingsParams } from 'elasticsearch'; -import { ClusterHealthParams } from 'elasticsearch'; -import { ClusterPendingTasksParams } from 'elasticsearch'; -import { ClusterPutSettingsParams } from 'elasticsearch'; -import { ClusterRerouteParams } from 'elasticsearch'; -import { ClusterStateParams } from 'elasticsearch'; -import { ClusterStatsParams } from 'elasticsearch'; -import { CountParams } from 'elasticsearch'; -import { CreateDocumentParams } from 'elasticsearch'; -import { DeleteDocumentByQueryParams } from 'elasticsearch'; -import { DeleteDocumentParams } from 'elasticsearch'; -import { DeleteScriptParams } from 'elasticsearch'; -import { DeleteTemplateParams } from 'elasticsearch'; import { EuiBreadcrumb } from '@elastic/eui'; import { EuiButtonEmptyProps } from '@elastic/eui'; import { EuiConfirmModalProps } from '@elastic/eui'; import { EuiGlobalToastListToast } from '@elastic/eui'; import { ExclusiveUnion } from '@elastic/eui'; -import { ExistsParams } from 'elasticsearch'; -import { ExplainParams } from 'elasticsearch'; -import { FieldStatsParams } from 'elasticsearch'; -import { GenericParams } from 'elasticsearch'; -import { GetParams } from 'elasticsearch'; -import { GetResponse } from 'elasticsearch'; -import { GetScriptParams } from 'elasticsearch'; -import { GetSourceParams } from 'elasticsearch'; -import { GetTemplateParams } from 'elasticsearch'; import { History } from 'history'; import { Href } from 'history'; import { IconType } from '@elastic/eui'; -import { IndexDocumentParams } from 'elasticsearch'; -import { IndicesAnalyzeParams } from 'elasticsearch'; -import { IndicesClearCacheParams } from 'elasticsearch'; -import { IndicesCloseParams } from 'elasticsearch'; -import { IndicesCreateParams } from 'elasticsearch'; -import { IndicesDeleteAliasParams } from 'elasticsearch'; -import { IndicesDeleteParams } from 'elasticsearch'; -import { IndicesDeleteTemplateParams } from 'elasticsearch'; -import { IndicesExistsAliasParams } from 'elasticsearch'; -import { IndicesExistsParams } from 'elasticsearch'; -import { IndicesExistsTemplateParams } from 'elasticsearch'; -import { IndicesExistsTypeParams } from 'elasticsearch'; -import { IndicesFlushParams } from 'elasticsearch'; -import { IndicesFlushSyncedParams } from 'elasticsearch'; -import { IndicesForcemergeParams } from 'elasticsearch'; -import { IndicesGetAliasParams } from 'elasticsearch'; -import { IndicesGetFieldMappingParams } from 'elasticsearch'; -import { IndicesGetMappingParams } from 'elasticsearch'; -import { IndicesGetParams } from 'elasticsearch'; -import { IndicesGetSettingsParams } from 'elasticsearch'; -import { IndicesGetTemplateParams } from 'elasticsearch'; -import { IndicesGetUpgradeParams } from 'elasticsearch'; -import { IndicesOpenParams } from 'elasticsearch'; -import { IndicesPutAliasParams } from 'elasticsearch'; -import { IndicesPutMappingParams } from 'elasticsearch'; -import { IndicesPutSettingsParams } from 'elasticsearch'; -import { IndicesPutTemplateParams } from 'elasticsearch'; -import { IndicesRecoveryParams } from 'elasticsearch'; -import { IndicesRefreshParams } from 'elasticsearch'; -import { IndicesRolloverParams } from 'elasticsearch'; -import { IndicesSegmentsParams } from 'elasticsearch'; -import { IndicesShardStoresParams } from 'elasticsearch'; -import { IndicesShrinkParams } from 'elasticsearch'; -import { IndicesStatsParams } from 'elasticsearch'; -import { IndicesUpdateAliasesParams } from 'elasticsearch'; -import { IndicesUpgradeParams } from 'elasticsearch'; -import { IndicesValidateQueryParams } from 'elasticsearch'; -import { InfoParams } from 'elasticsearch'; -import { IngestDeletePipelineParams } from 'elasticsearch'; -import { IngestGetPipelineParams } from 'elasticsearch'; -import { IngestPutPipelineParams } from 'elasticsearch'; -import { IngestSimulateParams } from 'elasticsearch'; +import { KibanaClient } from '@elastic/elasticsearch/api/kibana'; import { KibanaConfigType } from 'src/core/server/kibana_config'; import { Location } from 'history'; import { LocationDescriptorObject } from 'history'; import { MaybePromise } from '@kbn/utility-types'; -import { MGetParams } from 'elasticsearch'; -import { MGetResponse } from 'elasticsearch'; -import { MSearchParams } from 'elasticsearch'; -import { MSearchResponse } from 'elasticsearch'; -import { MSearchTemplateParams } from 'elasticsearch'; -import { MTermVectorsParams } from 'elasticsearch'; -import { NodesHotThreadsParams } from 'elasticsearch'; -import { NodesInfoParams } from 'elasticsearch'; -import { NodesStatsParams } from 'elasticsearch'; import { Observable } from 'rxjs'; import { ParsedQuery } from 'query-string'; import { Path } from 'history'; -import { PingParams } from 'elasticsearch'; import { PublicUiSettingsParams as PublicUiSettingsParams_2 } from 'src/core/server/types'; -import { PutScriptParams } from 'elasticsearch'; -import { PutTemplateParams } from 'elasticsearch'; import React from 'react'; import { RecursiveReadonly } from '@kbn/utility-types'; -import { ReindexParams } from 'elasticsearch'; -import { ReindexRethrottleParams } from 'elasticsearch'; -import { RenderSearchTemplateParams } from 'elasticsearch'; import * as Rx from 'rxjs'; -import { ScrollParams } from 'elasticsearch'; -import { SearchParams } from 'elasticsearch'; -import { SearchResponse } from 'elasticsearch'; -import { SearchShardsParams } from 'elasticsearch'; -import { SearchTemplateParams } from 'elasticsearch'; import { ShallowPromise } from '@kbn/utility-types'; -import { SnapshotCreateParams } from 'elasticsearch'; -import { SnapshotCreateRepositoryParams } from 'elasticsearch'; -import { SnapshotDeleteParams } from 'elasticsearch'; -import { SnapshotDeleteRepositoryParams } from 'elasticsearch'; -import { SnapshotGetParams } from 'elasticsearch'; -import { SnapshotGetRepositoryParams } from 'elasticsearch'; -import { SnapshotRestoreParams } from 'elasticsearch'; -import { SnapshotStatusParams } from 'elasticsearch'; -import { SnapshotVerifyRepositoryParams } from 'elasticsearch'; -import { SuggestParams } from 'elasticsearch'; -import { TasksCancelParams } from 'elasticsearch'; -import { TasksGetParams } from 'elasticsearch'; -import { TasksListParams } from 'elasticsearch'; -import { TermvectorsParams } from 'elasticsearch'; +import { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport'; +import { TransportRequestParams } from '@elastic/elasticsearch/lib/Transport'; +import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; import { Type } from '@kbn/config-schema'; import { TypeOf } from '@kbn/config-schema'; import { UnregisterCallback } from 'history'; -import { UpdateDocumentByQueryParams } from 'elasticsearch'; -import { UpdateDocumentParams } from 'elasticsearch'; import { UserProvidedValues as UserProvidedValues_2 } from 'src/core/server/types'; // @internal (undocumented) diff --git a/src/core/server/config/deprecation/core_deprecations.test.ts b/src/core/server/config/deprecation/core_deprecations.test.ts index ebdb6f1c88b16..adf0f52339366 100644 --- a/src/core/server/config/deprecation/core_deprecations.test.ts +++ b/src/core/server/config/deprecation/core_deprecations.test.ts @@ -51,7 +51,7 @@ describe('core deprecations', () => { const { messages } = applyCoreDeprecations(); expect(messages).toMatchInlineSnapshot(` Array [ - "Environment variable CONFIG_PATH is deprecated. It has been replaced with KIBANA_PATH_CONF pointing to a config folder", + "Environment variable CONFIG_PATH is deprecated. It has been replaced with KBN_PATH_CONF pointing to a config folder", ] `); }); diff --git a/src/core/server/config/deprecation/core_deprecations.ts b/src/core/server/config/deprecation/core_deprecations.ts index 715f5b883139f..6cc0e5ef138d5 100644 --- a/src/core/server/config/deprecation/core_deprecations.ts +++ b/src/core/server/config/deprecation/core_deprecations.ts @@ -23,7 +23,7 @@ import { ConfigDeprecationProvider, ConfigDeprecation } from './types'; const configPathDeprecation: ConfigDeprecation = (settings, fromPath, log) => { if (has(process.env, 'CONFIG_PATH')) { log( - `Environment variable CONFIG_PATH is deprecated. It has been replaced with KIBANA_PATH_CONF pointing to a config folder` + `Environment variable CONFIG_PATH is deprecated. It has been replaced with KBN_PATH_CONF pointing to a config folder` ); } return settings; diff --git a/src/core/server/core_app/core_app.test.ts b/src/core/server/core_app/core_app.test.ts new file mode 100644 index 0000000000000..841088c45833b --- /dev/null +++ b/src/core/server/core_app/core_app.test.ts @@ -0,0 +1,71 @@ +/* + * 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 { mockCoreContext } from '../core_context.mock'; +import { coreMock } from '../mocks'; +import { httpResourcesMock } from '../http_resources/http_resources_service.mock'; +import { CoreApp } from './core_app'; + +describe('CoreApp', () => { + let coreApp: CoreApp; + let internalCoreSetup: ReturnType; + let httpResourcesRegistrar: ReturnType; + + beforeEach(() => { + const coreContext = mockCoreContext.create(); + internalCoreSetup = coreMock.createInternalSetup(); + httpResourcesRegistrar = httpResourcesMock.createRegistrar(); + internalCoreSetup.httpResources.createRegistrar.mockReturnValue(httpResourcesRegistrar); + coreApp = new CoreApp(coreContext); + }); + + describe('`/status` route', () => { + it('is registered with `authRequired: false` is the status page is anonymous', () => { + internalCoreSetup.status.isStatusPageAnonymous.mockReturnValue(true); + coreApp.setup(internalCoreSetup); + + expect(httpResourcesRegistrar.register).toHaveBeenCalledWith( + { + path: '/status', + validate: false, + options: { + authRequired: false, + }, + }, + expect.any(Function) + ); + }); + + it('is registered with `authRequired: true` is the status page is not anonymous', () => { + internalCoreSetup.status.isStatusPageAnonymous.mockReturnValue(false); + coreApp.setup(internalCoreSetup); + + expect(httpResourcesRegistrar.register).toHaveBeenCalledWith( + { + path: '/status', + validate: false, + options: { + authRequired: true, + }, + }, + expect.any(Function) + ); + }); + }); +}); diff --git a/src/core/server/core_app/core_app.ts b/src/core/server/core_app/core_app.ts index 5e1a3794632ee..508e69ea11170 100644 --- a/src/core/server/core_app/core_app.ts +++ b/src/core/server/core_app/core_app.ts @@ -52,6 +52,24 @@ export class CoreApp { router.get({ path: '/core', validate: false }, async (context, req, res) => res.ok({ body: { version: '0.0.1' } }) ); + + const anonymousStatusPage = coreSetup.status.isStatusPageAnonymous(); + coreSetup.httpResources.createRegistrar(router).register( + { + path: '/status', + validate: false, + options: { + authRequired: !anonymousStatusPage, + }, + }, + async (context, request, response) => { + if (anonymousStatusPage) { + return response.renderAnonymousCoreApp(); + } else { + return response.renderCoreApp(); + } + } + ); } private registerStaticDirs(coreSetup: InternalCoreSetup) { coreSetup.http.registerStaticDir('/ui/{path*}', Path.resolve(__dirname, './assets')); diff --git a/src/core/server/elasticsearch/client/configure_client.test.ts b/src/core/server/elasticsearch/client/configure_client.test.ts index 32da142764a78..11e3199a79fd2 100644 --- a/src/core/server/elasticsearch/client/configure_client.test.ts +++ b/src/core/server/elasticsearch/client/configure_client.test.ts @@ -118,26 +118,40 @@ describe('configureClient', () => { }); describe('Client logging', () => { - it('logs error when the client emits an error', () => { + it('logs error when the client emits an @elastic/elasticsearch error', () => { + const client = configureClient(config, { logger, scoped: false }); + + const response = createApiResponse({ body: {} }); + client.emit('response', new errors.TimeoutError('message', response), response); + + expect(loggingSystemMock.collect(logger).error).toMatchInlineSnapshot(` + Array [ + Array [ + "[TimeoutError]: message", + ], + ] + `); + }); + + it('logs error when the client emits an ResponseError returned by elasticsearch', () => { const client = configureClient(config, { logger, scoped: false }); const response = createApiResponse({ + statusCode: 400, + headers: {}, body: { error: { - type: 'error message', + type: 'illegal_argument_exception', + reason: 'request [/_path] contains unrecognized parameter: [name]', }, }, }); - client.emit('response', new errors.ResponseError(response), null); - client.emit('response', new Error('some error'), null); + client.emit('response', new errors.ResponseError(response), response); expect(loggingSystemMock.collect(logger).error).toMatchInlineSnapshot(` Array [ Array [ - "ResponseError: error message", - ], - Array [ - "Error: some error", + "[illegal_argument_exception]: request [/_path] contains unrecognized parameter: [name]", ], ] `); diff --git a/src/core/server/elasticsearch/client/configure_client.ts b/src/core/server/elasticsearch/client/configure_client.ts index 5377f8ca1b070..9746ecb538b75 100644 --- a/src/core/server/elasticsearch/client/configure_client.ts +++ b/src/core/server/elasticsearch/client/configure_client.ts @@ -21,6 +21,7 @@ import { stringify } from 'querystring'; import { Client } from '@elastic/elasticsearch'; import { Logger } from '../../logging'; import { parseClientOptions, ElasticsearchClientConfig } from './client_config'; +import { isResponseError } from './errors'; export const configureClient = ( config: ElasticsearchClientConfig, @@ -35,9 +36,15 @@ export const configureClient = ( }; const addLogging = (client: Client, logger: Logger, logQueries: boolean) => { - client.on('response', (err, event) => { - if (err) { - logger.error(`${err.name}: ${err.message}`); + client.on('response', (error, event) => { + if (error) { + const errorMessage = + // error details for response errors provided by elasticsearch + isResponseError(error) + ? `[${event.body.error.type}]: ${event.body.error.reason}` + : `[${error.name}]: ${error.message}`; + + logger.error(errorMessage); } if (event && logQueries) { const params = event.meta.request.params; diff --git a/src/core/server/elasticsearch/client/index.ts b/src/core/server/elasticsearch/client/index.ts index b8125de2ee498..af63dfa6c7f4e 100644 --- a/src/core/server/elasticsearch/client/index.ts +++ b/src/core/server/elasticsearch/client/index.ts @@ -17,7 +17,7 @@ * under the License. */ -export { ElasticsearchClient } from './types'; +export * from './types'; export { IScopedClusterClient, ScopedClusterClient } from './scoped_cluster_client'; export { ElasticsearchClientConfig } from './client_config'; export { IClusterClient, ICustomClusterClient, ClusterClient } from './cluster_client'; diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts index ec2885dfdf922..c93294404b52f 100644 --- a/src/core/server/elasticsearch/client/mocks.ts +++ b/src/core/server/elasticsearch/client/mocks.ts @@ -45,7 +45,7 @@ const createInternalClientMock = (): DeeplyMockedKeys => { .forEach((key) => { const propType = typeof obj[key]; if (propType === 'function') { - obj[key] = jest.fn(); + obj[key] = jest.fn(() => createSuccessTransportRequestPromise({})); } else if (propType === 'object' && obj[key] != null) { mockify(obj[key]); } @@ -70,6 +70,7 @@ const createInternalClientMock = (): DeeplyMockedKeys => { return (mock as unknown) as DeeplyMockedKeys; }; +// TODO fix naming ElasticsearchClientMock export type ElasticSearchClientMock = DeeplyMockedKeys; const createClientMock = (): ElasticSearchClientMock => @@ -124,32 +125,41 @@ export type MockedTransportRequestPromise = TransportRequestPromise & { abort: jest.MockedFunction<() => undefined>; }; -const createMockedClientResponse = (body: T): MockedTransportRequestPromise> => { - const response: ApiResponse = { - body, - statusCode: 200, - warnings: [], - headers: {}, - meta: {} as any, - }; +const createSuccessTransportRequestPromise = ( + body: T, + { statusCode = 200 }: { statusCode?: number } = {} +): MockedTransportRequestPromise> => { + const response = createApiResponse({ body, statusCode }); const promise = Promise.resolve(response); (promise as MockedTransportRequestPromise>).abort = jest.fn(); return promise as MockedTransportRequestPromise>; }; -const createMockedClientError = (err: any): MockedTransportRequestPromise => { +const createErrorTransportRequestPromise = (err: any): MockedTransportRequestPromise => { const promise = Promise.reject(err); (promise as MockedTransportRequestPromise).abort = jest.fn(); return promise as MockedTransportRequestPromise; }; +function createApiResponse(opts: Partial = {}): ApiResponse { + return { + body: {}, + statusCode: 200, + headers: {}, + warnings: [], + meta: {} as any, + ...opts, + }; +} + export const elasticsearchClientMock = { createClusterClient: createClusterClientMock, createCustomClusterClient: createCustomClusterClientMock, createScopedClusterClient: createScopedClusterClientMock, createElasticSearchClient: createClientMock, createInternalClient: createInternalClientMock, - createClientResponse: createMockedClientResponse, - createClientError: createMockedClientError, + createSuccessTransportRequestPromise, + createErrorTransportRequestPromise, + createApiResponse, }; diff --git a/src/core/server/elasticsearch/client/retry_call_cluster.test.ts b/src/core/server/elasticsearch/client/retry_call_cluster.test.ts index a7177c0b29047..3aa47e8b40e24 100644 --- a/src/core/server/elasticsearch/client/retry_call_cluster.test.ts +++ b/src/core/server/elasticsearch/client/retry_call_cluster.test.ts @@ -23,7 +23,8 @@ import { loggingSystemMock } from '../../logging/logging_system.mock'; import { retryCallCluster, migrationRetryCallCluster } from './retry_call_cluster'; const dummyBody = { foo: 'bar' }; -const createErrorReturn = (err: any) => elasticsearchClientMock.createClientError(err); +const createErrorReturn = (err: any) => + elasticsearchClientMock.createErrorTransportRequestPromise(err); describe('retryCallCluster', () => { let client: ReturnType; @@ -33,7 +34,9 @@ describe('retryCallCluster', () => { }); it('returns response from ES API call in case of success', async () => { - const successReturn = elasticsearchClientMock.createClientResponse({ ...dummyBody }); + const successReturn = elasticsearchClientMock.createSuccessTransportRequestPromise({ + ...dummyBody, + }); client.asyncSearch.get.mockReturnValue(successReturn); @@ -42,7 +45,9 @@ describe('retryCallCluster', () => { }); it('retries ES API calls that rejects with `NoLivingConnectionsError`', async () => { - const successReturn = elasticsearchClientMock.createClientResponse({ ...dummyBody }); + const successReturn = elasticsearchClientMock.createSuccessTransportRequestPromise({ + ...dummyBody, + }); client.asyncSearch.get .mockImplementationOnce(() => @@ -57,7 +62,9 @@ describe('retryCallCluster', () => { it('rejects when ES API calls reject with other errors', async () => { client.ping .mockImplementationOnce(() => createErrorReturn(new Error('unknown error'))) - .mockImplementationOnce(() => elasticsearchClientMock.createClientResponse({ ...dummyBody })); + .mockImplementationOnce(() => + elasticsearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody }) + ); await expect(retryCallCluster(() => client.ping())).rejects.toMatchInlineSnapshot( `[Error: unknown error]` @@ -73,7 +80,9 @@ describe('retryCallCluster', () => { createErrorReturn(new errors.NoLivingConnectionsError('no living connections', {} as any)) ) .mockImplementationOnce(() => createErrorReturn(new Error('unknown error'))) - .mockImplementationOnce(() => elasticsearchClientMock.createClientResponse({ ...dummyBody })); + .mockImplementationOnce(() => + elasticsearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody }) + ); await expect(retryCallCluster(() => client.ping())).rejects.toMatchInlineSnapshot( `[Error: unknown error]` @@ -94,7 +103,9 @@ describe('migrationRetryCallCluster', () => { client.ping .mockImplementationOnce(() => createErrorReturn(error)) .mockImplementationOnce(() => createErrorReturn(error)) - .mockImplementationOnce(() => elasticsearchClientMock.createClientResponse({ ...dummyBody })); + .mockImplementationOnce(() => + elasticsearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody }) + ); }; it('retries ES API calls that rejects with `NoLivingConnectionsError`', async () => { @@ -225,7 +236,9 @@ describe('migrationRetryCallCluster', () => { } as any) ) ) - .mockImplementationOnce(() => elasticsearchClientMock.createClientResponse({ ...dummyBody })); + .mockImplementationOnce(() => + elasticsearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody }) + ); await migrationRetryCallCluster(() => client.ping(), logger, 1); @@ -258,7 +271,9 @@ describe('migrationRetryCallCluster', () => { } as any) ) ) - .mockImplementationOnce(() => elasticsearchClientMock.createClientResponse({ ...dummyBody })); + .mockImplementationOnce(() => + elasticsearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody }) + ); await expect( migrationRetryCallCluster(() => client.ping(), logger, 1) @@ -274,7 +289,9 @@ describe('migrationRetryCallCluster', () => { createErrorReturn(new errors.TimeoutError('timeout error', {} as any)) ) .mockImplementationOnce(() => createErrorReturn(new Error('unknown error'))) - .mockImplementationOnce(() => elasticsearchClientMock.createClientResponse({ ...dummyBody })); + .mockImplementationOnce(() => + elasticsearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody }) + ); await expect( migrationRetryCallCluster(() => client.ping(), logger, 1) diff --git a/src/core/server/elasticsearch/client/retry_call_cluster.ts b/src/core/server/elasticsearch/client/retry_call_cluster.ts index 1ad039e512215..792f7f0a7fac9 100644 --- a/src/core/server/elasticsearch/client/retry_call_cluster.ts +++ b/src/core/server/elasticsearch/client/retry_call_cluster.ts @@ -27,7 +27,7 @@ const retryResponseStatuses = [ 403, // AuthenticationException 408, // RequestTimeout 410, // Gone -]; +] as const; /** * Retries the provided Elasticsearch API call when a `NoLivingConnectionsError` error is diff --git a/src/core/server/elasticsearch/client/types.ts b/src/core/server/elasticsearch/client/types.ts index 7ce998aab7669..827b185672c7c 100644 --- a/src/core/server/elasticsearch/client/types.ts +++ b/src/core/server/elasticsearch/client/types.ts @@ -41,3 +41,105 @@ export type ElasticsearchClient = Omit< ): TransportRequestPromise; }; }; + +/** + * All response typings are maintained until elasticsearch-js provides them out of the box + * https://github.com/elastic/elasticsearch-js/pull/970 + */ + +/** + * @public + */ +export interface ShardsResponse { + total: number; + successful: number; + failed: number; + skipped: number; +} + +/** + * @public + */ +export interface Explanation { + value: number; + description: string; + details: Explanation[]; +} + +/** + * @public + */ +export interface ShardsInfo { + total: number; + successful: number; + skipped: number; + failed: number; +} + +/** + * @public + */ +export interface CountResponse { + _shards: ShardsInfo; + count: number; +} + +/** + * @public + */ +export interface SearchResponse { + took: number; + timed_out: boolean; + _scroll_id?: string; + _shards: ShardsResponse; + hits: { + total: number; + max_score: number; + hits: Array<{ + _index: string; + _type: string; + _id: string; + _score: number; + _source: T; + _version?: number; + _explanation?: Explanation; + fields?: any; + highlight?: any; + inner_hits?: any; + matched_queries?: string[]; + sort?: string[]; + }>; + }; + aggregations?: any; +} + +/** + * @public + */ +export interface GetResponse { + _index: string; + _type: string; + _id: string; + _version: number; + _routing?: string; + found: boolean; + _source: T; + _seq_no: number; + _primary_term: number; +} + +/** + * @public + */ +export interface DeleteDocumentResponse { + _shards: ShardsResponse; + found: boolean; + _index: string; + _type: string; + _id: string; + _version: number; + result: string; + error?: { + type: string; + }; +} diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts index 4375f09f1ce0b..49f5c8dd98790 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts @@ -227,7 +227,7 @@ describe('#setup', () => { it('esNodeVersionCompatibility$ only starts polling when subscribed to', async (done) => { const mockedClient = mockClusterClientInstance.asInternalUser; mockedClient.nodes.info.mockImplementation(() => - elasticsearchClientMock.createClientError(new Error()) + elasticsearchClientMock.createErrorTransportRequestPromise(new Error()) ); const setupContract = await elasticsearchService.setup(setupDeps); @@ -243,7 +243,7 @@ describe('#setup', () => { it('esNodeVersionCompatibility$ stops polling when unsubscribed from', async (done) => { const mockedClient = mockClusterClientInstance.asInternalUser; mockedClient.nodes.info.mockImplementation(() => - elasticsearchClientMock.createClientError(new Error()) + elasticsearchClientMock.createErrorTransportRequestPromise(new Error()) ); const setupContract = await elasticsearchService.setup(setupDeps); @@ -359,7 +359,7 @@ describe('#stop', () => { const mockedClient = mockClusterClientInstance.asInternalUser; mockedClient.nodes.info.mockImplementation(() => - elasticsearchClientMock.createClientError(new Error()) + elasticsearchClientMock.createErrorTransportRequestPromise(new Error()) ); const setupContract = await elasticsearchService.setup(setupDeps); diff --git a/src/core/server/elasticsearch/index.ts b/src/core/server/elasticsearch/index.ts index 8bb77b5dfdee0..9359b88434396 100644 --- a/src/core/server/elasticsearch/index.ts +++ b/src/core/server/elasticsearch/index.ts @@ -36,4 +36,12 @@ export { ElasticsearchClientConfig, ElasticsearchClient, IScopedClusterClient, + // responses + SearchResponse, + CountResponse, + ShardsInfo, + ShardsResponse, + Explanation, + GetResponse, + DeleteDocumentResponse, } from './client'; diff --git a/src/core/server/elasticsearch/legacy/index.ts b/src/core/server/elasticsearch/legacy/index.ts index 165980b9f4522..a1740faac7ddf 100644 --- a/src/core/server/elasticsearch/legacy/index.ts +++ b/src/core/server/elasticsearch/legacy/index.ts @@ -23,6 +23,5 @@ export { } from './cluster_client'; export { ILegacyScopedClusterClient, LegacyScopedClusterClient } from './scoped_cluster_client'; export { LegacyElasticsearchClientConfig } from './elasticsearch_client_config'; -export { retryCallCluster, migrationsRetryCallCluster } from './retry_call_cluster'; export { LegacyElasticsearchError, LegacyElasticsearchErrorHelpers } from './errors'; export * from './api_types'; diff --git a/src/core/server/elasticsearch/legacy/retry_call_cluster.test.ts b/src/core/server/elasticsearch/legacy/retry_call_cluster.test.ts deleted file mode 100644 index 62789a4fe952d..0000000000000 --- a/src/core/server/elasticsearch/legacy/retry_call_cluster.test.ts +++ /dev/null @@ -1,147 +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 * as legacyElasticsearch from 'elasticsearch'; - -import { retryCallCluster, migrationsRetryCallCluster } from './retry_call_cluster'; -import { loggingSystemMock } from '../../logging/logging_system.mock'; - -describe('retryCallCluster', () => { - it('retries ES API calls that rejects with NoConnections', () => { - expect.assertions(1); - const callEsApi = jest.fn(); - let i = 0; - const ErrorConstructor = legacyElasticsearch.errors.NoConnections; - callEsApi.mockImplementation(() => { - return i++ <= 2 ? Promise.reject(new ErrorConstructor()) : Promise.resolve('success'); - }); - const retried = retryCallCluster(callEsApi); - return expect(retried('endpoint')).resolves.toMatchInlineSnapshot(`"success"`); - }); - - it('rejects when ES API calls reject with other errors', async () => { - expect.assertions(3); - const callEsApi = jest.fn(); - let i = 0; - callEsApi.mockImplementation(() => { - i++; - - return i === 1 - ? Promise.reject(new Error('unknown error')) - : i === 2 - ? Promise.resolve('success') - : i === 3 || i === 4 - ? Promise.reject(new legacyElasticsearch.errors.NoConnections()) - : i === 5 - ? Promise.reject(new Error('unknown error')) - : null; - }); - const retried = retryCallCluster(callEsApi); - await expect(retried('endpoint')).rejects.toMatchInlineSnapshot(`[Error: unknown error]`); - await expect(retried('endpoint')).resolves.toMatchInlineSnapshot(`"success"`); - return expect(retried('endpoint')).rejects.toMatchInlineSnapshot(`[Error: unknown error]`); - }); -}); - -describe('migrationsRetryCallCluster', () => { - const errors = [ - 'NoConnections', - 'ConnectionFault', - 'ServiceUnavailable', - 'RequestTimeout', - 'AuthenticationException', - 'AuthorizationException', - 'Gone', - ]; - - const mockLogger = loggingSystemMock.create(); - - beforeEach(() => { - loggingSystemMock.clear(mockLogger); - }); - - errors.forEach((errorName) => { - it('retries ES API calls that rejects with ' + errorName, () => { - expect.assertions(1); - const callEsApi = jest.fn(); - let i = 0; - const ErrorConstructor = (legacyElasticsearch.errors as any)[errorName]; - callEsApi.mockImplementation(() => { - return i++ <= 2 ? Promise.reject(new ErrorConstructor()) : Promise.resolve('success'); - }); - const retried = migrationsRetryCallCluster(callEsApi, mockLogger.get('mock log'), 1); - return expect(retried('endpoint')).resolves.toMatchInlineSnapshot(`"success"`); - }); - }); - - it('retries ES API calls that rejects with snapshot_in_progress_exception', () => { - expect.assertions(1); - const callEsApi = jest.fn(); - let i = 0; - callEsApi.mockImplementation(() => { - return i++ <= 2 - ? Promise.reject({ body: { error: { type: 'snapshot_in_progress_exception' } } }) - : Promise.resolve('success'); - }); - const retried = migrationsRetryCallCluster(callEsApi, mockLogger.get('mock log'), 1); - return expect(retried('endpoint')).resolves.toMatchInlineSnapshot(`"success"`); - }); - - it('rejects when ES API calls reject with other errors', async () => { - expect.assertions(3); - const callEsApi = jest.fn(); - let i = 0; - callEsApi.mockImplementation(() => { - i++; - - return i === 1 - ? Promise.reject(new Error('unknown error')) - : i === 2 - ? Promise.resolve('success') - : i === 3 || i === 4 - ? Promise.reject(new legacyElasticsearch.errors.NoConnections()) - : i === 5 - ? Promise.reject(new Error('unknown error')) - : null; - }); - const retried = migrationsRetryCallCluster(callEsApi, mockLogger.get('mock log'), 1); - await expect(retried('endpoint')).rejects.toMatchInlineSnapshot(`[Error: unknown error]`); - await expect(retried('endpoint')).resolves.toMatchInlineSnapshot(`"success"`); - return expect(retried('endpoint')).rejects.toMatchInlineSnapshot(`[Error: unknown error]`); - }); - - it('logs only once for each unique error message', async () => { - const callEsApi = jest.fn(); - callEsApi.mockRejectedValueOnce(new legacyElasticsearch.errors.NoConnections()); - callEsApi.mockRejectedValueOnce(new legacyElasticsearch.errors.NoConnections()); - callEsApi.mockRejectedValueOnce(new legacyElasticsearch.errors.AuthenticationException()); - callEsApi.mockResolvedValueOnce('done'); - const retried = migrationsRetryCallCluster(callEsApi, mockLogger.get('mock log'), 1); - await retried('endpoint'); - expect(loggingSystemMock.collect(mockLogger).warn).toMatchInlineSnapshot(` - Array [ - Array [ - "Unable to connect to Elasticsearch. Error: No Living connections", - ], - Array [ - "Unable to connect to Elasticsearch. Error: Authentication Exception", - ], - ] - `); - }); -}); diff --git a/src/core/server/elasticsearch/legacy/retry_call_cluster.ts b/src/core/server/elasticsearch/legacy/retry_call_cluster.ts deleted file mode 100644 index 1b05cb2bf13cd..0000000000000 --- a/src/core/server/elasticsearch/legacy/retry_call_cluster.ts +++ /dev/null @@ -1,115 +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 { retryWhen, concatMap } from 'rxjs/operators'; -import { defer, throwError, iif, timer } from 'rxjs'; -import * as legacyElasticsearch from 'elasticsearch'; - -import { LegacyCallAPIOptions } from '.'; -import { LegacyAPICaller } from './api_types'; -import { Logger } from '../../logging'; - -const esErrors = legacyElasticsearch.errors; - -/** - * Retries the provided Elasticsearch API call when an error such as - * `AuthenticationException` `NoConnections`, `ConnectionFault`, - * `ServiceUnavailable` or `RequestTimeout` are encountered. The API call will - * be retried once a second, indefinitely, until a successful response or a - * different error is received. - * - * @param apiCaller - * @param log - * @param delay - */ -export function migrationsRetryCallCluster( - apiCaller: LegacyAPICaller, - log: Logger, - delay: number = 2500 -) { - const previousErrors: string[] = []; - return ( - endpoint: string, - clientParams: Record = {}, - options?: LegacyCallAPIOptions - ) => { - return defer(() => apiCaller(endpoint, clientParams, options)) - .pipe( - retryWhen((error$) => - error$.pipe( - concatMap((error) => { - if (!previousErrors.includes(error.message)) { - log.warn(`Unable to connect to Elasticsearch. Error: ${error.message}`); - previousErrors.push(error.message); - } - return iif( - () => { - return ( - error instanceof esErrors.NoConnections || - error instanceof esErrors.ConnectionFault || - error instanceof esErrors.ServiceUnavailable || - error instanceof esErrors.RequestTimeout || - error instanceof esErrors.AuthenticationException || - error instanceof esErrors.AuthorizationException || - // @ts-expect-error - error instanceof esErrors.Gone || - error?.body?.error?.type === 'snapshot_in_progress_exception' - ); - }, - timer(delay), - throwError(error) - ); - }) - ) - ) - ) - .toPromise(); - }; -} - -/** - * Retries the provided Elasticsearch API call when a `NoConnections` error is - * encountered. The API call will be retried once a second, indefinitely, until - * a successful response or a different error is received. - * - * @param apiCaller - */ -export function retryCallCluster(apiCaller: LegacyAPICaller) { - return ( - endpoint: string, - clientParams: Record = {}, - options?: LegacyCallAPIOptions - ) => { - return defer(() => apiCaller(endpoint, clientParams, options)) - .pipe( - retryWhen((errors) => - errors.pipe( - concatMap((error) => - iif( - () => error instanceof legacyElasticsearch.errors.NoConnections, - timer(1000), - throwError(error) - ) - ) - ) - ) - ) - .toPromise(); - }; -} diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts index 21adac081acf7..f6313f68abff2 100644 --- a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts +++ b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts @@ -28,8 +28,8 @@ const mockLogger = mockLoggerFactory.get('mock logger'); const KIBANA_VERSION = '5.1.0'; -const createEsSuccess = elasticsearchClientMock.createClientResponse; -const createEsError = elasticsearchClientMock.createClientError; +const createEsSuccess = elasticsearchClientMock.createSuccessTransportRequestPromise; +const createEsError = elasticsearchClientMock.createErrorTransportRequestPromise; function createNodes(...versions: string[]): NodesInfo { const nodes = {} as any; diff --git a/src/core/server/http/http_config.ts b/src/core/server/http/http_config.ts index 83a2e712b424f..e74f6d32e92b0 100644 --- a/src/core/server/http/http_config.ts +++ b/src/core/server/http/http_config.ts @@ -42,21 +42,7 @@ export const config = { validate: match(validBasePathRegex, "must start with a slash, don't end with one"), }) ), - cors: schema.conditional( - schema.contextRef('dev'), - true, - schema.object( - { - origin: schema.arrayOf(schema.string()), - }, - { - defaultValue: { - origin: ['*://localhost:9876'], // karma test server - }, - } - ), - schema.boolean({ defaultValue: false }) - ), + cors: schema.boolean({ defaultValue: false }), customResponseHeaders: schema.recordOf(schema.string(), schema.any(), { defaultValue: {}, }), diff --git a/src/core/server/http/http_server.test.ts b/src/core/server/http/http_server.test.ts index 601eba835a54e..007d75a69b955 100644 --- a/src/core/server/http/http_server.test.ts +++ b/src/core/server/http/http_server.test.ts @@ -992,6 +992,133 @@ describe('body options', () => { }); }); +describe('timeout options', () => { + test('should accept a socket "timeout" which is 3 minutes in milliseconds, "300000" for a POST', async () => { + const { registerRouter, server: innerServer } = await server.setup(config); + + const router = new Router('', logger, enhanceWithContext); + router.post( + { + path: '/', + validate: false, + options: { timeout: 300000 }, + }, + (context, req, res) => { + try { + return res.ok({ body: { timeout: req.route.options.timeout } }); + } catch (err) { + return res.internalError({ body: err.message }); + } + } + ); + registerRouter(router); + await server.start(); + await supertest(innerServer.listener).post('/').send({ test: 1 }).expect(200, { + timeout: 300000, + }); + }); + + test('should accept a socket "timeout" which is 3 minutes in milliseconds, "300000" for a GET', async () => { + const { registerRouter, server: innerServer } = await server.setup(config); + + const router = new Router('', logger, enhanceWithContext); + router.get( + { + path: '/', + validate: false, + options: { timeout: 300000 }, + }, + (context, req, res) => { + try { + return res.ok({ body: { timeout: req.route.options.timeout } }); + } catch (err) { + return res.internalError({ body: err.message }); + } + } + ); + registerRouter(router); + await server.start(); + await supertest(innerServer.listener).get('/').expect(200, { + timeout: 300000, + }); + }); + + test('should accept a socket "timeout" which is 3 minutes in milliseconds, "300000" for a DELETE', async () => { + const { registerRouter, server: innerServer } = await server.setup(config); + + const router = new Router('', logger, enhanceWithContext); + router.delete( + { + path: '/', + validate: false, + options: { timeout: 300000 }, + }, + (context, req, res) => { + try { + return res.ok({ body: { timeout: req.route.options.timeout } }); + } catch (err) { + return res.internalError({ body: err.message }); + } + } + ); + registerRouter(router); + await server.start(); + await supertest(innerServer.listener).delete('/').expect(200, { + timeout: 300000, + }); + }); + + test('should accept a socket "timeout" which is 3 minutes in milliseconds, "300000" for a PUT', async () => { + const { registerRouter, server: innerServer } = await server.setup(config); + + const router = new Router('', logger, enhanceWithContext); + router.put( + { + path: '/', + validate: false, + options: { timeout: 300000 }, + }, + (context, req, res) => { + try { + return res.ok({ body: { timeout: req.route.options.timeout } }); + } catch (err) { + return res.internalError({ body: err.message }); + } + } + ); + registerRouter(router); + await server.start(); + await supertest(innerServer.listener).put('/').expect(200, { + timeout: 300000, + }); + }); + + test('should accept a socket "timeout" which is 3 minutes in milliseconds, "300000" for a PATCH', async () => { + const { registerRouter, server: innerServer } = await server.setup(config); + + const router = new Router('', logger, enhanceWithContext); + router.patch( + { + path: '/', + validate: false, + options: { timeout: 300000 }, + }, + (context, req, res) => { + try { + return res.ok({ body: { timeout: req.route.options.timeout } }); + } catch (err) { + return res.internalError({ body: err.message }); + } + } + ); + registerRouter(router); + await server.start(); + await supertest(innerServer.listener).patch('/').expect(200, { + timeout: 300000, + }); + }); +}); + test('should return a stream in the body', async () => { const { registerRouter, server: innerServer } = await server.setup(config); diff --git a/src/core/server/http/http_server.ts b/src/core/server/http/http_server.ts index 9c16162d69334..4b70f58deba99 100644 --- a/src/core/server/http/http_server.ts +++ b/src/core/server/http/http_server.ts @@ -161,8 +161,10 @@ export class HttpServer { this.log.debug(`registering route handler for [${route.path}]`); // Hapi does not allow payload validation to be specified for 'head' or 'get' requests const validate = isSafeMethod(route.method) ? undefined : { payload: true }; - const { authRequired, tags, body = {} } = route.options; + const { authRequired, tags, body = {}, timeout } = route.options; const { accepts: allow, maxBytes, output, parse } = body; + // Hapi does not allow timeouts on payloads to be specified for 'head' or 'get' requests + const payloadTimeout = isSafeMethod(route.method) || timeout == null ? undefined : timeout; const kibanaRouteState: KibanaRouteState = { xsrfRequired: route.options.xsrfRequired ?? !isSafeMethod(route.method), @@ -181,9 +183,23 @@ export class HttpServer { // validation applied in ./http_tools#getServerOptions // (All NP routes are already required to specify their own validation in order to access the payload) validate, - payload: [allow, maxBytes, output, parse].some((v) => typeof v !== 'undefined') - ? { allow, maxBytes, output, parse } + payload: [allow, maxBytes, output, parse, payloadTimeout].some( + (v) => typeof v !== 'undefined' + ) + ? { + allow, + maxBytes, + output, + parse, + timeout: payloadTimeout, + } : undefined, + timeout: + timeout != null + ? { + socket: timeout + 1, // Hapi server requires the socket to be greater than payload settings so we add 1 millisecond + } + : undefined, }, }); } diff --git a/src/core/server/http/integration_tests/core_services.test.ts b/src/core/server/http/integration_tests/core_services.test.ts index 6338326626d54..6a00db5a6cc4a 100644 --- a/src/core/server/http/integration_tests/core_services.test.ts +++ b/src/core/server/http/integration_tests/core_services.test.ts @@ -479,7 +479,7 @@ describe('http service', () => { let elasticsearch: InternalElasticsearchServiceStart; esClient.ping.mockImplementation(() => - elasticsearchClientMock.createClientError( + elasticsearchClientMock.createErrorTransportRequestPromise( new ResponseError({ statusCode: 401, body: { @@ -517,7 +517,7 @@ describe('http service', () => { let elasticsearch: InternalElasticsearchServiceStart; esClient.ping.mockImplementation(() => - elasticsearchClientMock.createClientError( + elasticsearchClientMock.createErrorTransportRequestPromise( new ResponseError({ statusCode: 401, body: { diff --git a/src/core/server/http/integration_tests/router.test.ts b/src/core/server/http/integration_tests/router.test.ts index bb36fefa96611..434e22e3cf6f5 100644 --- a/src/core/server/http/integration_tests/router.test.ts +++ b/src/core/server/http/integration_tests/router.test.ts @@ -302,6 +302,130 @@ describe('Options', () => { }); }); }); + + describe('timeout', () => { + it('should timeout if configured with a small timeout value for a POST', async () => { + const { server: innerServer, createRouter } = await server.setup(setupDeps); + const router = createRouter('/'); + + router.post( + { path: '/a', validate: false, options: { timeout: 1000 } }, + async (context, req, res) => { + await new Promise((resolve) => setTimeout(resolve, 2000)); + return res.ok({}); + } + ); + router.post({ path: '/b', validate: false }, (context, req, res) => res.ok({})); + await server.start(); + expect(supertest(innerServer.listener).post('/a')).rejects.toThrow('socket hang up'); + await supertest(innerServer.listener).post('/b').expect(200, {}); + }); + + it('should timeout if configured with a small timeout value for a PUT', async () => { + const { server: innerServer, createRouter } = await server.setup(setupDeps); + const router = createRouter('/'); + + router.put( + { path: '/a', validate: false, options: { timeout: 1000 } }, + async (context, req, res) => { + await new Promise((resolve) => setTimeout(resolve, 2000)); + return res.ok({}); + } + ); + router.put({ path: '/b', validate: false }, (context, req, res) => res.ok({})); + await server.start(); + + expect(supertest(innerServer.listener).put('/a')).rejects.toThrow('socket hang up'); + await supertest(innerServer.listener).put('/b').expect(200, {}); + }); + + it('should timeout if configured with a small timeout value for a DELETE', async () => { + const { server: innerServer, createRouter } = await server.setup(setupDeps); + const router = createRouter('/'); + + router.delete( + { path: '/a', validate: false, options: { timeout: 1000 } }, + async (context, req, res) => { + await new Promise((resolve) => setTimeout(resolve, 2000)); + return res.ok({}); + } + ); + router.delete({ path: '/b', validate: false }, (context, req, res) => res.ok({})); + await server.start(); + expect(supertest(innerServer.listener).delete('/a')).rejects.toThrow('socket hang up'); + await supertest(innerServer.listener).delete('/b').expect(200, {}); + }); + + it('should timeout if configured with a small timeout value for a GET', async () => { + const { server: innerServer, createRouter } = await server.setup(setupDeps); + const router = createRouter('/'); + + router.get( + // Note: There is a bug within Hapi Server where it cannot set the payload timeout for a GET call but it also cannot configure a timeout less than the payload body + // so the least amount of possible time to configure the timeout is 10 seconds. + { path: '/a', validate: false, options: { timeout: 100000 } }, + async (context, req, res) => { + // Cause a wait of 20 seconds to cause the socket hangup + await new Promise((resolve) => setTimeout(resolve, 200000)); + return res.ok({}); + } + ); + router.get({ path: '/b', validate: false }, (context, req, res) => res.ok({})); + await server.start(); + + expect(supertest(innerServer.listener).get('/a')).rejects.toThrow('socket hang up'); + await supertest(innerServer.listener).get('/b').expect(200, {}); + }); + + it('should not timeout if configured with a 5 minute timeout value for a POST', async () => { + const { server: innerServer, createRouter } = await server.setup(setupDeps); + const router = createRouter('/'); + + router.post( + { path: '/a', validate: false, options: { timeout: 300000 } }, + async (context, req, res) => res.ok({}) + ); + await server.start(); + await supertest(innerServer.listener).post('/a').expect(200, {}); + }); + + it('should not timeout if configured with a 5 minute timeout value for a PUT', async () => { + const { server: innerServer, createRouter } = await server.setup(setupDeps); + const router = createRouter('/'); + + router.put( + { path: '/a', validate: false, options: { timeout: 300000 } }, + async (context, req, res) => res.ok({}) + ); + await server.start(); + + await supertest(innerServer.listener).put('/a').expect(200, {}); + }); + + it('should not timeout if configured with a 5 minute timeout value for a DELETE', async () => { + const { server: innerServer, createRouter } = await server.setup(setupDeps); + const router = createRouter('/'); + + router.delete( + { path: '/a', validate: false, options: { timeout: 300000 } }, + async (context, req, res) => res.ok({}) + ); + await server.start(); + await supertest(innerServer.listener).delete('/a').expect(200, {}); + }); + + it('should not timeout if configured with a 5 minute timeout value for a GET', async () => { + const { server: innerServer, createRouter } = await server.setup(setupDeps); + const router = createRouter('/'); + + router.get( + { path: '/a', validate: false, options: { timeout: 300000 } }, + async (context, req, res) => res.ok({}) + ); + await server.start(); + await supertest(innerServer.listener).get('/a').expect(200, {}); + }); + }); }); describe('Cache-Control', () => { diff --git a/src/core/server/http/router/request.ts b/src/core/server/http/router/request.ts index fefd75ad9710e..0e73431fe7c6d 100644 --- a/src/core/server/http/router/request.ts +++ b/src/core/server/http/router/request.ts @@ -197,12 +197,14 @@ export class KibanaRequest< private getRouteInfo(request: Request): KibanaRequestRoute { const method = request.method as Method; const { parse, maxBytes, allow, output } = request.route.settings.payload || {}; + const timeout = request.route.settings.timeout?.socket; const options = ({ authRequired: this.getAuthRequired(request), // some places in LP call KibanaRequest.from(request) manually. remove fallback to true before v8 xsrfRequired: (request.route.settings.app as KibanaRouteState)?.xsrfRequired ?? true, tags: request.route.settings.tags || [], + timeout: typeof timeout === 'number' ? timeout - 1 : undefined, // We are forced to have the timeout be 1 millisecond greater than the server and payload so we subtract one here to give the user consist settings body: isSafeMethod(method) ? undefined : { diff --git a/src/core/server/http/router/route.ts b/src/core/server/http/router/route.ts index 9789d266587af..676c494bec522 100644 --- a/src/core/server/http/router/route.ts +++ b/src/core/server/http/router/route.ts @@ -144,6 +144,12 @@ export interface RouteConfigOptions { * Additional body options {@link RouteConfigOptionsBody}. */ body?: Method extends 'get' | 'options' ? undefined : RouteConfigOptionsBody; + + /** + * Timeouts for processing durations. Response timeout is in milliseconds. + * Default value: 2 minutes + */ + timeout?: number; } /** diff --git a/src/core/server/http_resources/http_resources_service.mock.ts b/src/core/server/http_resources/http_resources_service.mock.ts index 4536b0898cad9..9d7db3a5b7273 100644 --- a/src/core/server/http_resources/http_resources_service.mock.ts +++ b/src/core/server/http_resources/http_resources_service.mock.ts @@ -25,7 +25,7 @@ const createHttpResourcesMock = (): jest.Mocked => ({ function createInternalHttpResourcesSetup() { return { - createRegistrar: createHttpResourcesMock, + createRegistrar: jest.fn(() => createHttpResourcesMock()), }; } diff --git a/src/core/server/index.ts b/src/core/server/index.ts index 706ec88c6ebfd..f46b41d6b8793 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -109,6 +109,14 @@ export { LegacyAPICaller, FakeRequest, ScopeableRequest, + ElasticsearchClient, + SearchResponse, + CountResponse, + ShardsInfo, + ShardsResponse, + Explanation, + GetResponse, + DeleteDocumentResponse, } from './elasticsearch'; export * from './elasticsearch/legacy/api_types'; export { diff --git a/src/core/server/mocks.ts b/src/core/server/mocks.ts index a3dbb279d19eb..84e4b4741b717 100644 --- a/src/core/server/mocks.ts +++ b/src/core/server/mocks.ts @@ -31,7 +31,6 @@ import { typeRegistryMock as savedObjectsTypeRegistryMock } from './saved_object import { renderingMock } from './rendering/rendering_service.mock'; import { uiSettingsServiceMock } from './ui_settings/ui_settings_service.mock'; import { SharedGlobalConfig } from './plugins'; -import { InternalCoreSetup, InternalCoreStart } from './internal_types'; import { capabilitiesServiceMock } from './capabilities/capabilities_service.mock'; import { metricsServiceMock } from './metrics/metrics_service.mock'; import { uuidServiceMock } from './uuid/uuid_service.mock'; @@ -157,7 +156,7 @@ function createCoreStartMock() { } function createInternalCoreSetupMock() { - const setupDeps: InternalCoreSetup = { + const setupDeps = { capabilities: capabilitiesServiceMock.createSetupContract(), context: contextServiceMock.createSetupContract(), elasticsearch: elasticsearchServiceMock.createInternalSetup(), @@ -175,7 +174,7 @@ function createInternalCoreSetupMock() { } function createInternalCoreStartMock() { - const startDeps: InternalCoreStart = { + const startDeps = { capabilities: capabilitiesServiceMock.createStartContract(), elasticsearch: elasticsearchServiceMock.createInternalStart(), http: httpServiceMock.createInternalStartContract(), diff --git a/src/core/server/path/index.ts b/src/core/server/path/index.ts index 1bb650518c47a..7c1a81643fbc8 100644 --- a/src/core/server/path/index.ts +++ b/src/core/server/path/index.ts @@ -25,14 +25,18 @@ import { fromRoot } from '../utils'; const isString = (v: any): v is string => typeof v === 'string'; const CONFIG_PATHS = [ + process.env.KBN_PATH_CONF && join(process.env.KBN_PATH_CONF, 'kibana.yml'), process.env.KIBANA_PATH_CONF && join(process.env.KIBANA_PATH_CONF, 'kibana.yml'), process.env.CONFIG_PATH, // deprecated fromRoot('config/kibana.yml'), ].filter(isString); -const CONFIG_DIRECTORIES = [process.env.KIBANA_PATH_CONF, fromRoot('config'), '/etc/kibana'].filter( - isString -); +const CONFIG_DIRECTORIES = [ + process.env.KBN_PATH_CONF, + process.env.KIBANA_PATH_CONF, + fromRoot('config'), + '/etc/kibana', +].filter(isString); const DATA_PATHS = [ process.env.DATA_PATH, // deprecated diff --git a/src/core/server/rendering/__mocks__/params.ts b/src/core/server/rendering/__mocks__/params.ts index ce2eea119d1bb..0901cec768cd2 100644 --- a/src/core/server/rendering/__mocks__/params.ts +++ b/src/core/server/rendering/__mocks__/params.ts @@ -21,15 +21,18 @@ import { mockCoreContext } from '../../core_context.mock'; import { httpServiceMock } from '../../http/http_service.mock'; import { pluginServiceMock } from '../../plugins/plugins_service.mock'; import { legacyServiceMock } from '../../legacy/legacy_service.mock'; +import { statusServiceMock } from '../../status/status_service.mock'; const context = mockCoreContext.create(); const http = httpServiceMock.createInternalSetupContract(); const uiPlugins = pluginServiceMock.createUiPlugins(); const legacyPlugins = legacyServiceMock.createDiscoverPlugins(); +const status = statusServiceMock.createInternalSetupContract(); export const mockRenderingServiceParams = context; export const mockRenderingSetupDeps = { http, legacyPlugins, uiPlugins, + status, }; 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 3b11313367d9c..95230b52c5c03 100644 --- a/src/core/server/rendering/__snapshots__/rendering_service.test.ts.snap +++ b/src/core/server/rendering/__snapshots__/rendering_service.test.ts.snap @@ -2,6 +2,7 @@ exports[`RenderingService setup() render() renders "core" from legacy request 1`] = ` Object { + "anonymousStatusPage": false, "basePath": "/mock-server-basepath", "branch": Any, "buildNumber": Any, @@ -74,6 +75,7 @@ Object { exports[`RenderingService setup() render() renders "core" page 1`] = ` Object { + "anonymousStatusPage": false, "basePath": "/mock-server-basepath", "branch": Any, "buildNumber": Any, @@ -146,6 +148,7 @@ Object { exports[`RenderingService setup() render() renders "core" page driven by settings 1`] = ` Object { + "anonymousStatusPage": false, "basePath": "/mock-server-basepath", "branch": Any, "buildNumber": Any, @@ -222,6 +225,7 @@ Object { exports[`RenderingService setup() render() renders "core" page for blank basepath 1`] = ` Object { + "anonymousStatusPage": false, "basePath": "", "branch": Any, "buildNumber": Any, @@ -294,6 +298,7 @@ Object { exports[`RenderingService setup() render() renders "core" with excluded user settings 1`] = ` Object { + "anonymousStatusPage": false, "basePath": "/mock-server-basepath", "branch": Any, "buildNumber": Any, @@ -366,6 +371,7 @@ Object { exports[`RenderingService setup() render() renders "legacy" page 1`] = ` Object { + "anonymousStatusPage": false, "basePath": "/mock-server-basepath", "branch": Any, "buildNumber": Any, @@ -438,6 +444,7 @@ Object { exports[`RenderingService setup() render() renders "legacy" page for blank basepath 1`] = ` Object { + "anonymousStatusPage": false, "basePath": "", "branch": Any, "buildNumber": Any, @@ -510,6 +517,7 @@ Object { exports[`RenderingService setup() render() renders "legacy" with custom vars 1`] = ` Object { + "anonymousStatusPage": false, "basePath": "/mock-server-basepath", "branch": Any, "buildNumber": Any, @@ -584,6 +592,7 @@ Object { exports[`RenderingService setup() render() renders "legacy" with excluded user settings 1`] = ` Object { + "anonymousStatusPage": false, "basePath": "/mock-server-basepath", "branch": Any, "buildNumber": Any, @@ -656,6 +665,7 @@ Object { exports[`RenderingService setup() render() renders "legacy" with excluded user settings and custom vars 1`] = ` Object { + "anonymousStatusPage": false, "basePath": "/mock-server-basepath", "branch": Any, "buildNumber": Any, diff --git a/src/core/server/rendering/rendering_service.tsx b/src/core/server/rendering/rendering_service.tsx index a02d85d22b2cb..8f87d62496891 100644 --- a/src/core/server/rendering/rendering_service.tsx +++ b/src/core/server/rendering/rendering_service.tsx @@ -42,6 +42,7 @@ export class RenderingService implements CoreService { @@ -79,6 +80,7 @@ export class RenderingService implements CoreService { + let client: ReturnType; + + beforeEach(() => { + client = elasticsearchClientMock.createElasticSearchClient(); + }); describe('fetchInfo', () => { test('it handles 404', async () => { - const callCluster = jest - .fn() - .mockImplementation(async (path: string, { ignore, index }: any) => { - expect(path).toEqual('indices.get'); - expect(ignore).toEqual([404]); - expect(index).toEqual('.kibana-test'); - return { status: 404 }; - }); + client.indices.get.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); - const info = await Index.fetchInfo(callCluster as any, '.kibana-test'); + const info = await Index.fetchInfo(client, '.kibana-test'); expect(info).toEqual({ aliases: {}, exists: false, indexName: '.kibana-test', mappings: { dynamic: 'strict', properties: {} }, }); + + expect(client.indices.get).toHaveBeenCalledWith({ index: '.kibana-test' }, { ignore: [404] }); }); test('fails if the index doc type is unsupported', async () => { - const callCluster = jest.fn(async (path: string, { index }: any) => { - return { + client.indices.get.mockImplementation((params) => { + const index = params!.index as string; + return elasticsearchClientMock.createSuccessTransportRequestPromise({ [index]: { aliases: { foo: index }, mappings: { spock: { dynamic: 'strict', properties: { a: 'b' } } }, }, - }; + }); }); - await expect(Index.fetchInfo(callCluster as any, '.baz')).rejects.toThrow( + await expect(Index.fetchInfo(client, '.baz')).rejects.toThrow( /cannot be automatically migrated/ ); }); test('fails if there are multiple root types', async () => { - const callCluster = jest.fn().mockImplementation(async (path: string, { index }: any) => { - return { + client.indices.get.mockImplementation((params) => { + const index = params!.index as string; + return elasticsearchClientMock.createSuccessTransportRequestPromise({ [index]: { aliases: { foo: index }, mappings: { @@ -66,25 +71,26 @@ describe('ElasticIndex', () => { doctor: { dynamic: 'strict', properties: { a: 'b' } }, }, }, - }; + }); }); - await expect(Index.fetchInfo(callCluster, '.baz')).rejects.toThrow( + await expect(Index.fetchInfo(client, '.baz')).rejects.toThrow( /cannot be automatically migrated/ ); }); test('decorates index info with exists and indexName', async () => { - const callCluster = jest.fn().mockImplementation(async (path: string, { index }: any) => { - return { + client.indices.get.mockImplementation((params) => { + const index = params!.index as string; + return elasticsearchClientMock.createSuccessTransportRequestPromise({ [index]: { aliases: { foo: index }, mappings: { dynamic: 'strict', properties: { a: 'b' } }, }, - }; + }); }); - const info = await Index.fetchInfo(callCluster, '.baz'); + const info = await Index.fetchInfo(client, '.baz'); expect(info).toEqual({ aliases: { foo: '.baz' }, mappings: { dynamic: 'strict', properties: { a: 'b' } }, @@ -96,171 +102,120 @@ describe('ElasticIndex', () => { describe('createIndex', () => { test('calls indices.create', async () => { - const callCluster = jest.fn(async (path: string, { body, index }: any) => { - expect(path).toEqual('indices.create'); - expect(body).toEqual({ + await Index.createIndex(client, '.abcd', { foo: 'bar' } as any); + + expect(client.indices.create).toHaveBeenCalledTimes(1); + expect(client.indices.create).toHaveBeenCalledWith({ + body: { mappings: { foo: 'bar' }, - settings: { auto_expand_replicas: '0-1', number_of_shards: 1 }, - }); - expect(index).toEqual('.abcd'); + settings: { + auto_expand_replicas: '0-1', + number_of_shards: 1, + }, + }, + index: '.abcd', }); - - await Index.createIndex(callCluster as any, '.abcd', { foo: 'bar' } as any); - expect(callCluster).toHaveBeenCalled(); }); }); describe('deleteIndex', () => { test('calls indices.delete', async () => { - const callCluster = jest.fn(async (path: string, { index }: any) => { - expect(path).toEqual('indices.delete'); - expect(index).toEqual('.lotr'); - }); + await Index.deleteIndex(client, '.lotr'); - await Index.deleteIndex(callCluster as any, '.lotr'); - expect(callCluster).toHaveBeenCalled(); + expect(client.indices.delete).toHaveBeenCalledTimes(1); + expect(client.indices.delete).toHaveBeenCalledWith({ + index: '.lotr', + }); }); }); describe('claimAlias', () => { - function assertCalled(callCluster: jest.Mock) { - expect(callCluster.mock.calls.map(([path]) => path)).toEqual([ - 'indices.getAlias', - 'indices.updateAliases', - 'indices.refresh', - ]); - } - test('handles unaliased indices', async () => { - const callCluster = jest.fn(async (path: string, arg: any) => { - switch (path) { - case 'indices.getAlias': - expect(arg.ignore).toEqual([404]); - expect(arg.name).toEqual('.hola'); - return { status: 404 }; - case 'indices.updateAliases': - expect(arg.body).toEqual({ - actions: [{ add: { index: '.hola-42', alias: '.hola' } }], - }); - return true; - case 'indices.refresh': - expect(arg.index).toEqual('.hola-42'); - return true; - default: - throw new Error(`Dunnoes what ${path} means.`); - } - }); + client.indices.getAlias.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); - await Index.claimAlias(callCluster as any, '.hola-42', '.hola'); + await Index.claimAlias(client, '.hola-42', '.hola'); - assertCalled(callCluster); + expect(client.indices.getAlias).toHaveBeenCalledWith( + { + name: '.hola', + }, + { ignore: [404] } + ); + expect(client.indices.updateAliases).toHaveBeenCalledWith({ + body: { + actions: [{ add: { index: '.hola-42', alias: '.hola' } }], + }, + }); + expect(client.indices.refresh).toHaveBeenCalledWith({ + index: '.hola-42', + }); }); test('removes existing alias', async () => { - const callCluster = jest.fn(async (path: string, arg: any) => { - switch (path) { - case 'indices.getAlias': - return { '.my-fanci-index': '.muchacha' }; - case 'indices.updateAliases': - expect(arg.body).toEqual({ - actions: [ - { remove: { index: '.my-fanci-index', alias: '.muchacha' } }, - { add: { index: '.ze-index', alias: '.muchacha' } }, - ], - }); - return true; - case 'indices.refresh': - expect(arg.index).toEqual('.ze-index'); - return true; - default: - throw new Error(`Dunnoes what ${path} means.`); - } - }); + client.indices.getAlias.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + '.my-fanci-index': '.muchacha', + }) + ); - await Index.claimAlias(callCluster as any, '.ze-index', '.muchacha'); + await Index.claimAlias(client, '.ze-index', '.muchacha'); - assertCalled(callCluster); + expect(client.indices.getAlias).toHaveBeenCalledTimes(1); + expect(client.indices.updateAliases).toHaveBeenCalledWith({ + body: { + actions: [ + { remove: { index: '.my-fanci-index', alias: '.muchacha' } }, + { add: { index: '.ze-index', alias: '.muchacha' } }, + ], + }, + }); + expect(client.indices.refresh).toHaveBeenCalledWith({ + index: '.ze-index', + }); }); test('allows custom alias actions', async () => { - const callCluster = jest.fn(async (path: string, arg: any) => { - switch (path) { - case 'indices.getAlias': - return { '.my-fanci-index': '.muchacha' }; - case 'indices.updateAliases': - expect(arg.body).toEqual({ - actions: [ - { remove_index: { index: 'awww-snap!' } }, - { remove: { index: '.my-fanci-index', alias: '.muchacha' } }, - { add: { index: '.ze-index', alias: '.muchacha' } }, - ], - }); - return true; - case 'indices.refresh': - expect(arg.index).toEqual('.ze-index'); - return true; - default: - throw new Error(`Dunnoes what ${path} means.`); - } - }); + client.indices.getAlias.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + '.my-fanci-index': '.muchacha', + }) + ); - await Index.claimAlias(callCluster as any, '.ze-index', '.muchacha', [ + await Index.claimAlias(client, '.ze-index', '.muchacha', [ { remove_index: { index: 'awww-snap!' } }, ]); - assertCalled(callCluster); + expect(client.indices.getAlias).toHaveBeenCalledTimes(1); + expect(client.indices.updateAliases).toHaveBeenCalledWith({ + body: { + actions: [ + { remove_index: { index: 'awww-snap!' } }, + { remove: { index: '.my-fanci-index', alias: '.muchacha' } }, + { add: { index: '.ze-index', alias: '.muchacha' } }, + ], + }, + }); + expect(client.indices.refresh).toHaveBeenCalledWith({ + index: '.ze-index', + }); }); }); describe('convertToAlias', () => { test('it creates the destination index, then reindexes to it', async () => { - const callCluster = jest.fn(async (path: string, arg: any) => { - switch (path) { - case 'indices.create': - expect(arg.body).toEqual({ - mappings: { - dynamic: 'strict', - properties: { foo: { type: 'keyword' } }, - }, - settings: { auto_expand_replicas: '0-1', number_of_shards: 1 }, - }); - expect(arg.index).toEqual('.ze-index'); - return true; - case 'reindex': - expect(arg).toMatchObject({ - body: { - dest: { index: '.ze-index' }, - source: { index: '.muchacha' }, - script: { - source: `ctx._id = ctx._source.type + ':' + ctx._id`, - lang: 'painless', - }, - }, - refresh: true, - waitForCompletion: false, - }); - return { task: 'abc' }; - case 'tasks.get': - expect(arg.taskId).toEqual('abc'); - return { completed: true }; - case 'indices.getAlias': - return { '.my-fanci-index': '.muchacha' }; - case 'indices.updateAliases': - expect(arg.body).toEqual({ - actions: [ - { remove_index: { index: '.muchacha' } }, - { remove: { alias: '.muchacha', index: '.my-fanci-index' } }, - { add: { index: '.ze-index', alias: '.muchacha' } }, - ], - }); - return true; - case 'indices.refresh': - expect(arg.index).toEqual('.ze-index'); - return true; - default: - throw new Error(`Dunnoes what ${path} means.`); - } - }); + client.indices.getAlias.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + '.my-fanci-index': '.muchacha', + }) + ); + client.reindex.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ task: 'abc' }) + ); + client.tasks.get.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ completed: true }) + ); const info = { aliases: {}, @@ -271,61 +226,77 @@ describe('ElasticIndex', () => { properties: { foo: { type: 'keyword' } }, }, }; + await Index.convertToAlias( - callCluster as any, + client, info, '.muchacha', 10, `ctx._id = ctx._source.type + ':' + ctx._id` ); - expect(callCluster.mock.calls.map(([path]) => path)).toEqual([ - 'indices.create', - 'reindex', - 'tasks.get', - 'indices.getAlias', - 'indices.updateAliases', - 'indices.refresh', - ]); + expect(client.indices.create).toHaveBeenCalledWith({ + body: { + mappings: { + dynamic: 'strict', + properties: { foo: { type: 'keyword' } }, + }, + settings: { auto_expand_replicas: '0-1', number_of_shards: 1 }, + }, + index: '.ze-index', + }); + + expect(client.reindex).toHaveBeenCalledWith({ + body: { + dest: { index: '.ze-index' }, + source: { index: '.muchacha', size: 10 }, + script: { + source: `ctx._id = ctx._source.type + ':' + ctx._id`, + lang: 'painless', + }, + }, + refresh: true, + wait_for_completion: false, + }); + + expect(client.tasks.get).toHaveBeenCalledWith({ + task_id: 'abc', + }); + + expect(client.indices.updateAliases).toHaveBeenCalledWith({ + body: { + actions: [ + { remove_index: { index: '.muchacha' } }, + { remove: { alias: '.muchacha', index: '.my-fanci-index' } }, + { add: { index: '.ze-index', alias: '.muchacha' } }, + ], + }, + }); + + expect(client.indices.refresh).toHaveBeenCalledWith({ + index: '.ze-index', + }); }); test('throws error if re-index task fails', async () => { - const callCluster = jest.fn(async (path: string, arg: any) => { - switch (path) { - case 'indices.create': - expect(arg.body).toEqual({ - mappings: { - dynamic: 'strict', - properties: { foo: { type: 'keyword' } }, - }, - settings: { auto_expand_replicas: '0-1', number_of_shards: 1 }, - }); - expect(arg.index).toEqual('.ze-index'); - return true; - case 'reindex': - expect(arg).toMatchObject({ - body: { - dest: { index: '.ze-index' }, - source: { index: '.muchacha' }, - }, - refresh: true, - waitForCompletion: false, - }); - return { task: 'abc' }; - case 'tasks.get': - expect(arg.taskId).toEqual('abc'); - return { - completed: true, - error: { - type: 'search_phase_execution_exception', - reason: 'all shards failed', - failed_shards: [], - }, - }; - default: - throw new Error(`Dunnoes what ${path} means.`); - } - }); + client.indices.getAlias.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + '.my-fanci-index': '.muchacha', + }) + ); + client.reindex.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ task: 'abc' }) + ); + client.tasks.get.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + completed: true, + error: { + type: 'search_phase_execution_exception', + reason: 'all shards failed', + failed_shards: [], + }, + }) + ); const info = { aliases: {}, @@ -336,22 +307,44 @@ describe('ElasticIndex', () => { properties: { foo: { type: 'keyword' } }, }, }; - await expect(Index.convertToAlias(callCluster as any, info, '.muchacha', 10)).rejects.toThrow( + + await expect(Index.convertToAlias(client, info, '.muchacha', 10)).rejects.toThrow( /Re-index failed \[search_phase_execution_exception\] all shards failed/ ); - expect(callCluster.mock.calls.map(([path]) => path)).toEqual([ - 'indices.create', - 'reindex', - 'tasks.get', - ]); + expect(client.indices.create).toHaveBeenCalledWith({ + body: { + mappings: { + dynamic: 'strict', + properties: { foo: { type: 'keyword' } }, + }, + settings: { auto_expand_replicas: '0-1', number_of_shards: 1 }, + }, + index: '.ze-index', + }); + + expect(client.reindex).toHaveBeenCalledWith({ + body: { + dest: { index: '.ze-index' }, + source: { index: '.muchacha', size: 10 }, + }, + refresh: true, + wait_for_completion: false, + }); + + expect(client.tasks.get).toHaveBeenCalledWith({ + task_id: 'abc', + }); }); }); describe('write', () => { test('writes documents in bulk to the index', async () => { + client.bulk.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ items: [] }) + ); + const index = '.myalias'; - const callCluster = jest.fn().mockResolvedValue({ items: [] }); const docs = [ { _id: 'niceguy:fredrogers', @@ -375,19 +368,20 @@ describe('ElasticIndex', () => { }, ]; - await Index.write(callCluster, index, docs); + await Index.write(client, index, docs); - expect(callCluster).toHaveBeenCalled(); - expect(callCluster.mock.calls[0]).toMatchSnapshot(); + expect(client.bulk).toHaveBeenCalled(); + expect(client.bulk.mock.calls[0]).toMatchSnapshot(); }); test('fails if any document fails', async () => { - const index = '.myalias'; - const callCluster = jest.fn(() => - Promise.resolve({ + client.bulk.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ items: [{ index: { error: { type: 'shazm', reason: 'dern' } } }], }) ); + + const index = '.myalias'; const docs = [ { _id: 'niceguy:fredrogers', @@ -400,23 +394,20 @@ describe('ElasticIndex', () => { }, ]; - await expect(Index.write(callCluster as any, index, docs)).rejects.toThrow(/dern/); - expect(callCluster).toHaveBeenCalled(); + await expect(Index.write(client as any, index, docs)).rejects.toThrow(/dern/); + expect(client.bulk).toHaveBeenCalledTimes(1); }); }); describe('reader', () => { test('returns docs in batches', async () => { const index = '.myalias'; - const callCluster = jest.fn(); - const batch1 = [ { _id: 'such:1', _source: { type: 'such', such: { num: 1 } }, }, ]; - const batch2 = [ { _id: 'aaa:2', @@ -432,42 +423,56 @@ describe('ElasticIndex', () => { }, ]; - callCluster - .mockResolvedValueOnce({ + client.search = jest.fn().mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ _scroll_id: 'x', _shards: { success: 1, total: 1 }, hits: { hits: _.cloneDeep(batch1) }, }) - .mockResolvedValueOnce({ - _scroll_id: 'y', - _shards: { success: 1, total: 1 }, - hits: { hits: _.cloneDeep(batch2) }, - }) - .mockResolvedValueOnce({ - _scroll_id: 'z', - _shards: { success: 1, total: 1 }, - hits: { hits: [] }, - }) - .mockResolvedValue({}); - - const read = Index.reader(callCluster, index, { batchSize: 100, scrollDuration: '5m' }); + ); + client.scroll = jest + .fn() + .mockReturnValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + _scroll_id: 'y', + _shards: { success: 1, total: 1 }, + hits: { hits: _.cloneDeep(batch2) }, + }) + ) + .mockReturnValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + _scroll_id: 'z', + _shards: { success: 1, total: 1 }, + hits: { hits: [] }, + }) + ); + + const read = Index.reader(client, index, { batchSize: 100, scrollDuration: '5m' }); expect(await read()).toEqual(batch1); expect(await read()).toEqual(batch2); expect(await read()).toEqual([]); - // Check order of calls, as well as args - expect(callCluster.mock.calls).toEqual([ - ['search', { body: { size: 100 }, index, scroll: '5m' }], - ['scroll', { scroll: '5m', scrollId: 'x' }], - ['scroll', { scroll: '5m', scrollId: 'y' }], - ['clearScroll', { scrollId: 'z' }], - ]); + expect(client.search).toHaveBeenCalledWith({ + body: { size: 100 }, + index, + scroll: '5m', + }); + expect(client.scroll).toHaveBeenCalledWith({ + scroll: '5m', + scroll_id: 'x', + }); + expect(client.scroll).toHaveBeenCalledWith({ + scroll: '5m', + scroll_id: 'y', + }); + expect(client.clearScroll).toHaveBeenCalledWith({ + scroll_id: 'z', + }); }); test('returns all root-level properties', async () => { const index = '.myalias'; - const callCluster = jest.fn(); const batch = [ { _id: 'such:1', @@ -480,19 +485,22 @@ describe('ElasticIndex', () => { }, ]; - callCluster - .mockResolvedValueOnce({ + client.search = jest.fn().mockReturnValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ _scroll_id: 'x', _shards: { success: 1, total: 1 }, hits: { hits: _.cloneDeep(batch) }, }) - .mockResolvedValue({ + ); + client.scroll = jest.fn().mockReturnValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ _scroll_id: 'z', _shards: { success: 1, total: 1 }, hits: { hits: [] }, - }); + }) + ); - const read = Index.reader(callCluster, index, { + const read = Index.reader(client, index, { batchSize: 100, scrollDuration: '5m', }); @@ -502,11 +510,14 @@ describe('ElasticIndex', () => { test('fails if not all shards were successful', async () => { const index = '.myalias'; - const callCluster = jest.fn(); - callCluster.mockResolvedValue({ _shards: { successful: 1, total: 2 } }); + client.search = jest.fn().mockReturnValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + _shards: { successful: 1, total: 2 }, + }) + ); - const read = Index.reader(callCluster, index, { + const read = Index.reader(client, index, { batchSize: 100, scrollDuration: '5m', }); @@ -516,7 +527,6 @@ describe('ElasticIndex', () => { test('handles shards not being returned', async () => { const index = '.myalias'; - const callCluster = jest.fn(); const batch = [ { _id: 'such:1', @@ -529,11 +539,20 @@ describe('ElasticIndex', () => { }, ]; - callCluster - .mockResolvedValueOnce({ _scroll_id: 'x', hits: { hits: _.cloneDeep(batch) } }) - .mockResolvedValue({ _scroll_id: 'z', hits: { hits: [] } }); + client.search = jest.fn().mockReturnValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + _scroll_id: 'x', + hits: { hits: _.cloneDeep(batch) }, + }) + ); + client.scroll = jest.fn().mockReturnValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + _scroll_id: 'z', + hits: { hits: [] }, + }) + ); - const read = Index.reader(callCluster, index, { + const read = Index.reader(client, index, { batchSize: 100, scrollDuration: '5m', }); @@ -550,23 +569,24 @@ describe('ElasticIndex', () => { count, migrations, }: any) { - const callCluster = jest.fn(async (path: string) => { - if (path === 'indices.get') { - return { - [index]: { mappings }, - }; - } - if (path === 'count') { - return { count, _shards: { success: 1, total: 1 } }; - } - throw new Error(`Unknown command ${path}.`); - }); - const hasMigrations = await Index.migrationsUpToDate(callCluster as any, index, migrations); - return { hasMigrations, callCluster }; + client.indices.get = jest.fn().mockReturnValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + [index]: { mappings }, + }) + ); + client.count = jest.fn().mockReturnValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + count, + _shards: { success: 1, total: 1 }, + }) + ); + + const hasMigrations = await Index.migrationsUpToDate(client, index, migrations); + return { hasMigrations }; } test('is false if the index mappings do not contain migrationVersion', async () => { - const { hasMigrations, callCluster } = await testMigrationsUpToDate({ + const { hasMigrations } = await testMigrationsUpToDate({ index: '.myalias', mappings: { properties: { @@ -578,17 +598,18 @@ describe('ElasticIndex', () => { }); expect(hasMigrations).toBeFalsy(); - expect(callCluster.mock.calls[0]).toEqual([ - 'indices.get', + expect(client.indices.get).toHaveBeenCalledWith( { - ignore: [404], index: '.myalias', }, - ]); + { + ignore: [404], + } + ); }); test('is true if there are no migrations defined', async () => { - const { hasMigrations, callCluster } = await testMigrationsUpToDate({ + const { hasMigrations } = await testMigrationsUpToDate({ index: '.myalias', mappings: { properties: { @@ -604,12 +625,11 @@ describe('ElasticIndex', () => { }); expect(hasMigrations).toBeTruthy(); - expect(callCluster).toHaveBeenCalled(); - expect(callCluster.mock.calls[0][0]).toEqual('indices.get'); + expect(client.indices.get).toHaveBeenCalledTimes(1); }); test('is true if there are no documents out of date', async () => { - const { hasMigrations, callCluster } = await testMigrationsUpToDate({ + const { hasMigrations } = await testMigrationsUpToDate({ index: '.myalias', mappings: { properties: { @@ -625,13 +645,12 @@ describe('ElasticIndex', () => { }); expect(hasMigrations).toBeTruthy(); - expect(callCluster).toHaveBeenCalled(); - expect(callCluster.mock.calls[0][0]).toEqual('indices.get'); - expect(callCluster.mock.calls[1][0]).toEqual('count'); + expect(client.indices.get).toHaveBeenCalledTimes(1); + expect(client.count).toHaveBeenCalledTimes(1); }); test('is false if there are documents out of date', async () => { - const { hasMigrations, callCluster } = await testMigrationsUpToDate({ + const { hasMigrations } = await testMigrationsUpToDate({ index: '.myalias', mappings: { properties: { @@ -647,12 +666,12 @@ describe('ElasticIndex', () => { }); expect(hasMigrations).toBeFalsy(); - expect(callCluster.mock.calls[0][0]).toEqual('indices.get'); - expect(callCluster.mock.calls[1][0]).toEqual('count'); + expect(client.indices.get).toHaveBeenCalledTimes(1); + expect(client.count).toHaveBeenCalledTimes(1); }); test('counts docs that are out of date', async () => { - const { callCluster } = await testMigrationsUpToDate({ + await testMigrationsUpToDate({ index: '.myalias', mappings: { properties: { @@ -686,23 +705,20 @@ describe('ElasticIndex', () => { }; } - expect(callCluster.mock.calls[1]).toEqual([ - 'count', - { - body: { - query: { - bool: { - should: [ - shouldClause('dashy', '23.2.5'), - shouldClause('bashy', '99.9.3'), - shouldClause('flashy', '3.4.5'), - ], - }, + expect(client.count).toHaveBeenCalledWith({ + body: { + query: { + bool: { + should: [ + shouldClause('dashy', '23.2.5'), + shouldClause('bashy', '99.9.3'), + shouldClause('flashy', '3.4.5'), + ], }, }, - index: '.myalias', }, - ]); + index: '.myalias', + }); }); }); }); diff --git a/src/core/server/saved_objects/migrations/core/elastic_index.ts b/src/core/server/saved_objects/migrations/core/elastic_index.ts index e87c3e3ff0d64..d5093bfd8dc42 100644 --- a/src/core/server/saved_objects/migrations/core/elastic_index.ts +++ b/src/core/server/saved_objects/migrations/core/elastic_index.ts @@ -23,9 +23,12 @@ */ import _ from 'lodash'; +import { MigrationEsClient } from './migration_es_client'; +import { CountResponse, SearchResponse } from '../../../elasticsearch'; import { IndexMapping } from '../../mappings'; import { SavedObjectsMigrationVersion } from '../../types'; -import { AliasAction, CallCluster, NotFound, RawDoc, ShardsInfo } from './call_cluster'; +import { AliasAction, RawDoc, ShardsInfo } from './call_cluster'; +import { SavedObjectsRawDocSource } from '../../serialization'; const settings = { number_of_shards: 1, auto_expand_replicas: '0-1' }; @@ -40,13 +43,10 @@ export interface FullIndexInfo { * A slight enhancement to indices.get, that adds indexName, and validates that the * index mappings are somewhat what we expect. */ -export async function fetchInfo(callCluster: CallCluster, index: string): Promise { - const result = await callCluster('indices.get', { - ignore: [404], - index, - }); +export async function fetchInfo(client: MigrationEsClient, index: string): Promise { + const { body, statusCode } = await client.indices.get({ index }, { ignore: [404] }); - if ((result as NotFound).status === 404) { + if (statusCode === 404) { return { aliases: {}, exists: false, @@ -55,7 +55,7 @@ export async function fetchInfo(callCluster: CallCluster, index: string): Promis }; } - const [indexName, indexInfo] = Object.entries(result)[0]; + const [indexName, indexInfo] = Object.entries(body)[0]; return assertIsSupportedIndex({ ...indexInfo, exists: true, indexName }); } @@ -71,7 +71,7 @@ export async function fetchInfo(callCluster: CallCluster, index: string): Promis * @prop {string} scrollDuration - The scroll duration used for scrolling through the index */ export function reader( - callCluster: CallCluster, + client: MigrationEsClient, index: string, { batchSize = 10, scrollDuration = '15m' }: { batchSize: number; scrollDuration: string } ) { @@ -80,19 +80,24 @@ export function reader( const nextBatch = () => scrollId !== undefined - ? callCluster('scroll', { scroll, scrollId }) - : callCluster('search', { body: { size: batchSize }, index, scroll }); - - const close = async () => scrollId && (await callCluster('clearScroll', { scrollId })); + ? client.scroll>({ + scroll, + scroll_id: scrollId, + }) + : client.search>({ + body: { size: batchSize }, + index, + scroll, + }); + + const close = async () => scrollId && (await client.clearScroll({ scroll_id: scrollId })); return async function read() { const result = await nextBatch(); - assertResponseIncludeAllShards(result); - - const docs = result.hits.hits; - - scrollId = result._scroll_id; + assertResponseIncludeAllShards(result.body); + scrollId = result.body._scroll_id; + const docs = result.body.hits.hits; if (!docs.length) { await close(); } @@ -109,8 +114,8 @@ export function reader( * @param {string} index * @param {RawDoc[]} docs */ -export async function write(callCluster: CallCluster, index: string, docs: RawDoc[]) { - const result = await callCluster('bulk', { +export async function write(client: MigrationEsClient, index: string, docs: RawDoc[]) { + const { body } = await client.bulk({ body: docs.reduce((acc: object[], doc: RawDoc) => { acc.push({ index: { @@ -125,7 +130,7 @@ export async function write(callCluster: CallCluster, index: string, docs: RawDo }, []), }); - const err = _.find(result.items, 'index.error.reason'); + const err = _.find(body.items, 'index.error.reason'); if (!err) { return; @@ -150,15 +155,15 @@ export async function write(callCluster: CallCluster, index: string, docs: RawDo * @param {SavedObjectsMigrationVersion} migrationVersion - The latest versions of the migrations */ export async function migrationsUpToDate( - callCluster: CallCluster, + client: MigrationEsClient, index: string, migrationVersion: SavedObjectsMigrationVersion, retryCount: number = 10 ): Promise { try { - const indexInfo = await fetchInfo(callCluster, index); + const indexInfo = await fetchInfo(client, index); - if (!_.get(indexInfo, 'mappings.properties.migrationVersion')) { + if (!indexInfo.mappings.properties?.migrationVersion) { return false; } @@ -167,7 +172,7 @@ export async function migrationsUpToDate( return true; } - const response = await callCluster('count', { + const { body } = await client.count({ body: { query: { bool: { @@ -175,7 +180,11 @@ export async function migrationsUpToDate( bool: { must: [ { exists: { field: type } }, - { bool: { must_not: { term: { [`migrationVersion.${type}`]: latestVersion } } } }, + { + bool: { + must_not: { term: { [`migrationVersion.${type}`]: latestVersion } }, + }, + }, ], }, })), @@ -185,9 +194,9 @@ export async function migrationsUpToDate( index, }); - assertResponseIncludeAllShards(response); + assertResponseIncludeAllShards(body); - return response.count === 0; + return body.count === 0; } catch (e) { // retry for Service Unavailable if (e.status !== 503 || retryCount === 0) { @@ -196,23 +205,23 @@ export async function migrationsUpToDate( await new Promise((r) => setTimeout(r, 1000)); - return await migrationsUpToDate(callCluster, index, migrationVersion, retryCount - 1); + return await migrationsUpToDate(client, index, migrationVersion, retryCount - 1); } } export async function createIndex( - callCluster: CallCluster, + client: MigrationEsClient, index: string, mappings?: IndexMapping ) { - await callCluster('indices.create', { + await client.indices.create({ body: { mappings, settings }, index, }); } -export async function deleteIndex(callCluster: CallCluster, index: string) { - await callCluster('indices.delete', { index }); +export async function deleteIndex(client: MigrationEsClient, index: string) { + await client.indices.delete({ index }); } /** @@ -225,20 +234,20 @@ export async function deleteIndex(callCluster: CallCluster, index: string) { * @param {string} alias - The name of the index being converted to an alias */ export async function convertToAlias( - callCluster: CallCluster, + client: MigrationEsClient, info: FullIndexInfo, alias: string, batchSize: number, script?: string ) { - await callCluster('indices.create', { + await client.indices.create({ body: { mappings: info.mappings, settings }, index: info.indexName, }); - await reindex(callCluster, alias, info.indexName, batchSize, script); + await reindex(client, alias, info.indexName, batchSize, script); - await claimAlias(callCluster, info.indexName, alias, [{ remove_index: { index: alias } }]); + await claimAlias(client, info.indexName, alias, [{ remove_index: { index: alias } }]); } /** @@ -252,22 +261,22 @@ export async function convertToAlias( * @param {AliasAction[]} aliasActions - Optional actions to be added to the updateAliases call */ export async function claimAlias( - callCluster: CallCluster, + client: MigrationEsClient, index: string, alias: string, aliasActions: AliasAction[] = [] ) { - const result = await callCluster('indices.getAlias', { ignore: [404], name: alias }); - const aliasInfo = (result as NotFound).status === 404 ? {} : result; + const { body, statusCode } = await client.indices.getAlias({ name: alias }, { ignore: [404] }); + const aliasInfo = statusCode === 404 ? {} : body; const removeActions = Object.keys(aliasInfo).map((key) => ({ remove: { index: key, alias } })); - await callCluster('indices.updateAliases', { + await client.indices.updateAliases({ body: { actions: aliasActions.concat(removeActions).concat({ add: { index, alias } }), }, }); - await callCluster('indices.refresh', { index }); + await client.indices.refresh({ index }); } /** @@ -318,7 +327,7 @@ function assertResponseIncludeAllShards({ _shards }: { _shards: ShardsInfo }) { * Reindexes from source to dest, polling for the reindex completion. */ async function reindex( - callCluster: CallCluster, + client: MigrationEsClient, source: string, dest: string, batchSize: number, @@ -329,7 +338,7 @@ async function reindex( // polling interval, as the request is fairly efficent, and we don't // want to block index migrations for too long on this. const pollInterval = 250; - const { task } = await callCluster('reindex', { + const { body: reindexBody } = await client.reindex({ body: { dest: { index: dest }, source: { index: source, size: batchSize }, @@ -341,23 +350,25 @@ async function reindex( : undefined, }, refresh: true, - waitForCompletion: false, + wait_for_completion: false, }); + const task = reindexBody.task; + let completed = false; while (!completed) { await new Promise((r) => setTimeout(r, pollInterval)); - completed = await callCluster('tasks.get', { - taskId: task, - }).then((result) => { - if (result.error) { - const e = result.error; - throw new Error(`Re-index failed [${e.type}] ${e.reason} :: ${JSON.stringify(e)}`); - } - - return result.completed; + const { body } = await client.tasks.get({ + task_id: task, }); + + if (body.error) { + const e = body.error; + throw new Error(`Re-index failed [${e.type}] ${e.reason} :: ${JSON.stringify(e)}`); + } + + completed = body.completed; } } diff --git a/src/core/server/saved_objects/migrations/core/index.ts b/src/core/server/saved_objects/migrations/core/index.ts index f7274740ea5fe..c9d3d2a71c9ad 100644 --- a/src/core/server/saved_objects/migrations/core/index.ts +++ b/src/core/server/saved_objects/migrations/core/index.ts @@ -23,3 +23,4 @@ export { buildActiveMappings } from './build_active_mappings'; export { CallCluster } from './call_cluster'; export { LogFn, SavedObjectsMigrationLogger } from './migration_logger'; export { MigrationResult, MigrationStatus } from './migration_coordinator'; +export { createMigrationEsClient, MigrationEsClient } from './migration_es_client'; diff --git a/src/core/server/saved_objects/migrations/core/index_migrator.test.ts b/src/core/server/saved_objects/migrations/core/index_migrator.test.ts index f8b203bf66d6a..78601d033f8d8 100644 --- a/src/core/server/saved_objects/migrations/core/index_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/core/index_migrator.test.ts @@ -18,18 +18,22 @@ */ import _ from 'lodash'; +import { elasticsearchClientMock } from '../../../elasticsearch/client/mocks'; import { SavedObjectUnsanitizedDoc, SavedObjectsSerializer } from '../../serialization'; import { SavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import { IndexMigrator } from './index_migrator'; +import { MigrationOpts } from './migration_context'; import { loggingSystemMock } from '../../../logging/logging_system.mock'; describe('IndexMigrator', () => { - let testOpts: any; + let testOpts: jest.Mocked & { + client: ReturnType; + }; beforeEach(() => { testOpts = { batchSize: 10, - callCluster: jest.fn(), + client: elasticsearchClientMock.createElasticSearchClient(), index: '.kibana', log: loggingSystemMock.create().get(), mappingProperties: {}, @@ -44,15 +48,15 @@ describe('IndexMigrator', () => { }); test('creates the index if it does not exist', async () => { - const { callCluster } = testOpts; + const { client } = testOpts; - testOpts.mappingProperties = { foo: { type: 'long' } }; + testOpts.mappingProperties = { foo: { type: 'long' } as any }; - withIndex(callCluster, { index: { status: 404 }, alias: { status: 404 } }); + withIndex(client, { index: { statusCode: 404 }, alias: { statusCode: 404 } }); await new IndexMigrator(testOpts).migrate(); - expect(callCluster).toHaveBeenCalledWith('indices.create', { + expect(client.indices.create).toHaveBeenCalledWith({ body: { mappings: { dynamic: 'strict', @@ -91,9 +95,9 @@ describe('IndexMigrator', () => { }); test('returns stats about the migration', async () => { - const { callCluster } = testOpts; + const { client } = testOpts; - withIndex(callCluster, { index: { status: 404 }, alias: { status: 404 } }); + withIndex(client, { index: { statusCode: 404 }, alias: { statusCode: 404 } }); const result = await new IndexMigrator(testOpts).migrate(); @@ -105,9 +109,9 @@ describe('IndexMigrator', () => { }); test('fails if there are multiple root doc types', async () => { - const { callCluster } = testOpts; + const { client } = testOpts; - withIndex(callCluster, { + withIndex(client, { index: { '.kibana_1': { aliases: {}, @@ -129,9 +133,9 @@ describe('IndexMigrator', () => { }); test('fails if root doc type is not "doc"', async () => { - const { callCluster } = testOpts; + const { client } = testOpts; - withIndex(callCluster, { + withIndex(client, { index: { '.kibana_1': { aliases: {}, @@ -152,11 +156,11 @@ describe('IndexMigrator', () => { }); test('retains unknown core field mappings from the previous index', async () => { - const { callCluster } = testOpts; + const { client } = testOpts; - testOpts.mappingProperties = { foo: { type: 'text' } }; + testOpts.mappingProperties = { foo: { type: 'text' } as any }; - withIndex(callCluster, { + withIndex(client, { index: { '.kibana_1': { aliases: {}, @@ -171,7 +175,7 @@ describe('IndexMigrator', () => { await new IndexMigrator(testOpts).migrate(); - expect(callCluster).toHaveBeenCalledWith('indices.create', { + expect(client.indices.create).toHaveBeenCalledWith({ body: { mappings: { dynamic: 'strict', @@ -211,11 +215,11 @@ describe('IndexMigrator', () => { }); test('disables complex field mappings from unknown types in the previous index', async () => { - const { callCluster } = testOpts; + const { client } = testOpts; - testOpts.mappingProperties = { foo: { type: 'text' } }; + testOpts.mappingProperties = { foo: { type: 'text' } as any }; - withIndex(callCluster, { + withIndex(client, { index: { '.kibana_1': { aliases: {}, @@ -230,7 +234,7 @@ describe('IndexMigrator', () => { await new IndexMigrator(testOpts).migrate(); - expect(callCluster).toHaveBeenCalledWith('indices.create', { + expect(client.indices.create).toHaveBeenCalledWith({ body: { mappings: { dynamic: 'strict', @@ -270,31 +274,31 @@ describe('IndexMigrator', () => { }); test('points the alias at the dest index', async () => { - const { callCluster } = testOpts; + const { client } = testOpts; - withIndex(callCluster, { index: { status: 404 }, alias: { status: 404 } }); + withIndex(client, { index: { statusCode: 404 }, alias: { statusCode: 404 } }); await new IndexMigrator(testOpts).migrate(); - expect(callCluster).toHaveBeenCalledWith('indices.create', expect.any(Object)); - expect(callCluster).toHaveBeenCalledWith('indices.updateAliases', { + expect(client.indices.create).toHaveBeenCalledWith(expect.any(Object)); + expect(client.indices.updateAliases).toHaveBeenCalledWith({ body: { actions: [{ add: { alias: '.kibana', index: '.kibana_1' } }] }, }); }); test('removes previous indices from the alias', async () => { - const { callCluster } = testOpts; + const { client } = testOpts; testOpts.documentMigrator.migrationVersion = { dashboard: '2.4.5', }; - withIndex(callCluster, { numOutOfDate: 1 }); + withIndex(client, { numOutOfDate: 1 }); await new IndexMigrator(testOpts).migrate(); - expect(callCluster).toHaveBeenCalledWith('indices.create', expect.any(Object)); - expect(callCluster).toHaveBeenCalledWith('indices.updateAliases', { + expect(client.indices.create).toHaveBeenCalledWith(expect.any(Object)); + expect(client.indices.updateAliases).toHaveBeenCalledWith({ body: { actions: [ { remove: { alias: '.kibana', index: '.kibana_1' } }, @@ -306,7 +310,7 @@ describe('IndexMigrator', () => { test('transforms all docs from the original index', async () => { let count = 0; - const { callCluster } = testOpts; + const { client } = testOpts; const migrateDoc = jest.fn((doc: SavedObjectUnsanitizedDoc) => { return { ...doc, @@ -319,7 +323,7 @@ describe('IndexMigrator', () => { migrate: migrateDoc, }; - withIndex(callCluster, { + withIndex(client, { numOutOfDate: 1, docs: [ [{ _id: 'foo:1', _source: { type: 'foo', foo: { name: 'Bar' } } }], @@ -344,30 +348,27 @@ describe('IndexMigrator', () => { migrationVersion: {}, references: [], }); - const bulkCalls = callCluster.mock.calls.filter(([action]: any) => action === 'bulk'); - expect(bulkCalls.length).toEqual(2); - expect(bulkCalls[0]).toEqual([ - 'bulk', - { - body: [ - { index: { _id: 'foo:1', _index: '.kibana_2' } }, - { foo: { name: 1 }, type: 'foo', migrationVersion: {}, references: [] }, - ], - }, - ]); - expect(bulkCalls[1]).toEqual([ - 'bulk', - { - body: [ - { index: { _id: 'foo:2', _index: '.kibana_2' } }, - { foo: { name: 2 }, type: 'foo', migrationVersion: {}, references: [] }, - ], - }, - ]); + + expect(client.bulk).toHaveBeenCalledTimes(2); + expect(client.bulk).toHaveBeenNthCalledWith(1, { + body: [ + { index: { _id: 'foo:1', _index: '.kibana_2' } }, + { foo: { name: 1 }, type: 'foo', migrationVersion: {}, references: [] }, + ], + }); + expect(client.bulk).toHaveBeenNthCalledWith(2, { + body: [ + { index: { _id: 'foo:2', _index: '.kibana_2' } }, + { foo: { name: 2 }, type: 'foo', migrationVersion: {}, references: [] }, + ], + }); }); }); -function withIndex(callCluster: jest.Mock, opts: any = {}) { +function withIndex( + client: ReturnType, + opts: any = {} +) { const defaultIndex = { '.kibana_1': { aliases: { '.kibana': {} }, @@ -386,39 +387,56 @@ function withIndex(callCluster: jest.Mock, opts: any = {}) { const { alias = defaultAlias } = opts; const { index = defaultIndex } = opts; const { docs = [] } = opts; - const searchResult = (i: number) => - Promise.resolve({ - _scroll_id: i, - _shards: { - successful: 1, - total: 1, - }, - hits: { - hits: docs[i] || [], - }, - }); + const searchResult = (i: number) => ({ + _scroll_id: i, + _shards: { + successful: 1, + total: 1, + }, + hits: { + hits: docs[i] || [], + }, + }); let scrollCallCounter = 1; - callCluster.mockImplementation((method) => { - if (method === 'indices.get') { - return Promise.resolve(index); - } else if (method === 'indices.getAlias') { - return Promise.resolve(alias); - } else if (method === 'reindex') { - return Promise.resolve({ task: 'zeid', _shards: { successful: 1, total: 1 } }); - } else if (method === 'tasks.get') { - return Promise.resolve({ completed: true }); - } else if (method === 'search') { - return searchResult(0); - } else if (method === 'bulk') { - return Promise.resolve({ items: [] }); - } else if (method === 'count') { - return Promise.resolve({ count: numOutOfDate, _shards: { successful: 1, total: 1 } }); - } else if (method === 'scroll' && scrollCallCounter <= docs.length) { + client.indices.get.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise(index, { + statusCode: index.statusCode, + }) + ); + client.indices.getAlias.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise(alias, { + statusCode: index.statusCode, + }) + ); + client.reindex.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + task: 'zeid', + _shards: { successful: 1, total: 1 }, + }) + ); + client.tasks.get.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ completed: true }) + ); + client.search.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise(searchResult(0)) + ); + client.bulk.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ items: [] }) + ); + client.count.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + count: numOutOfDate, + _shards: { successful: 1, total: 1 }, + }) + ); + client.scroll.mockImplementation(() => { + if (scrollCallCounter <= docs.length) { const result = searchResult(scrollCallCounter); scrollCallCounter++; - return result; + return elasticsearchClientMock.createSuccessTransportRequestPromise(result); } + return elasticsearchClientMock.createSuccessTransportRequestPromise({}); }); } diff --git a/src/core/server/saved_objects/migrations/core/index_migrator.ts b/src/core/server/saved_objects/migrations/core/index_migrator.ts index e588eb7877322..ceca27fa87723 100644 --- a/src/core/server/saved_objects/migrations/core/index_migrator.ts +++ b/src/core/server/saved_objects/migrations/core/index_migrator.ts @@ -16,7 +16,6 @@ * specific language governing permissions and limitations * under the License. */ - import { diffMappings } from './build_active_mappings'; import * as Index from './elastic_index'; import { migrateRawDocs } from './migrate_raw_docs'; @@ -71,11 +70,11 @@ export class IndexMigrator { * Determines what action the migration system needs to take (none, patch, migrate). */ async function requiresMigration(context: Context): Promise { - const { callCluster, alias, documentMigrator, dest, log } = context; + const { client, alias, documentMigrator, dest, log } = context; // Have all of our known migrations been run against the index? const hasMigrations = await Index.migrationsUpToDate( - callCluster, + client, alias, documentMigrator.migrationVersion ); @@ -85,7 +84,7 @@ async function requiresMigration(context: Context): Promise { } // Is our index aliased? - const refreshedSource = await Index.fetchInfo(callCluster, alias); + const refreshedSource = await Index.fetchInfo(client, alias); if (!refreshedSource.aliases[alias]) { return true; @@ -109,19 +108,19 @@ async function requiresMigration(context: Context): Promise { */ async function migrateIndex(context: Context): Promise { const startTime = Date.now(); - const { callCluster, alias, source, dest, log } = context; + const { client, alias, source, dest, log } = context; await deleteIndexTemplates(context); log.info(`Creating index ${dest.indexName}.`); - await Index.createIndex(callCluster, dest.indexName, dest.mappings); + await Index.createIndex(client, dest.indexName, dest.mappings); await migrateSourceToDest(context); log.info(`Pointing alias ${alias} to ${dest.indexName}.`); - await Index.claimAlias(callCluster, dest.indexName, alias); + await Index.claimAlias(client, dest.indexName, alias); const result: MigrationResult = { status: 'migrated', @@ -139,12 +138,12 @@ async function migrateIndex(context: Context): Promise { * If the obsoleteIndexTemplatePattern option is specified, this will delete any index templates * that match it. */ -async function deleteIndexTemplates({ callCluster, log, obsoleteIndexTemplatePattern }: Context) { +async function deleteIndexTemplates({ client, log, obsoleteIndexTemplatePattern }: Context) { if (!obsoleteIndexTemplatePattern) { return; } - const templates = await callCluster('cat.templates', { + const { body: templates } = await client.cat.templates>({ format: 'json', name: obsoleteIndexTemplatePattern, }); @@ -157,7 +156,7 @@ async function deleteIndexTemplates({ callCluster, log, obsoleteIndexTemplatePat log.info(`Removing index templates: ${templateNames}`); - return Promise.all(templateNames.map((name) => callCluster('indices.deleteTemplate', { name }))); + return Promise.all(templateNames.map((name) => client.indices.deleteTemplate({ name }))); } /** @@ -166,7 +165,7 @@ async function deleteIndexTemplates({ callCluster, log, obsoleteIndexTemplatePat * a situation where the alias moves out from under us as we're migrating docs. */ async function migrateSourceToDest(context: Context) { - const { callCluster, alias, dest, source, batchSize } = context; + const { client, alias, dest, source, batchSize } = context; const { scrollDuration, documentMigrator, log, serializer } = context; if (!source.exists) { @@ -176,10 +175,10 @@ async function migrateSourceToDest(context: Context) { if (!source.aliases[alias]) { log.info(`Reindexing ${alias} to ${source.indexName}`); - await Index.convertToAlias(callCluster, source, alias, batchSize, context.convertToAliasScript); + await Index.convertToAlias(client, source, alias, batchSize, context.convertToAliasScript); } - const read = Index.reader(callCluster, source.indexName, { batchSize, scrollDuration }); + const read = Index.reader(client, source.indexName, { batchSize, scrollDuration }); log.info(`Migrating ${source.indexName} saved objects to ${dest.indexName}`); @@ -193,7 +192,7 @@ async function migrateSourceToDest(context: Context) { log.debug(`Migrating saved objects ${docs.map((d) => d._id).join(', ')}`); await Index.write( - callCluster, + client, dest.indexName, await migrateRawDocs(serializer, documentMigrator.migrate, docs, log) ); diff --git a/src/core/server/saved_objects/migrations/core/migration_context.ts b/src/core/server/saved_objects/migrations/core/migration_context.ts index adf1851a1aa75..0ea362d65623e 100644 --- a/src/core/server/saved_objects/migrations/core/migration_context.ts +++ b/src/core/server/saved_objects/migrations/core/migration_context.ts @@ -25,6 +25,7 @@ */ import { Logger } from 'src/core/server/logging'; +import { MigrationEsClient } from './migration_es_client'; import { SavedObjectsSerializer } from '../../serialization'; import { SavedObjectsTypeMappingDefinitions, @@ -32,16 +33,15 @@ import { IndexMapping, } from '../../mappings'; import { buildActiveMappings } from './build_active_mappings'; -import { CallCluster } from './call_cluster'; import { VersionedTransformer } from './document_migrator'; -import { fetchInfo, FullIndexInfo } from './elastic_index'; +import * as Index from './elastic_index'; import { SavedObjectsMigrationLogger, MigrationLogger } from './migration_logger'; export interface MigrationOpts { batchSize: number; pollInterval: number; scrollDuration: string; - callCluster: CallCluster; + client: MigrationEsClient; index: string; log: Logger; mappingProperties: SavedObjectsTypeMappingDefinitions; @@ -56,11 +56,14 @@ export interface MigrationOpts { obsoleteIndexTemplatePattern?: string; } +/** + * @internal + */ export interface Context { - callCluster: CallCluster; + client: MigrationEsClient; alias: string; - source: FullIndexInfo; - dest: FullIndexInfo; + source: Index.FullIndexInfo; + dest: Index.FullIndexInfo; documentMigrator: VersionedTransformer; log: SavedObjectsMigrationLogger; batchSize: number; @@ -76,13 +79,13 @@ export interface Context { * and various info needed to migrate the source index. */ export async function migrationContext(opts: MigrationOpts): Promise { - const { log, callCluster } = opts; + const { log, client } = opts; const alias = opts.index; - const source = createSourceContext(await fetchInfo(callCluster, alias), alias); + const source = createSourceContext(await Index.fetchInfo(client, alias), alias); const dest = createDestContext(source, alias, opts.mappingProperties); return { - callCluster, + client, alias, source, dest, @@ -97,7 +100,7 @@ export async function migrationContext(opts: MigrationOpts): Promise { }; } -function createSourceContext(source: FullIndexInfo, alias: string) { +function createSourceContext(source: Index.FullIndexInfo, alias: string) { if (source.exists && source.indexName === alias) { return { ...source, @@ -109,10 +112,10 @@ function createSourceContext(source: FullIndexInfo, alias: string) { } function createDestContext( - source: FullIndexInfo, + source: Index.FullIndexInfo, alias: string, typeMappingDefinitions: SavedObjectsTypeMappingDefinitions -): FullIndexInfo { +): Index.FullIndexInfo { const targetMappings = disableUnknownTypeMappingFields( buildActiveMappings(typeMappingDefinitions), source.mappings diff --git a/src/core/server/saved_objects/migrations/core/migration_es_client.test.mock.ts b/src/core/server/saved_objects/migrations/core/migration_es_client.test.mock.ts new file mode 100644 index 0000000000000..8ebed25d87cba --- /dev/null +++ b/src/core/server/saved_objects/migrations/core/migration_es_client.test.mock.ts @@ -0,0 +1,22 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +export const migrationRetryCallClusterMock = jest.fn((fn) => fn()); +jest.doMock('../../../elasticsearch/client/retry_call_cluster', () => ({ + migrationRetryCallCluster: migrationRetryCallClusterMock, +})); diff --git a/src/core/server/saved_objects/migrations/core/migration_es_client.test.ts b/src/core/server/saved_objects/migrations/core/migration_es_client.test.ts new file mode 100644 index 0000000000000..40c06677c4a5a --- /dev/null +++ b/src/core/server/saved_objects/migrations/core/migration_es_client.test.ts @@ -0,0 +1,65 @@ +/* + * 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 { migrationRetryCallClusterMock } from './migration_es_client.test.mock'; + +import { createMigrationEsClient, MigrationEsClient } from './migration_es_client'; +import { elasticsearchClientMock } from '../../../elasticsearch/client/mocks'; +import { loggerMock } from '../../../logging/logger.mock'; +import { SavedObjectsErrorHelpers } from '../../service/lib/errors'; + +describe('MigrationEsClient', () => { + let client: ReturnType; + let migrationEsClient: MigrationEsClient; + + beforeEach(() => { + client = elasticsearchClientMock.createElasticSearchClient(); + migrationEsClient = createMigrationEsClient(client, loggerMock.create()); + migrationRetryCallClusterMock.mockClear(); + }); + + it('delegates call to ES client method', async () => { + expect(migrationEsClient.bulk).toStrictEqual(expect.any(Function)); + await migrationEsClient.bulk({ body: [] }); + expect(client.bulk).toHaveBeenCalledTimes(1); + }); + + it('wraps a method call in migrationRetryCallClusterMock', async () => { + await migrationEsClient.bulk({ body: [] }); + expect(migrationRetryCallClusterMock).toHaveBeenCalledTimes(1); + }); + + it('sets maxRetries: 0 to delegate retry logic to migrationRetryCallCluster', async () => { + expect(migrationEsClient.bulk).toStrictEqual(expect.any(Function)); + await migrationEsClient.bulk({ body: [] }); + expect(client.bulk).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ maxRetries: 0 }) + ); + }); + + it('do not transform elasticsearch errors into saved objects errors', async () => { + expect.assertions(1); + client.bulk = jest.fn().mockRejectedValue(new Error('reason')); + try { + await migrationEsClient.bulk({ body: [] }); + } catch (e) { + expect(SavedObjectsErrorHelpers.isSavedObjectsClientError(e)).toBe(false); + } + }); +}); diff --git a/src/core/server/saved_objects/migrations/core/migration_es_client.ts b/src/core/server/saved_objects/migrations/core/migration_es_client.ts new file mode 100644 index 0000000000000..ff859057f8fe8 --- /dev/null +++ b/src/core/server/saved_objects/migrations/core/migration_es_client.ts @@ -0,0 +1,90 @@ +/* + * 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 type { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport'; +import { get } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; + +import { ElasticsearchClient } from '../../../elasticsearch'; +import { migrationRetryCallCluster } from '../../../elasticsearch/client/retry_call_cluster'; +import { Logger } from '../../../logging'; + +const methods = [ + 'bulk', + 'cat.templates', + 'clearScroll', + 'count', + 'indices.create', + 'indices.delete', + 'indices.deleteTemplate', + 'indices.get', + 'indices.getAlias', + 'indices.refresh', + 'indices.updateAliases', + 'reindex', + 'search', + 'scroll', + 'tasks.get', +] as const; + +type MethodName = typeof methods[number]; + +export interface MigrationEsClient { + bulk: ElasticsearchClient['bulk']; + cat: { + templates: ElasticsearchClient['cat']['templates']; + }; + clearScroll: ElasticsearchClient['clearScroll']; + count: ElasticsearchClient['count']; + indices: { + create: ElasticsearchClient['indices']['create']; + delete: ElasticsearchClient['indices']['delete']; + deleteTemplate: ElasticsearchClient['indices']['deleteTemplate']; + get: ElasticsearchClient['indices']['get']; + getAlias: ElasticsearchClient['indices']['getAlias']; + refresh: ElasticsearchClient['indices']['refresh']; + updateAliases: ElasticsearchClient['indices']['updateAliases']; + }; + reindex: ElasticsearchClient['reindex']; + search: ElasticsearchClient['search']; + scroll: ElasticsearchClient['scroll']; + tasks: { + get: ElasticsearchClient['tasks']['get']; + }; +} + +export function createMigrationEsClient( + client: ElasticsearchClient, + log: Logger, + delay?: number +): MigrationEsClient { + return methods.reduce((acc: MigrationEsClient, key: MethodName) => { + set(acc, key, async (params?: unknown, options?: TransportRequestOptions) => { + const fn = get(client, key); + if (!fn) { + throw new Error(`unknown ElasticsearchClient client method [${key}]`); + } + return await migrationRetryCallCluster( + () => fn(params, { maxRetries: 0, ...options }), + log, + delay + ); + }); + return acc; + }, {} as MigrationEsClient); +} diff --git a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts index 01b0d1cd0ba3a..c3ed97a89af80 100644 --- a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts @@ -18,6 +18,7 @@ */ import { take } from 'rxjs/operators'; +import { elasticsearchClientMock } from '../../../elasticsearch/client/mocks'; import { KibanaMigratorOptions, KibanaMigrator } from './kibana_migrator'; import { loggingSystemMock } from '../../../logging/logging_system.mock'; import { SavedObjectTypeRegistry } from '../../saved_objects_type_registry'; @@ -66,26 +67,44 @@ describe('KibanaMigrator', () => { describe('runMigrations', () => { it('only runs migrations once if called multiple times', async () => { const options = mockOptions(); - const clusterStub = jest.fn(() => ({ status: 404 })); - options.callCluster = clusterStub; + options.client.cat.templates.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise( + { templates: [] }, + { statusCode: 404 } + ) + ); + options.client.indices.get.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); + options.client.indices.getAlias.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); + const migrator = new KibanaMigrator(options); + await migrator.runMigrations(); await migrator.runMigrations(); - // callCluster with "cat.templates" is called by "deleteIndexTemplates" function - // and should only be done once - const callClusterCommands = clusterStub.mock.calls - .map(([callClusterPath]) => callClusterPath) - .filter((callClusterPath) => callClusterPath === 'cat.templates'); - expect(callClusterCommands.length).toBe(1); + expect(options.client.cat.templates).toHaveBeenCalledTimes(1); }); it('emits results on getMigratorResult$()', async () => { const options = mockOptions(); - const clusterStub = jest.fn(() => ({ status: 404 })); - options.callCluster = clusterStub; + options.client.cat.templates.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise( + { templates: [] }, + { statusCode: 404 } + ) + ); + options.client.indices.get.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); + options.client.indices.getAlias.mockReturnValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); + const migrator = new KibanaMigrator(options); const migratorStatus = migrator.getStatus$().pipe(take(3)).toPromise(); await migrator.runMigrations(); @@ -107,9 +126,12 @@ describe('KibanaMigrator', () => { }); }); -function mockOptions(): KibanaMigratorOptions { - const callCluster = jest.fn(); - return { +type MockedOptions = KibanaMigratorOptions & { + client: ReturnType; +}; + +const mockOptions = () => { + const options: MockedOptions = { logger: loggingSystemMock.create().get(), kibanaVersion: '8.2.3', savedObjectValidations: {}, @@ -148,6 +170,7 @@ function mockOptions(): KibanaMigratorOptions { scrollDuration: '10m', skip: false, }, - callCluster, + client: elasticsearchClientMock.createElasticSearchClient(), }; -} + return options; +}; diff --git a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.ts b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.ts index 69b57a498936e..85b9099308807 100644 --- a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.ts +++ b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.ts @@ -24,25 +24,21 @@ import { KibanaConfigType } from 'src/core/server/kibana_config'; import { BehaviorSubject } from 'rxjs'; + import { Logger } from '../../../logging'; import { IndexMapping, SavedObjectsTypeMappingDefinitions } from '../../mappings'; import { SavedObjectUnsanitizedDoc, SavedObjectsSerializer } from '../../serialization'; import { docValidator, PropertyValidators } from '../../validation'; -import { - buildActiveMappings, - CallCluster, - IndexMigrator, - MigrationResult, - MigrationStatus, -} from '../core'; +import { buildActiveMappings, IndexMigrator, MigrationResult, MigrationStatus } from '../core'; import { DocumentMigrator, VersionedTransformer } from '../core/document_migrator'; +import { MigrationEsClient } from '../core/'; import { createIndexMap } from '../core/build_index_map'; import { SavedObjectsMigrationConfigType } from '../../saved_objects_config'; import { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import { SavedObjectsType } from '../../types'; export interface KibanaMigratorOptions { - callCluster: CallCluster; + client: MigrationEsClient; typeRegistry: ISavedObjectTypeRegistry; savedObjectsConfig: SavedObjectsMigrationConfigType; kibanaConfig: KibanaConfigType; @@ -62,7 +58,7 @@ export interface KibanaMigratorStatus { * Manages the shape of mappings and documents in the Kibana index. */ export class KibanaMigrator { - private readonly callCluster: CallCluster; + private readonly client: MigrationEsClient; private readonly savedObjectsConfig: SavedObjectsMigrationConfigType; private readonly documentMigrator: VersionedTransformer; private readonly kibanaConfig: KibanaConfigType; @@ -80,7 +76,7 @@ export class KibanaMigrator { * Creates an instance of KibanaMigrator. */ constructor({ - callCluster, + client, typeRegistry, kibanaConfig, savedObjectsConfig, @@ -88,7 +84,7 @@ export class KibanaMigrator { kibanaVersion, logger, }: KibanaMigratorOptions) { - this.callCluster = callCluster; + this.client = client; this.kibanaConfig = kibanaConfig; this.savedObjectsConfig = savedObjectsConfig; this.typeRegistry = typeRegistry; @@ -153,7 +149,7 @@ export class KibanaMigrator { const migrators = Object.keys(indexMap).map((index) => { return new IndexMigrator({ batchSize: this.savedObjectsConfig.batchSize, - callCluster: this.callCluster, + client: this.client, documentMigrator: this.documentMigrator, index, log: this.log, diff --git a/src/core/server/saved_objects/saved_objects_service.test.ts b/src/core/server/saved_objects/saved_objects_service.test.ts index e8b2cf0b583b1..8df6a07318c45 100644 --- a/src/core/server/saved_objects/saved_objects_service.test.ts +++ b/src/core/server/saved_objects/saved_objects_service.test.ts @@ -25,18 +25,20 @@ import { } from './saved_objects_service.test.mocks'; import { BehaviorSubject } from 'rxjs'; import { ByteSizeValue } from '@kbn/config-schema'; +import { errors as esErrors } from '@elastic/elasticsearch'; + import { SavedObjectsService } from './saved_objects_service'; import { mockCoreContext } from '../core_context.mock'; -import * as legacyElasticsearch from 'elasticsearch'; import { Env } from '../config'; import { configServiceMock } from '../mocks'; import { elasticsearchServiceMock } from '../elasticsearch/elasticsearch_service.mock'; +import { elasticsearchClientMock } from '../elasticsearch/client/mocks'; import { legacyServiceMock } from '../legacy/legacy_service.mock'; import { httpServiceMock } from '../http/http_service.mock'; +import { httpServerMock } from '../http/http_server.mocks'; import { SavedObjectsClientFactoryProvider } from './service/lib'; import { NodesVersionCompatibility } from '../elasticsearch/version_check/ensure_es_version'; import { SavedObjectsRepository } from './service/lib/repository'; -import { KibanaRequest } from '../http'; jest.mock('./service/lib/repository'); @@ -70,7 +72,7 @@ describe('SavedObjectsService', () => { const createStartDeps = (pluginsInitialized: boolean = true) => { return { pluginsInitialized, - elasticsearch: elasticsearchServiceMock.createStart(), + elasticsearch: elasticsearchServiceMock.createInternalStart(), }; }; @@ -161,26 +163,27 @@ describe('SavedObjectsService', () => { }); describe('#start()', () => { - it('creates a KibanaMigrator which retries NoConnections errors from callAsInternalUser', async () => { + it('creates a KibanaMigrator which retries NoLivingConnectionsError errors from ES client', async () => { const coreContext = createCoreContext(); const soService = new SavedObjectsService(coreContext); const coreSetup = createSetupDeps(); const coreStart = createStartDeps(); - let i = 0; - coreStart.elasticsearch.legacy.client.callAsInternalUser = jest + coreStart.elasticsearch.client.asInternalUser.indices.create = jest .fn() - .mockImplementation(() => - i++ <= 2 - ? Promise.reject(new legacyElasticsearch.errors.NoConnections()) - : Promise.resolve('success') + .mockImplementationOnce(() => + Promise.reject(new esErrors.NoLivingConnectionsError('reason', {} as any)) + ) + .mockImplementationOnce(() => + elasticsearchClientMock.createSuccessTransportRequestPromise('success') ); await soService.setup(coreSetup); await soService.start(coreStart, 1); - return expect(KibanaMigratorMock.mock.calls[0][0].callCluster()).resolves.toMatch('success'); + const response = await KibanaMigratorMock.mock.calls[0][0].client.indices.create(); + return expect(response.body).toBe('success'); }); it('skips KibanaMigrator migrations when pluginsInitialized=false', async () => { @@ -291,22 +294,15 @@ describe('SavedObjectsService', () => { const coreStart = createStartDeps(); const { createScopedRepository } = await soService.start(coreStart); - const req = {} as KibanaRequest; + const req = httpServerMock.createKibanaRequest(); createScopedRepository(req); - expect(coreStart.elasticsearch.legacy.client.asScoped).toHaveBeenCalledWith(req); - - const [ - { - value: { callAsCurrentUser }, - }, - ] = coreStart.elasticsearch.legacy.client.asScoped.mock.results; + expect(coreStart.elasticsearch.client.asScoped).toHaveBeenCalledWith(req); const [ - [, , , callCluster, includedHiddenTypes], + [, , , , includedHiddenTypes], ] = (SavedObjectsRepository.createRepository as jest.Mocked).mock.calls; - expect(callCluster).toBe(callAsCurrentUser); expect(includedHiddenTypes).toEqual([]); }); @@ -318,7 +314,7 @@ describe('SavedObjectsService', () => { const coreStart = createStartDeps(); const { createScopedRepository } = await soService.start(coreStart); - const req = {} as KibanaRequest; + const req = httpServerMock.createKibanaRequest(); createScopedRepository(req, ['someHiddenType']); const [ @@ -341,11 +337,10 @@ describe('SavedObjectsService', () => { createInternalRepository(); const [ - [, , , callCluster, includedHiddenTypes], + [, , , client, includedHiddenTypes], ] = (SavedObjectsRepository.createRepository as jest.Mocked).mock.calls; - expect(coreStart.elasticsearch.legacy.client.callAsInternalUser).toBe(callCluster); - expect(callCluster).toBe(coreStart.elasticsearch.legacy.client.callAsInternalUser); + expect(coreStart.elasticsearch.client.asInternalUser).toBe(client); expect(includedHiddenTypes).toEqual([]); }); diff --git a/src/core/server/saved_objects/saved_objects_service.ts b/src/core/server/saved_objects/saved_objects_service.ts index c2d4f49d7ee2a..f05e912b12ad8 100644 --- a/src/core/server/saved_objects/saved_objects_service.ts +++ b/src/core/server/saved_objects/saved_objects_service.ts @@ -30,13 +30,12 @@ import { KibanaMigrator, IKibanaMigrator } from './migrations'; import { CoreContext } from '../core_context'; import { LegacyServiceDiscoverPlugins } from '../legacy'; import { - LegacyAPICaller, - ElasticsearchServiceStart, - ILegacyClusterClient, + ElasticsearchClient, + IClusterClient, InternalElasticsearchServiceSetup, + InternalElasticsearchServiceStart, } from '../elasticsearch'; import { KibanaConfigType } from '../kibana_config'; -import { migrationsRetryCallCluster } from '../elasticsearch/legacy'; import { SavedObjectsConfigType, SavedObjectsMigrationConfigType, @@ -57,7 +56,7 @@ import { SavedObjectsSerializer } from './serialization'; import { registerRoutes } from './routes'; import { ServiceStatus } from '../status'; import { calculateStatus$ } from './status'; - +import { createMigrationEsClient } from './migrations/core/'; /** * Saved Objects is Kibana's data persistence mechanism allowing plugins to * use Elasticsearch for storing and querying state. The SavedObjectsServiceSetup API exposes methods @@ -284,7 +283,7 @@ interface WrappedClientFactoryWrapper { /** @internal */ export interface SavedObjectsStartDeps { - elasticsearch: ElasticsearchServiceStart; + elasticsearch: InternalElasticsearchServiceStart; pluginsInitialized?: boolean; } @@ -383,12 +382,12 @@ export class SavedObjectsService .atPath('kibana') .pipe(first()) .toPromise(); - const client = elasticsearch.legacy.client; + const client = elasticsearch.client; const migrator = this.createMigrator( kibanaConfig, this.config.migration, - client, + elasticsearch.client, migrationsRetryDelay ); @@ -434,21 +433,24 @@ export class SavedObjectsService await migrator.runMigrations(); } - const createRepository = (callCluster: LegacyAPICaller, includedHiddenTypes: string[] = []) => { + const createRepository = ( + esClient: ElasticsearchClient, + includedHiddenTypes: string[] = [] + ) => { return SavedObjectsRepository.createRepository( migrator, this.typeRegistry, kibanaConfig.index, - callCluster, + esClient, includedHiddenTypes ); }; const repositoryFactory: SavedObjectsRepositoryFactory = { createInternalRepository: (includedHiddenTypes?: string[]) => - createRepository(client.callAsInternalUser, includedHiddenTypes), + createRepository(client.asInternalUser, includedHiddenTypes), createScopedRepository: (req: KibanaRequest, includedHiddenTypes?: string[]) => - createRepository(client.asScoped(req).callAsCurrentUser, includedHiddenTypes), + createRepository(client.asScoped(req).asCurrentUser, includedHiddenTypes), }; const clientProvider = new SavedObjectsClientProvider({ @@ -484,7 +486,7 @@ export class SavedObjectsService private createMigrator( kibanaConfig: KibanaConfigType, savedObjectsConfig: SavedObjectsMigrationConfigType, - esClient: ILegacyClusterClient, + client: IClusterClient, migrationsRetryDelay?: number ): KibanaMigrator { return new KibanaMigrator({ @@ -494,11 +496,7 @@ export class SavedObjectsService savedObjectsConfig, savedObjectValidations: this.validations, kibanaConfig, - callCluster: migrationsRetryCallCluster( - esClient.callAsInternalUser, - this.logger, - migrationsRetryDelay - ), + client: createMigrationEsClient(client.asInternalUser, this.logger, migrationsRetryDelay), }); } } diff --git a/src/core/server/saved_objects/serialization/index.ts b/src/core/server/saved_objects/serialization/index.ts index f7f4e75704341..812a0770ad988 100644 --- a/src/core/server/saved_objects/serialization/index.ts +++ b/src/core/server/saved_objects/serialization/index.ts @@ -22,5 +22,10 @@ * the raw document format as stored in ElasticSearch. */ -export { SavedObjectUnsanitizedDoc, SavedObjectSanitizedDoc, SavedObjectsRawDoc } from './types'; +export { + SavedObjectUnsanitizedDoc, + SavedObjectSanitizedDoc, + SavedObjectsRawDoc, + SavedObjectsRawDocSource, +} from './types'; export { SavedObjectsSerializer } from './serializer'; diff --git a/src/core/server/saved_objects/service/lib/decorate_es_error.test.ts b/src/core/server/saved_objects/service/lib/decorate_es_error.test.ts index 1fdebd87397eb..623610eebd8d7 100644 --- a/src/core/server/saved_objects/service/lib/decorate_es_error.test.ts +++ b/src/core/server/saved_objects/service/lib/decorate_es_error.test.ts @@ -17,75 +17,93 @@ * under the License. */ -import { errors as esErrors } from 'elasticsearch'; - +import { errors as esErrors } from '@elastic/elasticsearch'; +import { elasticsearchClientMock } from '../../../elasticsearch/client/mocks'; import { decorateEsError } from './decorate_es_error'; import { SavedObjectsErrorHelpers } from './errors'; describe('savedObjectsClient/decorateEsError', () => { it('always returns the same error it receives', () => { - const error = new Error(); + const error = new esErrors.ResponseError(elasticsearchClientMock.createApiResponse()); expect(decorateEsError(error)).toBe(error); }); - it('makes es.ConnectionFault a SavedObjectsClient/EsUnavailable error', () => { - const error = new esErrors.ConnectionFault(); + it('makes ConnectionError a SavedObjectsClient/EsUnavailable error', () => { + const error = new esErrors.ConnectionError( + 'reason', + elasticsearchClientMock.createApiResponse() + ); expect(SavedObjectsErrorHelpers.isEsUnavailableError(error)).toBe(false); expect(decorateEsError(error)).toBe(error); expect(SavedObjectsErrorHelpers.isEsUnavailableError(error)).toBe(true); }); - it('makes es.ServiceUnavailable a SavedObjectsClient/EsUnavailable error', () => { - const error = new esErrors.ServiceUnavailable(); + it('makes ServiceUnavailable a SavedObjectsClient/EsUnavailable error', () => { + const error = new esErrors.ResponseError( + elasticsearchClientMock.createApiResponse({ statusCode: 503 }) + ); expect(SavedObjectsErrorHelpers.isEsUnavailableError(error)).toBe(false); expect(decorateEsError(error)).toBe(error); expect(SavedObjectsErrorHelpers.isEsUnavailableError(error)).toBe(true); }); - it('makes es.NoConnections a SavedObjectsClient/EsUnavailable error', () => { - const error = new esErrors.NoConnections(); + it('makes NoLivingConnectionsError a SavedObjectsClient/EsUnavailable error', () => { + const error = new esErrors.NoLivingConnectionsError( + 'reason', + elasticsearchClientMock.createApiResponse() + ); expect(SavedObjectsErrorHelpers.isEsUnavailableError(error)).toBe(false); expect(decorateEsError(error)).toBe(error); expect(SavedObjectsErrorHelpers.isEsUnavailableError(error)).toBe(true); }); - it('makes es.RequestTimeout a SavedObjectsClient/EsUnavailable error', () => { - const error = new esErrors.RequestTimeout(); + it('makes TimeoutError a SavedObjectsClient/EsUnavailable error', () => { + const error = new esErrors.TimeoutError('reason', elasticsearchClientMock.createApiResponse()); expect(SavedObjectsErrorHelpers.isEsUnavailableError(error)).toBe(false); expect(decorateEsError(error)).toBe(error); expect(SavedObjectsErrorHelpers.isEsUnavailableError(error)).toBe(true); }); - it('makes es.Conflict a SavedObjectsClient/Conflict error', () => { - const error = new esErrors.Conflict(); + it('makes Conflict a SavedObjectsClient/Conflict error', () => { + const error = new esErrors.ResponseError( + elasticsearchClientMock.createApiResponse({ statusCode: 409 }) + ); expect(SavedObjectsErrorHelpers.isConflictError(error)).toBe(false); expect(decorateEsError(error)).toBe(error); expect(SavedObjectsErrorHelpers.isConflictError(error)).toBe(true); }); - it('makes es.AuthenticationException a SavedObjectsClient/NotAuthorized error', () => { - const error = new esErrors.AuthenticationException(); + it('makes NotAuthorized a SavedObjectsClient/NotAuthorized error', () => { + const error = new esErrors.ResponseError( + elasticsearchClientMock.createApiResponse({ statusCode: 401 }) + ); expect(SavedObjectsErrorHelpers.isNotAuthorizedError(error)).toBe(false); expect(decorateEsError(error)).toBe(error); expect(SavedObjectsErrorHelpers.isNotAuthorizedError(error)).toBe(true); }); - it('makes es.Forbidden a SavedObjectsClient/Forbidden error', () => { - const error = new esErrors.Forbidden(); + it('makes Forbidden a SavedObjectsClient/Forbidden error', () => { + const error = new esErrors.ResponseError( + elasticsearchClientMock.createApiResponse({ statusCode: 403 }) + ); expect(SavedObjectsErrorHelpers.isForbiddenError(error)).toBe(false); expect(decorateEsError(error)).toBe(error); expect(SavedObjectsErrorHelpers.isForbiddenError(error)).toBe(true); }); - it('makes es.RequestEntityTooLarge a SavedObjectsClient/RequestEntityTooLarge error', () => { - const error = new esErrors.RequestEntityTooLarge(); + it('makes RequestEntityTooLarge a SavedObjectsClient/RequestEntityTooLarge error', () => { + const error = new esErrors.ResponseError( + elasticsearchClientMock.createApiResponse({ statusCode: 413 }) + ); expect(SavedObjectsErrorHelpers.isRequestEntityTooLargeError(error)).toBe(false); expect(decorateEsError(error)).toBe(error); expect(SavedObjectsErrorHelpers.isRequestEntityTooLargeError(error)).toBe(true); }); - it('discards es.NotFound errors and returns a generic NotFound error', () => { - const error = new esErrors.NotFound(); + it('discards NotFound errors and returns a generic NotFound error', () => { + const error = new esErrors.ResponseError( + elasticsearchClientMock.createApiResponse({ statusCode: 404 }) + ); expect(SavedObjectsErrorHelpers.isNotFoundError(error)).toBe(false); const genericError = decorateEsError(error); expect(genericError).not.toBe(error); @@ -93,8 +111,10 @@ describe('savedObjectsClient/decorateEsError', () => { expect(SavedObjectsErrorHelpers.isNotFoundError(genericError)).toBe(true); }); - it('makes es.BadRequest a SavedObjectsClient/BadRequest error', () => { - const error = new esErrors.BadRequest(); + it('makes BadRequest a SavedObjectsClient/BadRequest error', () => { + const error = new esErrors.ResponseError( + elasticsearchClientMock.createApiResponse({ statusCode: 400 }) + ); expect(SavedObjectsErrorHelpers.isBadRequestError(error)).toBe(false); expect(decorateEsError(error)).toBe(error); expect(SavedObjectsErrorHelpers.isBadRequestError(error)).toBe(true); @@ -102,10 +122,16 @@ describe('savedObjectsClient/decorateEsError', () => { describe('when es.BadRequest has a reason', () => { it('makes a SavedObjectsClient/esCannotExecuteScriptError error when script context is disabled', () => { - const error = new esErrors.BadRequest(); - (error as Record).body = { - error: { reason: 'cannot execute scripts using [update] context' }, - }; + const error = new esErrors.ResponseError( + elasticsearchClientMock.createApiResponse({ + statusCode: 400, + body: { + error: { + reason: 'cannot execute scripts using [update] context', + }, + }, + }) + ); expect(SavedObjectsErrorHelpers.isEsCannotExecuteScriptError(error)).toBe(false); expect(decorateEsError(error)).toBe(error); expect(SavedObjectsErrorHelpers.isEsCannotExecuteScriptError(error)).toBe(true); @@ -113,10 +139,16 @@ describe('savedObjectsClient/decorateEsError', () => { }); it('makes a SavedObjectsClient/esCannotExecuteScriptError error when inline scripts are disabled', () => { - const error = new esErrors.BadRequest(); - (error as Record).body = { - error: { reason: 'cannot execute [inline] scripts' }, - }; + const error = new esErrors.ResponseError( + elasticsearchClientMock.createApiResponse({ + statusCode: 400, + body: { + error: { + reason: 'cannot execute [inline] scripts', + }, + }, + }) + ); expect(SavedObjectsErrorHelpers.isEsCannotExecuteScriptError(error)).toBe(false); expect(decorateEsError(error)).toBe(error); expect(SavedObjectsErrorHelpers.isEsCannotExecuteScriptError(error)).toBe(true); @@ -124,8 +156,9 @@ describe('savedObjectsClient/decorateEsError', () => { }); it('makes a SavedObjectsClient/BadRequest error for any other reason', () => { - const error = new esErrors.BadRequest(); - (error as Record).body = { error: { reason: 'some other reason' } }; + const error = new esErrors.ResponseError( + elasticsearchClientMock.createApiResponse({ statusCode: 400 }) + ); expect(SavedObjectsErrorHelpers.isBadRequestError(error)).toBe(false); expect(decorateEsError(error)).toBe(error); expect(SavedObjectsErrorHelpers.isBadRequestError(error)).toBe(true); @@ -133,7 +166,7 @@ describe('savedObjectsClient/decorateEsError', () => { }); it('returns other errors as Boom errors', () => { - const error = new Error(); + const error = new esErrors.ResponseError(elasticsearchClientMock.createApiResponse()); expect(error).not.toHaveProperty('isBoom'); expect(decorateEsError(error)).toBe(error); expect(error).toHaveProperty('isBoom'); diff --git a/src/core/server/saved_objects/service/lib/decorate_es_error.ts b/src/core/server/saved_objects/service/lib/decorate_es_error.ts index 7d1575798c357..cf8a16cdaae6f 100644 --- a/src/core/server/saved_objects/service/lib/decorate_es_error.ts +++ b/src/core/server/saved_objects/service/lib/decorate_es_error.ts @@ -17,65 +17,66 @@ * under the License. */ -import * as legacyElasticsearch from 'elasticsearch'; +import { errors as esErrors } from '@elastic/elasticsearch'; import { get } from 'lodash'; -const { - ConnectionFault, - ServiceUnavailable, - NoConnections, - RequestTimeout, - Conflict, - // @ts-expect-error - 401: NotAuthorized, - // @ts-expect-error - 403: Forbidden, - // @ts-expect-error - 413: RequestEntityTooLarge, - NotFound, - BadRequest, -} = legacyElasticsearch.errors; +const responseErrors = { + isServiceUnavailable: (statusCode: number) => statusCode === 503, + isConflict: (statusCode: number) => statusCode === 409, + isNotAuthorized: (statusCode: number) => statusCode === 401, + isForbidden: (statusCode: number) => statusCode === 403, + isRequestEntityTooLarge: (statusCode: number) => statusCode === 413, + isNotFound: (statusCode: number) => statusCode === 404, + isBadRequest: (statusCode: number) => statusCode === 400, +}; +const { ConnectionError, NoLivingConnectionsError, TimeoutError } = esErrors; const SCRIPT_CONTEXT_DISABLED_REGEX = /(?:cannot execute scripts using \[)([a-z]*)(?:\] context)/; const INLINE_SCRIPTS_DISABLED_MESSAGE = 'cannot execute [inline] scripts'; import { SavedObjectsErrorHelpers } from './errors'; -export function decorateEsError(error: Error) { +type EsErrors = + | esErrors.ConnectionError + | esErrors.NoLivingConnectionsError + | esErrors.TimeoutError + | esErrors.ResponseError; + +export function decorateEsError(error: EsErrors) { if (!(error instanceof Error)) { throw new Error('Expected an instance of Error'); } const { reason } = get(error, 'body.error', { reason: undefined }) as { reason?: string }; if ( - error instanceof ConnectionFault || - error instanceof ServiceUnavailable || - error instanceof NoConnections || - error instanceof RequestTimeout + error instanceof ConnectionError || + error instanceof NoLivingConnectionsError || + error instanceof TimeoutError || + responseErrors.isServiceUnavailable(error.statusCode) ) { return SavedObjectsErrorHelpers.decorateEsUnavailableError(error, reason); } - if (error instanceof Conflict) { + if (responseErrors.isConflict(error.statusCode)) { return SavedObjectsErrorHelpers.decorateConflictError(error, reason); } - if (error instanceof NotAuthorized) { + if (responseErrors.isNotAuthorized(error.statusCode)) { return SavedObjectsErrorHelpers.decorateNotAuthorizedError(error, reason); } - if (error instanceof Forbidden) { + if (responseErrors.isForbidden(error.statusCode)) { return SavedObjectsErrorHelpers.decorateForbiddenError(error, reason); } - if (error instanceof RequestEntityTooLarge) { + if (responseErrors.isRequestEntityTooLarge(error.statusCode)) { return SavedObjectsErrorHelpers.decorateRequestEntityTooLargeError(error, reason); } - if (error instanceof NotFound) { + if (responseErrors.isNotFound(error.statusCode)) { return SavedObjectsErrorHelpers.createGenericNotFoundError(); } - if (error instanceof BadRequest) { + if (responseErrors.isBadRequest(error.statusCode)) { if ( SCRIPT_CONTEXT_DISABLED_REGEX.test(reason || '') || reason === INLINE_SCRIPTS_DISABLED_MESSAGE diff --git a/src/core/server/saved_objects/service/lib/repository.test.js b/src/core/server/saved_objects/service/lib/repository.test.js index d563edbe66c9b..b902179b012ff 100644 --- a/src/core/server/saved_objects/service/lib/repository.test.js +++ b/src/core/server/saved_objects/service/lib/repository.test.js @@ -24,6 +24,7 @@ import { SavedObjectsSerializer } from '../../serialization'; import { encodeHitVersion } from '../../version'; import { SavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import { DocumentMigrator } from '../../migrations/core/document_migrator'; +import { elasticsearchClientMock } from '../../../elasticsearch/client/mocks'; jest.mock('./search_dsl/search_dsl', () => ({ getSearchDsl: jest.fn() })); @@ -40,7 +41,7 @@ const createUnsupportedTypeError = (...args) => SavedObjectsErrorHelpers.createUnsupportedTypeError(...args).output.payload; describe('SavedObjectsRepository', () => { - let callAdminCluster; + let client; let savedObjectsRepository; let migrator; @@ -170,26 +171,11 @@ describe('SavedObjectsRepository', () => { }); const getMockMgetResponse = (objects, namespace) => ({ - status: 200, docs: objects.map((obj) => obj.found === false ? obj : getMockGetResponse({ ...obj, namespace }) ), }); - const expectClusterCalls = (...actions) => { - for (let i = 0; i < actions.length; i++) { - expect(callAdminCluster).toHaveBeenNthCalledWith(i + 1, actions[i], expect.any(Object)); - } - expect(callAdminCluster).toHaveBeenCalledTimes(actions.length); - }; - const expectClusterCallArgs = (args, n = 1) => { - expect(callAdminCluster).toHaveBeenNthCalledWith( - n, - expect.any(String), - expect.objectContaining(args) - ); - }; - expect.extend({ toBeDocumentWithoutError(received, type, id) { if (received.type === type && received.id === id && !received.error) { @@ -215,7 +201,7 @@ describe('SavedObjectsRepository', () => { }; beforeEach(() => { - callAdminCluster = jest.fn(); + client = elasticsearchClientMock.createElasticSearchClient(); migrator = { migrateDocument: jest.fn().mockImplementation(documentMigrator.migrate), runMigrations: async () => ({ status: 'skipped' }), @@ -240,7 +226,7 @@ describe('SavedObjectsRepository', () => { savedObjectsRepository = new SavedObjectsRepository({ index: '.kibana-test', mappings, - callCluster: callAdminCluster, + client, migrator, typeRegistry: registry, serializer, @@ -248,7 +234,7 @@ describe('SavedObjectsRepository', () => { }); savedObjectsRepository._getCurrentTime = jest.fn(() => mockTimestamp); - getSearchDslNS.getSearchDsl.mockReset(); + getSearchDslNS.getSearchDsl.mockClear(); }); const mockMigrationVersion = { foo: '2.3.4' }; @@ -274,25 +260,29 @@ describe('SavedObjectsRepository', () => { // mock a document that exists in two namespaces const mockResponse = getMockGetResponse({ type, id }); mockResponse._source.namespaces = [currentNs1, currentNs2]; - callAdminCluster.mockResolvedValueOnce(mockResponse); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(mockResponse) + ); }; const addToNamespacesSuccess = async (type, id, namespaces, options) => { - mockGetResponse(type, id); // this._callCluster('get', ...) - callAdminCluster.mockResolvedValue({ - _id: `${type}:${id}`, - ...mockVersionProps, - result: 'updated', - }); // this._writeToCluster('update', ...) + mockGetResponse(type, id); + client.update.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + _id: `${type}:${id}`, + ...mockVersionProps, + result: 'updated', + }) + ); const result = await savedObjectsRepository.addToNamespaces(type, id, namespaces, options); - expect(callAdminCluster).toHaveBeenCalledTimes(2); + expect(client.get).toHaveBeenCalledTimes(1); + expect(client.update).toHaveBeenCalledTimes(1); return result; }; - describe('cluster calls', () => { + describe('client calls', () => { it(`should use ES get action then update action`, async () => { await addToNamespacesSuccess(type, id, [newNs1, newNs2]); - expectClusterCalls('get', 'update'); }); it(`defaults to the version of the existing document`, async () => { @@ -301,25 +291,28 @@ describe('SavedObjectsRepository', () => { if_seq_no: mockVersionProps._seq_no, if_primary_term: mockVersionProps._primary_term, }; - expectClusterCallArgs(versionProperties, 2); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining(versionProperties), + expect.anything() + ); }); it(`accepts version`, async () => { await addToNamespacesSuccess(type, id, [newNs1, newNs2], { version: encodeHitVersion({ _seq_no: 100, _primary_term: 200 }), }); - expectClusterCallArgs({ if_seq_no: 100, if_primary_term: 200 }, 2); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ if_seq_no: 100, if_primary_term: 200 }), + expect.anything() + ); }); it(`defaults to a refresh setting of wait_for`, async () => { await addToNamespacesSuccess(type, id, [newNs1, newNs2]); - expectClusterCallArgs({ refresh: 'wait_for' }, 2); - }); - - it(`accepts a custom refresh setting`, async () => { - const refresh = 'foo'; - await addToNamespacesSuccess(type, id, [newNs1, newNs2], { refresh }); - expectClusterCallArgs({ refresh }, 2); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ refresh: 'wait_for' }), + expect.anything() + ); }); }); @@ -337,19 +330,19 @@ describe('SavedObjectsRepository', () => { it(`throws when type is invalid`, async () => { await expectNotFoundError('unknownType', id, [newNs1, newNs2]); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }); it(`throws when type is hidden`, async () => { await expectNotFoundError(HIDDEN_TYPE, id, [newNs1, newNs2]); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }); it(`throws when type is not multi-namespace`, async () => { const test = async (type) => { const message = `${type} doesn't support multiple namespaces`; await expectBadRequestError(type, id, [newNs1, newNs2], message); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }; await test('index-pattern'); await test(NAMESPACE_AGNOSTIC_TYPE); @@ -359,48 +352,43 @@ describe('SavedObjectsRepository', () => { const test = async (namespaces) => { const message = 'namespaces must be a non-empty array of strings'; await expectBadRequestError(type, id, namespaces, message); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }; await test([]); }); it(`throws when ES is unable to find the document during get`, async () => { - callAdminCluster.mockResolvedValue({ found: false }); // this._callCluster('get', ...) + client.get.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({ found: false }) + ); await expectNotFoundError(type, id, [newNs1, newNs2]); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the index during get`, async () => { - callAdminCluster.mockResolvedValue({ status: 404 }); // this._callCluster('get', ...) + client.get.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); await expectNotFoundError(type, id, [newNs1, newNs2]); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when the document exists, but not in this namespace`, async () => { - mockGetResponse(type, id); // this._callCluster('get', ...) + mockGetResponse(type, id); await expectNotFoundError(type, id, [newNs1, newNs2], { namespace: 'some-other-namespace', }); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the document during update`, async () => { - mockGetResponse(type, id); // this._callCluster('get', ...) - callAdminCluster.mockResolvedValue({ status: 404 }); // this._writeToCluster('update', ...) - await expectNotFoundError(type, id, [newNs1, newNs2]); - expectClusterCalls('get', 'update'); - }); - }); - - describe('migration', () => { - it(`waits until migrations are complete before proceeding`, async () => { - let callAdminClusterCount = 0; - migrator.runMigrations = jest.fn(async () => - // runMigrations should resolve before callAdminCluster is initiated - expect(callAdminCluster).toHaveBeenCalledTimes(callAdminClusterCount++) + mockGetResponse(type, id); + client.update.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) ); - await expect(addToNamespacesSuccess(type, id, [newNs1, newNs2])).resolves.toBeDefined(); - expect(migrator.runMigrations).toHaveReturnedTimes(2); + await expectNotFoundError(type, id, [newNs1, newNs2]); + expect(client.get).toHaveBeenCalledTimes(1); + expect(client.update).toHaveBeenCalledTimes(1); }); }); @@ -457,17 +445,21 @@ describe('SavedObjectsRepository', () => { objects.filter(({ type, id }) => registry.isMultiNamespace(type) && id); if (multiNamespaceObjects?.length) { const response = getMockMgetResponse(multiNamespaceObjects, options?.namespace); - callAdminCluster.mockResolvedValueOnce(response); // this._callCluster('mget', ...) + client.mget.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); } const response = getMockBulkCreateResponse(objects, options?.namespace); - callAdminCluster.mockResolvedValue(response); // this._writeToCluster('bulk', ...) + client.bulk.mockResolvedValue( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); const result = await savedObjectsRepository.bulkCreate(objects, options); - expect(callAdminCluster).toHaveBeenCalledTimes(multiNamespaceObjects?.length ? 2 : 1); + expect(client.mget).toHaveBeenCalledTimes(multiNamespaceObjects?.length ? 1 : 0); return result; }; // bulk create calls have two objects for each source -- the action, and the source - const expectClusterCallArgsAction = ( + const expectClientCallArgsAction = ( objects, { method, _index = expect.any(String), getId = () => expect.any(String) } ) => { @@ -476,7 +468,10 @@ describe('SavedObjectsRepository', () => { body.push({ [method]: { _index, _id: getId(type, id) } }); body.push(expect.any(Object)); } - expectClusterCallArgs({ body }); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); }; const expectObjArgs = ({ type, attributes, references }, overrides) => [ @@ -498,53 +493,60 @@ describe('SavedObjectsRepository', () => { ...mockTimestampFields, }); - describe('cluster calls', () => { + describe('client calls', () => { it(`should use the ES bulk action by default`, async () => { await bulkCreateSuccess([obj1, obj2]); - expectClusterCalls('bulk'); + expect(client.bulk).toHaveBeenCalledTimes(1); }); it(`should use the ES mget action before bulk action for any types that are multi-namespace, when overwrite=true`, async () => { const objects = [obj1, { ...obj2, type: MULTI_NAMESPACE_TYPE }]; await bulkCreateSuccess(objects, { overwrite: true }); - expectClusterCalls('mget', 'bulk'); + expect(client.bulk).toHaveBeenCalledTimes(1); + expect(client.mget).toHaveBeenCalledTimes(1); const docs = [expect.objectContaining({ _id: `${MULTI_NAMESPACE_TYPE}:${obj2.id}` })]; - expectClusterCallArgs({ body: { docs } }, 1); + expect(client.mget.mock.calls[0][0].body).toEqual({ docs }); }); it(`should use the ES create method if ID is undefined and overwrite=true`, async () => { const objects = [obj1, obj2].map((obj) => ({ ...obj, id: undefined })); await bulkCreateSuccess(objects, { overwrite: true }); - expectClusterCallArgsAction(objects, { method: 'create' }); + expectClientCallArgsAction(objects, { method: 'create' }); }); it(`should use the ES create method if ID is undefined and overwrite=false`, async () => { const objects = [obj1, obj2].map((obj) => ({ ...obj, id: undefined })); await bulkCreateSuccess(objects); - expectClusterCallArgsAction(objects, { method: 'create' }); + expectClientCallArgsAction(objects, { method: 'create' }); }); it(`should use the ES index method if ID is defined and overwrite=true`, async () => { await bulkCreateSuccess([obj1, obj2], { overwrite: true }); - expectClusterCallArgsAction([obj1, obj2], { method: 'index' }); + expectClientCallArgsAction([obj1, obj2], { method: 'index' }); }); it(`should use the ES create method if ID is defined and overwrite=false`, async () => { await bulkCreateSuccess([obj1, obj2]); - expectClusterCallArgsAction([obj1, obj2], { method: 'create' }); + expectClientCallArgsAction([obj1, obj2], { method: 'create' }); }); it(`formats the ES request`, async () => { await bulkCreateSuccess([obj1, obj2]); const body = [...expectObjArgs(obj1), ...expectObjArgs(obj2)]; - expectClusterCallArgs({ body }); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); }); it(`adds namespace to request body for any types that are single-namespace`, async () => { await bulkCreateSuccess([obj1, obj2], { namespace }); const expected = expect.objectContaining({ namespace }); const body = [expect.any(Object), expected, expect.any(Object), expected]; - expectClusterCallArgs({ body }); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); }); it(`doesn't add namespace to request body for any types that are not single-namespace`, async () => { @@ -555,7 +557,10 @@ describe('SavedObjectsRepository', () => { await bulkCreateSuccess(objects, { namespace }); const expected = expect.not.objectContaining({ namespace: expect.anything() }); const body = [expect.any(Object), expected, expect.any(Object), expected]; - expectClusterCallArgs({ body }); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); }); it(`adds namespaces to request body for any types that are multi-namespace`, async () => { @@ -565,8 +570,12 @@ describe('SavedObjectsRepository', () => { await bulkCreateSuccess(objects, { namespace, overwrite: true }); const expected = expect.objectContaining({ namespaces }); const body = [expect.any(Object), expected, expect.any(Object), expected]; - expectClusterCallArgs({ body }, 2); - callAdminCluster.mockReset(); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); + client.bulk.mockClear(); + client.mget.mockClear(); }; await test(undefined); await test(namespace); @@ -578,8 +587,11 @@ describe('SavedObjectsRepository', () => { await bulkCreateSuccess(objects, { namespace, overwrite: true }); const expected = expect.not.objectContaining({ namespaces: expect.anything() }); const body = [expect.any(Object), expected, expect.any(Object), expected]; - expectClusterCallArgs({ body }); - callAdminCluster.mockReset(); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); + client.bulk.mockClear(); }; await test(undefined); await test(namespace); @@ -587,35 +599,32 @@ describe('SavedObjectsRepository', () => { it(`defaults to a refresh setting of wait_for`, async () => { await bulkCreateSuccess([obj1, obj2]); - expectClusterCallArgs({ refresh: 'wait_for' }); - }); - - it(`accepts a custom refresh setting`, async () => { - const refresh = 'foo'; - await bulkCreateSuccess([obj1, obj2], { refresh }); - expectClusterCallArgs({ refresh }); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ refresh: 'wait_for' }), + expect.anything() + ); }); it(`should use default index`, async () => { await bulkCreateSuccess([obj1, obj2]); - expectClusterCallArgsAction([obj1, obj2], { method: 'create', _index: '.kibana-test' }); + expectClientCallArgsAction([obj1, obj2], { method: 'create', _index: '.kibana-test' }); }); it(`should use custom index`, async () => { await bulkCreateSuccess([obj1, obj2].map((x) => ({ ...x, type: CUSTOM_INDEX_TYPE }))); - expectClusterCallArgsAction([obj1, obj2], { method: 'create', _index: 'custom' }); + expectClientCallArgsAction([obj1, obj2], { method: 'create', _index: 'custom' }); }); it(`prepends namespace to the id when providing namespace for single-namespace type`, async () => { const getId = (type, id) => `${namespace}:${type}:${id}`; await bulkCreateSuccess([obj1, obj2], { namespace }); - expectClusterCallArgsAction([obj1, obj2], { method: 'create', getId }); + expectClientCallArgsAction([obj1, obj2], { method: 'create', getId }); }); it(`doesn't prepend namespace to the id when providing no namespace for single-namespace type`, async () => { const getId = (type, id) => `${type}:${id}`; await bulkCreateSuccess([obj1, obj2]); - expectClusterCallArgsAction([obj1, obj2], { method: 'create', getId }); + expectClientCallArgsAction([obj1, obj2], { method: 'create', getId }); }); it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { @@ -625,7 +634,7 @@ describe('SavedObjectsRepository', () => { { ...obj2, type: MULTI_NAMESPACE_TYPE }, ]; await bulkCreateSuccess(objects, { namespace }); - expectClusterCallArgsAction(objects, { method: 'create', getId }); + expectClientCallArgsAction(objects, { method: 'create', getId }); }); }); @@ -645,14 +654,19 @@ describe('SavedObjectsRepository', () => { } else { response = getMockBulkCreateResponse([obj1, obj2]); } - callAdminCluster.mockResolvedValue(response); // this._writeToCluster('bulk', ...) + client.bulk.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); const objects = [obj1, obj, obj2]; const result = await savedObjectsRepository.bulkCreate(objects); - expectClusterCalls('bulk'); + expect(client.bulk).toHaveBeenCalled(); const objCall = esError ? expectObjArgs(obj) : []; const body = [...expectObjArgs(obj1), ...objCall, ...expectObjArgs(obj2)]; - expectClusterCallArgs({ body }); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); expect(result).toEqual({ saved_objects: [expectSuccess(obj1), expectedError, expectSuccess(obj2)], }); @@ -682,17 +696,29 @@ describe('SavedObjectsRepository', () => { }, ], }; - callAdminCluster.mockResolvedValueOnce(response1); // this._callCluster('mget', ...) + client.mget.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response1) + ); const response2 = getMockBulkCreateResponse([obj1, obj2]); - callAdminCluster.mockResolvedValue(response2); // this._writeToCluster('bulk', ...) + client.bulk.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response2) + ); const options = { overwrite: true }; const result = await savedObjectsRepository.bulkCreate([obj1, obj, obj2], options); - expectClusterCalls('mget', 'bulk'); + expect(client.bulk).toHaveBeenCalled(); + expect(client.mget).toHaveBeenCalled(); + const body1 = { docs: [expect.objectContaining({ _id: `${obj.type}:${obj.id}` })] }; - expectClusterCallArgs({ body: body1 }, 1); + expect(client.mget).toHaveBeenCalledWith( + expect.objectContaining({ body: body1 }), + expect.anything() + ); const body2 = [...expectObjArgs(obj1), ...expectObjArgs(obj2)]; - expectClusterCallArgs({ body: body2 }, 2); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body: body2 }), + expect.anything() + ); expect(result).toEqual({ saved_objects: [expectSuccess(obj1), expectErrorConflict(obj), expectSuccess(obj2)], }); @@ -721,14 +747,6 @@ describe('SavedObjectsRepository', () => { }); describe('migration', () => { - it(`waits until migrations are complete before proceeding`, async () => { - migrator.runMigrations = jest.fn(async () => - expect(callAdminCluster).not.toHaveBeenCalled() - ); - await expect(bulkCreateSuccess([obj1, obj2])).resolves.toBeDefined(); - expect(migrator.runMigrations).toHaveBeenCalledTimes(1); - }); - it(`migrates the docs and serializes the migrated docs`, async () => { migrator.migrateDocument.mockImplementation(mockMigrateDocument); await bulkCreateSuccess([obj1, obj2]); @@ -793,9 +811,7 @@ describe('SavedObjectsRepository', () => { }); }); - it(`should return objects in the same order regardless of type`, async () => { - // TODO - }); + it.todo(`should return objects in the same order regardless of type`); it(`handles a mix of successful creates and errors`, async () => { const obj = { @@ -804,9 +820,11 @@ describe('SavedObjectsRepository', () => { }; const objects = [obj1, obj, obj2]; const response = getMockBulkCreateResponse([obj1, obj2]); - callAdminCluster.mockResolvedValue(response); // this._writeToCluster('bulk', ...) + client.bulk.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); const result = await savedObjectsRepository.bulkCreate(objects); - expect(callAdminCluster).toHaveBeenCalledTimes(1); + expect(client.bulk).toHaveBeenCalledTimes(1); expect(result).toEqual({ saved_objects: [expectSuccessResult(obj1), expectError(obj), expectSuccessResult(obj2)], }); @@ -817,7 +835,9 @@ describe('SavedObjectsRepository', () => { // we returned raw ID's when an object without an id was created. const namespace = 'myspace'; const response = getMockBulkCreateResponse([obj1, obj2], namespace); - callAdminCluster.mockResolvedValueOnce(response); // this._writeToCluster('bulk', ...) + client.bulk.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); // Bulk create one object with id unspecified, and one with id specified const result = await savedObjectsRepository.bulkCreate([{ ...obj1, id: undefined }, obj2], { @@ -884,69 +904,78 @@ describe('SavedObjectsRepository', () => { ); const bulkGetSuccess = async (objects, options) => { const response = getMockMgetResponse(objects, options?.namespace); - callAdminCluster.mockReturnValue(response); + client.mget.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); const result = await bulkGet(objects, options); - expect(callAdminCluster).toHaveBeenCalledTimes(1); + expect(client.mget).toHaveBeenCalledTimes(1); return result; }; - const _expectClusterCallArgs = ( + const _expectClientCallArgs = ( objects, { _index = expect.any(String), getId = () => expect.any(String) } ) => { - expectClusterCallArgs({ - body: { - docs: objects.map(({ type, id }) => - expect.objectContaining({ - _index, - _id: getId(type, id), - }) - ), - }, - }); + expect(client.mget).toHaveBeenCalledWith( + expect.objectContaining({ + body: { + docs: objects.map(({ type, id }) => + expect.objectContaining({ + _index, + _id: getId(type, id), + }) + ), + }, + }), + expect.anything() + ); }; - describe('cluster calls', () => { + describe('client calls', () => { it(`prepends namespace to the id when providing namespace for single-namespace type`, async () => { const getId = (type, id) => `${namespace}:${type}:${id}`; await bulkGetSuccess([obj1, obj2], { namespace }); - _expectClusterCallArgs([obj1, obj2], { getId }); + _expectClientCallArgs([obj1, obj2], { getId }); }); it(`doesn't prepend namespace to the id when providing no namespace for single-namespace type`, async () => { const getId = (type, id) => `${type}:${id}`; await bulkGetSuccess([obj1, obj2]); - _expectClusterCallArgs([obj1, obj2], { getId }); + _expectClientCallArgs([obj1, obj2], { getId }); }); it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { const getId = (type, id) => `${type}:${id}`; let objects = [obj1, obj2].map((obj) => ({ ...obj, type: NAMESPACE_AGNOSTIC_TYPE })); await bulkGetSuccess(objects, { namespace }); - _expectClusterCallArgs(objects, { getId }); + _expectClientCallArgs(objects, { getId }); - callAdminCluster.mockReset(); + client.mget.mockClear(); objects = [obj1, obj2].map((obj) => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); await bulkGetSuccess(objects, { namespace }); - _expectClusterCallArgs(objects, { getId }); + _expectClientCallArgs(objects, { getId }); }); }); describe('errors', () => { const bulkGetErrorInvalidType = async ([obj1, obj, obj2]) => { const response = getMockMgetResponse([obj1, obj2]); - callAdminCluster.mockResolvedValue(response); + client.mget.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); const result = await bulkGet([obj1, obj, obj2]); - expectClusterCalls('mget'); + expect(client.mget).toHaveBeenCalled(); expect(result).toEqual({ saved_objects: [expectSuccess(obj1), expectErrorInvalidType(obj), expectSuccess(obj2)], }); }; const bulkGetErrorNotFound = async ([obj1, obj, obj2], options, response) => { - callAdminCluster.mockResolvedValue(response); + client.mget.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); const result = await bulkGet([obj1, obj, obj2], options); - expectClusterCalls('mget'); + expect(client.mget).toHaveBeenCalled(); expect(result).toEqual({ saved_objects: [expectSuccess(obj1), expectErrorNotFound(obj), expectSuccess(obj2)], }); @@ -982,16 +1011,6 @@ describe('SavedObjectsRepository', () => { }); }); - describe('migration', () => { - it(`waits until migrations are complete before proceeding`, async () => { - migrator.runMigrations = jest.fn(async () => - expect(callAdminCluster).not.toHaveBeenCalled() - ); - await expect(bulkGetSuccess([obj1, obj2])).resolves.toBeDefined(); - expect(migrator.runMigrations).toHaveBeenCalledTimes(1); - }); - }); - describe('returns', () => { const expectSuccessResult = ({ type, id }, doc) => ({ type, @@ -1007,14 +1026,16 @@ describe('SavedObjectsRepository', () => { it(`returns early for empty objects argument`, async () => { const result = await bulkGet([]); expect(result).toEqual({ saved_objects: [] }); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.mget).not.toHaveBeenCalled(); }); it(`formats the ES response`, async () => { const response = getMockMgetResponse([obj1, obj2]); - callAdminCluster.mockResolvedValue(response); + client.mget.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); const result = await bulkGet([obj1, obj2]); - expect(callAdminCluster).toHaveBeenCalledTimes(1); + expect(client.mget).toHaveBeenCalledTimes(1); expect(result).toEqual({ saved_objects: [ expectSuccessResult(obj1, response.docs[0]), @@ -1025,10 +1046,12 @@ describe('SavedObjectsRepository', () => { it(`handles a mix of successful gets and errors`, async () => { const response = getMockMgetResponse([obj1, obj2]); - callAdminCluster.mockResolvedValue(response); + client.mget.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); const obj = { type: 'unknownType', id: 'three' }; const result = await bulkGet([obj1, obj, obj2]); - expect(callAdminCluster).toHaveBeenCalledTimes(1); + expect(client.mget).toHaveBeenCalledTimes(1); expect(result).toEqual({ saved_objects: [ expectSuccessResult(obj1, response.docs[0]), @@ -1081,20 +1104,23 @@ describe('SavedObjectsRepository', () => { const multiNamespaceObjects = objects.filter(({ type }) => registry.isMultiNamespace(type)); if (multiNamespaceObjects?.length) { const response = getMockMgetResponse(multiNamespaceObjects, options?.namespace); - callAdminCluster.mockResolvedValueOnce(response); // this._callCluster('mget', ...) + client.mget.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); } const response = getMockBulkUpdateResponse(objects, options?.namespace); - callAdminCluster.mockResolvedValue(response); // this._writeToCluster('bulk', ...) + client.bulk.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); const result = await savedObjectsRepository.bulkUpdate(objects, options); - expect(callAdminCluster).toHaveBeenCalledTimes(multiNamespaceObjects?.length ? 2 : 1); + expect(client.mget).toHaveBeenCalledTimes(multiNamespaceObjects?.length ? 1 : 0); return result; }; // bulk create calls have two objects for each source -- the action, and the source - const expectClusterCallArgsAction = ( + const expectClientCallArgsAction = ( objects, - { method, _index = expect.any(String), getId = () => expect.any(String), overrides }, - n + { method, _index = expect.any(String), getId = () => expect.any(String), overrides } ) => { const body = []; for (const { type, id } of objects) { @@ -1107,7 +1133,10 @@ describe('SavedObjectsRepository', () => { }); body.push(expect.any(Object)); } - expectClusterCallArgs({ body }, n); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); }; const expectObjArgs = ({ type, attributes }) => [ @@ -1120,44 +1149,58 @@ describe('SavedObjectsRepository', () => { }, ]; - describe('cluster calls', () => { + describe('client calls', () => { it(`should use the ES bulk action by default`, async () => { await bulkUpdateSuccess([obj1, obj2]); - expectClusterCalls('bulk'); + expect(client.bulk).toHaveBeenCalled(); }); it(`should use the ES mget action before bulk action for any types that are multi-namespace`, async () => { const objects = [obj1, { ...obj2, type: MULTI_NAMESPACE_TYPE }]; await bulkUpdateSuccess(objects); - expectClusterCalls('mget', 'bulk'); + expect(client.bulk).toHaveBeenCalled(); + expect(client.mget).toHaveBeenCalled(); + const docs = [expect.objectContaining({ _id: `${MULTI_NAMESPACE_TYPE}:${obj2.id}` })]; - expectClusterCallArgs({ body: { docs } }, 1); + expect(client.mget).toHaveBeenCalledWith( + expect.objectContaining({ body: { docs } }), + expect.anything() + ); }); it(`formats the ES request`, async () => { await bulkUpdateSuccess([obj1, obj2]); const body = [...expectObjArgs(obj1), ...expectObjArgs(obj2)]; - expectClusterCallArgs({ body }); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); }); it(`formats the ES request for any types that are multi-namespace`, async () => { const _obj2 = { ...obj2, type: MULTI_NAMESPACE_TYPE }; await bulkUpdateSuccess([obj1, _obj2]); const body = [...expectObjArgs(obj1), ...expectObjArgs(_obj2)]; - expectClusterCallArgs({ body }, 2); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); }); it(`doesnt call Elasticsearch if there are no valid objects to update`, async () => { const objects = [obj1, obj2].map((x) => ({ ...x, type: 'unknownType' })); await savedObjectsRepository.bulkUpdate(objects); - expect(callAdminCluster).toHaveBeenCalledTimes(0); + expect(client.bulk).toHaveBeenCalledTimes(0); }); it(`defaults to no references`, async () => { await bulkUpdateSuccess([obj1, obj2]); const expected = { doc: expect.not.objectContaining({ references: expect.anything() }) }; const body = [expect.any(Object), expected, expect.any(Object), expected]; - expectClusterCallArgs({ body }); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); }); it(`accepts custom references array`, async () => { @@ -1166,8 +1209,11 @@ describe('SavedObjectsRepository', () => { await bulkUpdateSuccess(objects); const expected = { doc: expect.objectContaining({ references }) }; const body = [expect.any(Object), expected, expect.any(Object), expected]; - expectClusterCallArgs({ body }); - callAdminCluster.mockReset(); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); + client.bulk.mockClear(); }; await test(references); await test(['string']); @@ -1180,8 +1226,11 @@ describe('SavedObjectsRepository', () => { await bulkUpdateSuccess(objects); const expected = { doc: expect.not.objectContaining({ references: expect.anything() }) }; const body = [expect.any(Object), expected, expect.any(Object), expected]; - expectClusterCallArgs({ body }); - callAdminCluster.mockReset(); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); + client.bulk.mockClear(); }; await test('string'); await test(123); @@ -1191,13 +1240,10 @@ describe('SavedObjectsRepository', () => { it(`defaults to a refresh setting of wait_for`, async () => { await bulkUpdateSuccess([obj1, obj2]); - expectClusterCallArgs({ refresh: 'wait_for' }); - }); - - it(`accepts a custom refresh setting`, async () => { - const refresh = 'foo'; - await bulkUpdateSuccess([obj1, obj2], { refresh }); - expectClusterCallArgs({ refresh }); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ refresh: 'wait_for' }), + expect.anything() + ); }); it(`defaults to the version of the existing document for multi-namespace types`, async () => { @@ -1211,13 +1257,13 @@ describe('SavedObjectsRepository', () => { if_seq_no: mockVersionProps._seq_no, if_primary_term: mockVersionProps._primary_term, }; - expectClusterCallArgsAction(objects, { method: 'update', overrides }, 2); + expectClientCallArgsAction(objects, { method: 'update', overrides }); }); it(`defaults to no version for types that are not multi-namespace`, async () => { const objects = [obj1, { ...obj2, type: NAMESPACE_AGNOSTIC_TYPE }]; await bulkUpdateSuccess(objects); - expectClusterCallArgsAction(objects, { method: 'update' }); + expectClientCallArgsAction(objects, { method: 'update' }); }); it(`accepts version`, async () => { @@ -1229,27 +1275,27 @@ describe('SavedObjectsRepository', () => { ]; await bulkUpdateSuccess(objects); const overrides = { if_seq_no: 100, if_primary_term: 200 }; - expectClusterCallArgsAction(objects, { method: 'update', overrides }, 2); + expectClientCallArgsAction(objects, { method: 'update', overrides }, 2); }); it(`prepends namespace to the id when providing namespace for single-namespace type`, async () => { const getId = (type, id) => `${namespace}:${type}:${id}`; await bulkUpdateSuccess([obj1, obj2], { namespace }); - expectClusterCallArgsAction([obj1, obj2], { method: 'update', getId }); + expectClientCallArgsAction([obj1, obj2], { method: 'update', getId }); }); it(`doesn't prepend namespace to the id when providing no namespace for single-namespace type`, async () => { const getId = (type, id) => `${type}:${id}`; await bulkUpdateSuccess([obj1, obj2]); - expectClusterCallArgsAction([obj1, obj2], { method: 'update', getId }); + expectClientCallArgsAction([obj1, obj2], { method: 'update', getId }); }); it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { const getId = (type, id) => `${type}:${id}`; const objects1 = [{ ...obj1, type: NAMESPACE_AGNOSTIC_TYPE }]; await bulkUpdateSuccess(objects1, { namespace }); - expectClusterCallArgsAction(objects1, { method: 'update', getId }); - callAdminCluster.mockReset(); + expectClientCallArgsAction(objects1, { method: 'update', getId }); + client.bulk.mockClear(); const overrides = { // bulkUpdate uses a preflight `get` request for multi-namespace saved objects, and specifies that version on `update` // we aren't testing for this here, but we need to include Jest assertions so this test doesn't fail @@ -1258,7 +1304,7 @@ describe('SavedObjectsRepository', () => { }; const objects2 = [{ ...obj2, type: MULTI_NAMESPACE_TYPE }]; await bulkUpdateSuccess(objects2, { namespace }); - expectClusterCallArgsAction(objects2, { method: 'update', getId, overrides }, 2); + expectClientCallArgsAction(objects2, { method: 'update', getId, overrides }, 2); }); }); @@ -1274,27 +1320,44 @@ describe('SavedObjectsRepository', () => { if (esError) { mockResponse.items[1].update = { error: esError }; } - callAdminCluster.mockResolvedValue(mockResponse); // this._writeToCluster('bulk', ...) + client.bulk.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(mockResponse) + ); const result = await savedObjectsRepository.bulkUpdate(objects); - expectClusterCalls('bulk'); + expect(client.bulk).toHaveBeenCalled(); const objCall = esError ? expectObjArgs(obj) : []; const body = [...expectObjArgs(obj1), ...objCall, ...expectObjArgs(obj2)]; - expectClusterCallArgs({ body }); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); expect(result).toEqual({ saved_objects: [expectSuccess(obj1), expectedError, expectSuccess(obj2)], }); }; const bulkUpdateMultiError = async ([obj1, _obj, obj2], options, mgetResponse) => { - callAdminCluster.mockResolvedValueOnce(mgetResponse); // this._callCluster('mget', ...) + client.mget.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(mgetResponse, { + statusCode: mgetResponse.statusCode, + }) + ); + const bulkResponse = getMockBulkUpdateResponse([obj1, obj2], namespace); - callAdminCluster.mockResolvedValue(bulkResponse); // this._writeToCluster('bulk', ...) + client.bulk.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(bulkResponse) + ); const result = await savedObjectsRepository.bulkUpdate([obj1, _obj, obj2], options); - expectClusterCalls('mget', 'bulk'); + expect(client.bulk).toHaveBeenCalled(); + expect(client.mget).toHaveBeenCalled(); const body = [...expectObjArgs(obj1), ...expectObjArgs(obj2)]; - expectClusterCallArgs({ body }, 2); + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); + expect(result).toEqual({ saved_objects: [expectSuccess(obj1), expectErrorNotFound(_obj), expectSuccess(obj2)], }); @@ -1318,7 +1381,7 @@ describe('SavedObjectsRepository', () => { it(`returns error when ES is unable to find the index (mget)`, async () => { const _obj = { ...obj, type: MULTI_NAMESPACE_TYPE }; - const mgetResponse = { status: 404 }; + const mgetResponse = { statusCode: 404 }; await bulkUpdateMultiError([obj1, _obj, obj2], { namespace }, mgetResponse); }); @@ -1350,16 +1413,6 @@ describe('SavedObjectsRepository', () => { }); }); - describe('migration', () => { - it(`waits until migrations are complete before proceeding`, async () => { - migrator.runMigrations = jest.fn(async () => - expect(callAdminCluster).not.toHaveBeenCalled() - ); - await expect(bulkUpdateSuccess([obj1, obj2])).resolves.toBeDefined(); - expect(migrator.runMigrations).toHaveReturnedTimes(1); - }); - }); - describe('returns', () => { const expectSuccessResult = ({ type, id, attributes, references, namespaces }) => ({ type, @@ -1393,9 +1446,12 @@ describe('SavedObjectsRepository', () => { }; const objects = [obj1, obj, obj2]; const mockResponse = getMockBulkUpdateResponse(objects); - callAdminCluster.mockResolvedValue(mockResponse); // this._writeToCluster('bulk', ...) + client.bulk.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(mockResponse) + ); + const result = await savedObjectsRepository.bulkUpdate(objects); - expect(callAdminCluster).toHaveBeenCalledTimes(1); + expect(client.bulk).toHaveBeenCalledTimes(1); expect(result).toEqual({ saved_objects: [expectSuccessResult(obj1), expectError(obj), expectSuccessResult(obj2)], }); @@ -1416,10 +1472,12 @@ describe('SavedObjectsRepository', () => { describe('#create', () => { beforeEach(() => { - callAdminCluster.mockImplementation((method, params) => ({ - _id: params.id, - ...mockVersionProps, - })); + client.create.mockImplementation((params) => + elasticsearchClientMock.createSuccessTransportRequestPromise({ + _id: params.id, + ...mockVersionProps, + }) + ); }); const type = 'index-pattern'; @@ -1436,52 +1494,49 @@ describe('SavedObjectsRepository', () => { const createSuccess = async (type, attributes, options) => { const result = await savedObjectsRepository.create(type, attributes, options); - expect(callAdminCluster).toHaveBeenCalledTimes( - registry.isMultiNamespace(type) && options.overwrite ? 2 : 1 + expect(client.get).toHaveBeenCalledTimes( + registry.isMultiNamespace(type) && options.overwrite ? 1 : 0 ); return result; }; - describe('cluster calls', () => { + describe('client calls', () => { it(`should use the ES create action if ID is undefined and overwrite=true`, async () => { await createSuccess(type, attributes, { overwrite: true }); - expectClusterCalls('create'); + expect(client.create).toHaveBeenCalled(); }); it(`should use the ES create action if ID is undefined and overwrite=false`, async () => { await createSuccess(type, attributes); - expectClusterCalls('create'); + expect(client.create).toHaveBeenCalled(); }); it(`should use the ES index action if ID is defined and overwrite=true`, async () => { await createSuccess(type, attributes, { id, overwrite: true }); - expectClusterCalls('index'); + expect(client.index).toHaveBeenCalled(); }); it(`should use the ES create action if ID is defined and overwrite=false`, async () => { await createSuccess(type, attributes, { id }); - expectClusterCalls('create'); + expect(client.create).toHaveBeenCalled(); }); it(`should use the ES get action then index action if type is multi-namespace, ID is defined, and overwrite=true`, async () => { await createSuccess(MULTI_NAMESPACE_TYPE, attributes, { id, overwrite: true }); - expectClusterCalls('get', 'index'); + expect(client.get).toHaveBeenCalled(); + expect(client.index).toHaveBeenCalled(); }); it(`defaults to empty references array`, async () => { await createSuccess(type, attributes, { id }); - expectClusterCallArgs({ - body: expect.objectContaining({ references: [] }), - }); + expect(client.create.mock.calls[0][0].body.references).toEqual([]); }); it(`accepts custom references array`, async () => { const test = async (references) => { await createSuccess(type, attributes, { id, references }); - expectClusterCallArgs({ - body: expect.objectContaining({ references }), - }); - callAdminCluster.mockReset(); + expect(client.create.mock.calls[0][0].body.references).toEqual(references); + client.create.mockClear(); }; await test(references); await test(['string']); @@ -1491,10 +1546,8 @@ describe('SavedObjectsRepository', () => { it(`doesn't accept custom references if not an array`, async () => { const test = async (references) => { await createSuccess(type, attributes, { id, references }); - expectClusterCallArgs({ - body: expect.not.objectContaining({ references: expect.anything() }), - }); - callAdminCluster.mockReset(); + expect(client.create.mock.calls[0][0].body.references).not.toBeDefined(); + client.create.mockClear(); }; await test('string'); await test(123); @@ -1504,49 +1557,75 @@ describe('SavedObjectsRepository', () => { it(`defaults to a refresh setting of wait_for`, async () => { await createSuccess(type, attributes); - expectClusterCallArgs({ refresh: 'wait_for' }); - }); - - it(`accepts a custom refresh setting`, async () => { - const refresh = 'foo'; - await createSuccess(type, attributes, { refresh }); - expectClusterCallArgs({ refresh }); + expect(client.create).toHaveBeenCalledWith( + expect.objectContaining({ refresh: 'wait_for' }), + expect.anything() + ); }); it(`should use default index`, async () => { await createSuccess(type, attributes, { id }); - expectClusterCallArgs({ index: '.kibana-test' }); + expect(client.create).toHaveBeenCalledWith( + expect.objectContaining({ index: '.kibana-test' }), + expect.anything() + ); }); it(`should use custom index`, async () => { await createSuccess(CUSTOM_INDEX_TYPE, attributes, { id }); - expectClusterCallArgs({ index: 'custom' }); + expect(client.create).toHaveBeenCalledWith( + expect.objectContaining({ index: 'custom' }), + expect.anything() + ); }); it(`self-generates an id if none is provided`, async () => { await createSuccess(type, attributes); - expectClusterCallArgs({ - id: expect.objectContaining(/index-pattern:[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}/), - }); + expect(client.create).toHaveBeenCalledWith( + expect.objectContaining({ + id: expect.objectContaining(/index-pattern:[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}/), + }), + expect.anything() + ); }); it(`prepends namespace to the id when providing namespace for single-namespace type`, async () => { await createSuccess(type, attributes, { id, namespace }); - expectClusterCallArgs({ id: `${namespace}:${type}:${id}` }); + expect(client.create).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${namespace}:${type}:${id}`, + }), + expect.anything() + ); }); it(`doesn't prepend namespace to the id when providing no namespace for single-namespace type`, async () => { await createSuccess(type, attributes, { id }); - expectClusterCallArgs({ id: `${type}:${id}` }); + expect(client.create).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${type}:${id}`, + }), + expect.anything() + ); }); it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { await createSuccess(NAMESPACE_AGNOSTIC_TYPE, attributes, { id, namespace }); - expectClusterCallArgs({ id: `${NAMESPACE_AGNOSTIC_TYPE}:${id}` }); - callAdminCluster.mockReset(); + expect(client.create).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${NAMESPACE_AGNOSTIC_TYPE}:${id}`, + }), + expect.anything() + ); + client.create.mockClear(); await createSuccess(MULTI_NAMESPACE_TYPE, attributes, { id, namespace }); - expectClusterCallArgs({ id: `${MULTI_NAMESPACE_TYPE}:${id}` }); + expect(client.create).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${MULTI_NAMESPACE_TYPE}:${id}`, + }), + expect.anything() + ); }); }); @@ -1555,14 +1634,14 @@ describe('SavedObjectsRepository', () => { await expect(savedObjectsRepository.create('unknownType', attributes)).rejects.toThrowError( createUnsupportedTypeError('unknownType') ); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.create).not.toHaveBeenCalled(); }); it(`throws when type is hidden`, async () => { await expect(savedObjectsRepository.create(HIDDEN_TYPE, attributes)).rejects.toThrowError( createUnsupportedTypeError(HIDDEN_TYPE) ); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.create).not.toHaveBeenCalled(); }); it(`throws when there is a conflict with an existing multi-namespace saved object (get)`, async () => { @@ -1571,7 +1650,9 @@ describe('SavedObjectsRepository', () => { id, namespace: 'bar-namespace', }); - callAdminCluster.mockResolvedValue(response); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); await expect( savedObjectsRepository.create(MULTI_NAMESPACE_TYPE, attributes, { id, @@ -1579,16 +1660,12 @@ describe('SavedObjectsRepository', () => { namespace, }) ).rejects.toThrowError(createConflictError(MULTI_NAMESPACE_TYPE, id)); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalled(); }); - it(`throws when automatic index creation fails`, async () => { - // TODO - }); + it.todo(`throws when automatic index creation fails`); - it(`throws when an unexpected failure occurs`, async () => { - // TODO - }); + it.todo(`throws when an unexpected failure occurs`); }); describe('migration', () => { @@ -1596,14 +1673,6 @@ describe('SavedObjectsRepository', () => { migrator.migrateDocument.mockImplementation(mockMigrateDocument); }); - it(`waits until migrations are complete before proceeding`, async () => { - migrator.runMigrations = jest.fn(async () => - expect(callAdminCluster).not.toHaveBeenCalled() - ); - await expect(createSuccess(type, attributes, { id, namespace })).resolves.toBeDefined(); - expect(migrator.runMigrations).toHaveBeenCalledTimes(1); - }); - it(`migrates a document and serializes the migrated doc`, async () => { const migrationVersion = mockMigrationVersion; await createSuccess(type, attributes, { id, references, migrationVersion }); @@ -1628,7 +1697,7 @@ describe('SavedObjectsRepository', () => { await createSuccess(NAMESPACE_AGNOSTIC_TYPE, attributes, { id, namespace }); expectMigrationArgs({ namespace: expect.anything() }, false, 1); - callAdminCluster.mockReset(); + client.create.mockClear(); await createSuccess(MULTI_NAMESPACE_TYPE, attributes, { id }); expectMigrationArgs({ namespace: expect.anything() }, false, 2); }); @@ -1647,7 +1716,7 @@ describe('SavedObjectsRepository', () => { await createSuccess(type, attributes, { id }); expectMigrationArgs({ namespaces: expect.anything() }, false, 1); - callAdminCluster.mockReset(); + client.create.mockClear(); await createSuccess(NAMESPACE_AGNOSTIC_TYPE, attributes, { id }); expectMigrationArgs({ namespaces: expect.anything() }, false, 2); }); @@ -1678,33 +1747,43 @@ describe('SavedObjectsRepository', () => { const deleteSuccess = async (type, id, options) => { if (registry.isMultiNamespace(type)) { const mockGetResponse = getMockGetResponse({ type, id, namespace: options?.namespace }); - callAdminCluster.mockResolvedValueOnce(mockGetResponse); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(mockGetResponse) + ); } - callAdminCluster.mockResolvedValue({ result: 'deleted' }); // this._writeToCluster('delete', ...) + client.delete.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ result: 'deleted' }) + ); const result = await savedObjectsRepository.delete(type, id, options); - expect(callAdminCluster).toHaveBeenCalledTimes(registry.isMultiNamespace(type) ? 2 : 1); + expect(client.get).toHaveBeenCalledTimes(registry.isMultiNamespace(type) ? 1 : 0); return result; }; - describe('cluster calls', () => { + describe('client calls', () => { it(`should use the ES delete action when not using a multi-namespace type`, async () => { await deleteSuccess(type, id); - expectClusterCalls('delete'); + expect(client.delete).toHaveBeenCalledTimes(1); }); it(`should use ES get action then delete action when using a multi-namespace type with no namespaces remaining`, async () => { await deleteSuccess(MULTI_NAMESPACE_TYPE, id); - expectClusterCalls('get', 'delete'); + expect(client.get).toHaveBeenCalledTimes(1); + expect(client.delete).toHaveBeenCalledTimes(1); }); it(`should use ES get action then update action when using a multi-namespace type with one or more namespaces remaining`, async () => { const mockResponse = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id }); mockResponse._source.namespaces = ['default', 'some-other-nameespace']; - callAdminCluster - .mockResolvedValueOnce(mockResponse) // this._callCluster('get', ...) - .mockResolvedValue({ result: 'updated' }); // this._writeToCluster('update', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(mockResponse) + ); + client.update.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ result: 'updated' }) + ); + await savedObjectsRepository.delete(MULTI_NAMESPACE_TYPE, id); - expectClusterCalls('get', 'update'); + expect(client.get).toHaveBeenCalledTimes(1); + expect(client.update).toHaveBeenCalledTimes(1); }); it(`includes the version of the existing document when type is multi-namespace`, async () => { @@ -1713,37 +1792,49 @@ describe('SavedObjectsRepository', () => { if_seq_no: mockVersionProps._seq_no, if_primary_term: mockVersionProps._primary_term, }; - expectClusterCallArgs(versionProperties, 2); + expect(client.delete).toHaveBeenCalledWith( + expect.objectContaining(versionProperties), + expect.anything() + ); }); it(`defaults to a refresh setting of wait_for`, async () => { await deleteSuccess(type, id); - expectClusterCallArgs({ refresh: 'wait_for' }); - }); - - it(`accepts a custom refresh setting`, async () => { - const refresh = 'foo'; - await deleteSuccess(type, id, { refresh }); - expectClusterCallArgs({ refresh }); + expect(client.delete).toHaveBeenCalledWith( + expect.objectContaining({ refresh: 'wait_for' }), + expect.anything() + ); }); it(`prepends namespace to the id when providing namespace for single-namespace type`, async () => { await deleteSuccess(type, id, { namespace }); - expectClusterCallArgs({ id: `${namespace}:${type}:${id}` }); + expect(client.delete).toHaveBeenCalledWith( + expect.objectContaining({ id: `${namespace}:${type}:${id}` }), + expect.anything() + ); }); it(`doesn't prepend namespace to the id when providing no namespace for single-namespace type`, async () => { await deleteSuccess(type, id); - expectClusterCallArgs({ id: `${type}:${id}` }); + expect(client.delete).toHaveBeenCalledWith( + expect.objectContaining({ id: `${type}:${id}` }), + expect.anything() + ); }); it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { await deleteSuccess(NAMESPACE_AGNOSTIC_TYPE, id, { namespace }); - expectClusterCallArgs({ id: `${NAMESPACE_AGNOSTIC_TYPE}:${id}` }); + expect(client.delete).toHaveBeenCalledWith( + expect.objectContaining({ id: `${NAMESPACE_AGNOSTIC_TYPE}:${id}` }), + expect.anything() + ); - callAdminCluster.mockReset(); + client.delete.mockClear(); await deleteSuccess(MULTI_NAMESPACE_TYPE, id, { namespace }); - expectClusterCallArgs({ id: `${MULTI_NAMESPACE_TYPE}:${id}` }); + expect(client.delete).toHaveBeenCalledWith( + expect.objectContaining({ id: `${MULTI_NAMESPACE_TYPE}:${id}` }), + expect.anything() + ); }); }); @@ -1756,73 +1847,82 @@ describe('SavedObjectsRepository', () => { it(`throws when type is invalid`, async () => { await expectNotFoundError('unknownType', id); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.delete).not.toHaveBeenCalled(); }); it(`throws when type is hidden`, async () => { await expectNotFoundError(HIDDEN_TYPE, id); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.delete).not.toHaveBeenCalled(); }); it(`throws when ES is unable to find the document during get`, async () => { - callAdminCluster.mockResolvedValue({ found: false }); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ found: false }) + ); await expectNotFoundError(MULTI_NAMESPACE_TYPE, id); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the index during get`, async () => { - callAdminCluster.mockResolvedValue({ status: 404 }); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); await expectNotFoundError(MULTI_NAMESPACE_TYPE, id); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when the type is multi-namespace and the document exists, but not in this namespace`, async () => { const response = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id, namespace }); - callAdminCluster.mockResolvedValue(response); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); await expectNotFoundError(MULTI_NAMESPACE_TYPE, id, { namespace: 'bar-namespace' }); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the document during update`, async () => { const mockResponse = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id }); mockResponse._source.namespaces = ['default', 'some-other-nameespace']; - callAdminCluster - .mockResolvedValueOnce(mockResponse) // this._callCluster('get', ...) - .mockResolvedValue({ status: 404 }); // this._writeToCluster('update', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(mockResponse) + ); + client.update.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); + await expectNotFoundError(MULTI_NAMESPACE_TYPE, id); - expectClusterCalls('get', 'update'); + expect(client.get).toHaveBeenCalledTimes(1); + expect(client.update).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the document during delete`, async () => { - callAdminCluster.mockResolvedValue({ result: 'not_found' }); // this._writeToCluster('delete', ...) + client.delete.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ result: 'not_found' }) + ); await expectNotFoundError(type, id); - expectClusterCalls('delete'); + expect(client.delete).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the index during delete`, async () => { - callAdminCluster.mockResolvedValue({ error: { type: 'index_not_found_exception' } }); // this._writeToCluster('delete', ...) + client.delete.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + error: { type: 'index_not_found_exception' }, + }) + ); await expectNotFoundError(type, id); - expectClusterCalls('delete'); + expect(client.delete).toHaveBeenCalledTimes(1); }); it(`throws when ES returns an unexpected response`, async () => { - callAdminCluster.mockResolvedValue({ result: 'something unexpected' }); // this._writeToCluster('delete', ...) + client.delete.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + result: 'something unexpected', + }) + ); await expect(savedObjectsRepository.delete(type, id)).rejects.toThrowError( 'Unexpected Elasticsearch DELETE response' ); - expectClusterCalls('delete'); - }); - }); - - describe('migration', () => { - it(`waits until migrations are complete before proceeding`, async () => { - let callAdminClusterCount = 0; - migrator.runMigrations = jest.fn(async () => - // runMigrations should resolve before callAdminCluster is initiated - expect(callAdminCluster).toHaveBeenCalledTimes(callAdminClusterCount++) - ); - await expect(deleteSuccess(type, id)).resolves.toBeDefined(); - expect(migrator.runMigrations).toHaveBeenCalledTimes(1); + expect(client.delete).toHaveBeenCalledTimes(1); }); }); @@ -1853,33 +1953,27 @@ describe('SavedObjectsRepository', () => { }; const deleteByNamespaceSuccess = async (namespace, options) => { - callAdminCluster.mockResolvedValue(mockUpdateResults); + client.updateByQuery.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(mockUpdateResults) + ); const result = await savedObjectsRepository.deleteByNamespace(namespace, options); expect(getSearchDslNS.getSearchDsl).toHaveBeenCalledTimes(1); - expect(callAdminCluster).toHaveBeenCalledTimes(1); + expect(client.updateByQuery).toHaveBeenCalledTimes(1); return result; }; - describe('cluster calls', () => { + describe('client calls', () => { it(`should use the ES updateByQuery action`, async () => { await deleteByNamespaceSuccess(namespace); - expectClusterCalls('updateByQuery'); - }); - - it(`defaults to a refresh setting of wait_for`, async () => { - await deleteByNamespaceSuccess(namespace); - expectClusterCallArgs({ refresh: 'wait_for' }); - }); - - it(`accepts a custom refresh setting`, async () => { - const refresh = 'foo'; - await deleteByNamespaceSuccess(namespace, { refresh }); - expectClusterCallArgs({ refresh }); + expect(client.updateByQuery).toHaveBeenCalledTimes(1); }); it(`should use all indices for types that are not namespace-agnostic`, async () => { await deleteByNamespaceSuccess(namespace); - expectClusterCallArgs({ index: ['.kibana-test', 'custom'] }, 1); + expect(client.updateByQuery).toHaveBeenCalledWith( + expect.objectContaining({ index: ['.kibana-test', 'custom'] }), + expect.anything() + ); }); }); @@ -1889,7 +1983,7 @@ describe('SavedObjectsRepository', () => { await expect(savedObjectsRepository.deleteByNamespace(namespace)).rejects.toThrowError( `namespace is required, and must be a string` ); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.updateByQuery).not.toHaveBeenCalled(); }; await test(undefined); await test(['namespace']); @@ -1898,16 +1992,6 @@ describe('SavedObjectsRepository', () => { }); }); - describe('migration', () => { - it(`waits until migrations are complete before proceeding`, async () => { - migrator.runMigrations = jest.fn(async () => - expect(callAdminCluster).not.toHaveBeenCalled() - ); - await expect(deleteByNamespaceSuccess(namespace)).resolves.toBeDefined(); - expect(migrator.runMigrations).toHaveBeenCalledTimes(1); - }); - }); - describe('returns', () => { it(`returns the query results on success`, async () => { const result = await deleteByNamespaceSuccess(namespace); @@ -2002,64 +2086,90 @@ describe('SavedObjectsRepository', () => { const namespace = 'foo-namespace'; const findSuccess = async (options, namespace) => { - callAdminCluster.mockResolvedValue(generateSearchResults(namespace)); + client.search.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise( + generateSearchResults(namespace) + ) + ); const result = await savedObjectsRepository.find(options); expect(getSearchDslNS.getSearchDsl).toHaveBeenCalledTimes(1); - expect(callAdminCluster).toHaveBeenCalledTimes(1); + expect(client.search).toHaveBeenCalledTimes(1); return result; }; - describe('cluster calls', () => { + describe('client calls', () => { it(`should use the ES search action`, async () => { await findSuccess({ type }); - expectClusterCalls('search'); + expect(client.search).toHaveBeenCalledTimes(1); }); it(`merges output of getSearchDsl into es request body`, async () => { const query = { query: 1, aggregations: 2 }; getSearchDslNS.getSearchDsl.mockReturnValue(query); await findSuccess({ type }); - expectClusterCallArgs({ body: expect.objectContaining({ ...query }) }); + + expect(client.search).toHaveBeenCalledWith( + expect.objectContaining({ + body: expect.objectContaining({ ...query }), + }), + expect.anything() + ); }); it(`accepts per_page/page`, async () => { await findSuccess({ type, perPage: 10, page: 6 }); - expectClusterCallArgs({ - size: 10, - from: 50, - }); + expect(client.search).toHaveBeenCalledWith( + expect.objectContaining({ + size: 10, + from: 50, + }), + expect.anything() + ); }); it(`accepts preference`, async () => { await findSuccess({ type, preference: 'pref' }); - expectClusterCallArgs({ preference: 'pref' }); + expect(client.search).toHaveBeenCalledWith( + expect.objectContaining({ + preference: 'pref', + }), + expect.anything() + ); }); it(`can filter by fields`, async () => { await findSuccess({ type, fields: ['title'] }); - expectClusterCallArgs({ - _source: [ - `${type}.title`, - 'namespace', - 'namespaces', - 'type', - 'references', - 'migrationVersion', - 'updated_at', - 'title', - ], - }); + expect(client.search).toHaveBeenCalledWith( + expect.objectContaining({ + _source: [ + `${type}.title`, + 'namespace', + 'namespaces', + 'type', + 'references', + 'migrationVersion', + 'updated_at', + 'title', + ], + }), + expect.anything() + ); }); it(`should set rest_total_hits_as_int to true on a request`, async () => { await findSuccess({ type }); - expectClusterCallArgs({ rest_total_hits_as_int: true }); + expect(client.search).toHaveBeenCalledWith( + expect.objectContaining({ + rest_total_hits_as_int: true, + }), + expect.anything() + ); }); - it(`should not make a cluster call when attempting to find only invalid or hidden types`, async () => { + it(`should not make a client call when attempting to find only invalid or hidden types`, async () => { const test = async (types) => { await savedObjectsRepository.find({ type: types }); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.search).not.toHaveBeenCalled(); }; await test('unknownType'); @@ -2073,21 +2183,21 @@ describe('SavedObjectsRepository', () => { await expect(savedObjectsRepository.find({})).rejects.toThrowError( 'options.type must be a string or an array of strings' ); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.search).not.toHaveBeenCalled(); }); it(`throws when searchFields is defined but not an array`, async () => { await expect( savedObjectsRepository.find({ type, searchFields: 'string' }) ).rejects.toThrowError('options.searchFields must be an array'); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.search).not.toHaveBeenCalled(); }); it(`throws when fields is defined but not an array`, async () => { await expect(savedObjectsRepository.find({ type, fields: 'string' })).rejects.toThrowError( 'options.fields must be an array' ); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.search).not.toHaveBeenCalled(); }); it(`throws when KQL filter syntax is invalid`, async () => { @@ -2113,24 +2223,16 @@ describe('SavedObjectsRepository', () => { --------------------------------^: Bad Request] `); expect(getSearchDslNS.getSearchDsl).not.toHaveBeenCalled(); - expect(callAdminCluster).not.toHaveBeenCalled(); - }); - }); - - describe('migration', () => { - it(`waits until migrations are complete before proceeding`, async () => { - migrator.runMigrations = jest.fn(async () => - expect(callAdminCluster).not.toHaveBeenCalled() - ); - await expect(findSuccess({ type })).resolves.toBeDefined(); - expect(migrator.runMigrations).toHaveBeenCalledTimes(1); + expect(client.search).not.toHaveBeenCalled(); }); }); describe('returns', () => { it(`formats the ES response when there is no namespace`, async () => { const noNamespaceSearchResults = generateSearchResults(); - callAdminCluster.mockReturnValue(noNamespaceSearchResults); + client.search.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(noNamespaceSearchResults) + ); const count = noNamespaceSearchResults.hits.hits.length; const response = await savedObjectsRepository.find({ type }); @@ -2154,7 +2256,9 @@ describe('SavedObjectsRepository', () => { it(`formats the ES response when there is a namespace`, async () => { const namespacedSearchResults = generateSearchResults(namespace); - callAdminCluster.mockReturnValue(namespacedSearchResults); + client.search.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(namespacedSearchResults) + ); const count = namespacedSearchResults.hits.hits.length; const response = await savedObjectsRepository.find({ type, namespaces: [namespace] }); @@ -2298,35 +2402,57 @@ describe('SavedObjectsRepository', () => { const getSuccess = async (type, id, options) => { const response = getMockGetResponse({ type, id, namespace: options?.namespace }); - callAdminCluster.mockResolvedValue(response); + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); const result = await savedObjectsRepository.get(type, id, options); - expect(callAdminCluster).toHaveBeenCalledTimes(1); + expect(client.get).toHaveBeenCalledTimes(1); return result; }; - describe('cluster calls', () => { + describe('client calls', () => { it(`should use the ES get action`, async () => { await getSuccess(type, id); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`prepends namespace to the id when providing namespace for single-namespace type`, async () => { await getSuccess(type, id, { namespace }); - expectClusterCallArgs({ id: `${namespace}:${type}:${id}` }); + expect(client.get).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${namespace}:${type}:${id}`, + }), + expect.anything() + ); }); it(`doesn't prepend namespace to the id when providing no namespace for single-namespace type`, async () => { await getSuccess(type, id); - expectClusterCallArgs({ id: `${type}:${id}` }); + expect(client.get).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${type}:${id}`, + }), + expect.anything() + ); }); it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { await getSuccess(NAMESPACE_AGNOSTIC_TYPE, id, { namespace }); - expectClusterCallArgs({ id: `${NAMESPACE_AGNOSTIC_TYPE}:${id}` }); + expect(client.get).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${NAMESPACE_AGNOSTIC_TYPE}:${id}`, + }), + expect.anything() + ); - callAdminCluster.mockReset(); + client.get.mockClear(); await getSuccess(MULTI_NAMESPACE_TYPE, id, { namespace }); - expectClusterCallArgs({ id: `${MULTI_NAMESPACE_TYPE}:${id}` }); + expect(client.get).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${MULTI_NAMESPACE_TYPE}:${id}`, + }), + expect.anything() + ); }); }); @@ -2339,41 +2465,37 @@ describe('SavedObjectsRepository', () => { it(`throws when type is invalid`, async () => { await expectNotFoundError('unknownType', id); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.get).not.toHaveBeenCalled(); }); it(`throws when type is hidden`, async () => { await expectNotFoundError(HIDDEN_TYPE, id); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.get).not.toHaveBeenCalled(); }); it(`throws when ES is unable to find the document during get`, async () => { - callAdminCluster.mockResolvedValue({ found: false }); + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ found: false }) + ); await expectNotFoundError(type, id); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the index during get`, async () => { - callAdminCluster.mockResolvedValue({ status: 404 }); + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); await expectNotFoundError(type, id); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when type is multi-namespace and the document exists, but not in this namespace`, async () => { const response = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id, namespace }); - callAdminCluster.mockResolvedValue(response); - await expectNotFoundError(MULTI_NAMESPACE_TYPE, id, { namespace: 'bar-namespace' }); - expectClusterCalls('get'); - }); - }); - - describe('migration', () => { - it(`waits until migrations are complete before proceeding`, async () => { - migrator.runMigrations = jest.fn(async () => - expect(callAdminCluster).not.toHaveBeenCalled() + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) ); - await expect(getSuccess(type, id)).resolves.toBeDefined(); - expect(migrator.runMigrations).toHaveBeenCalledTimes(1); + await expectNotFoundError(MULTI_NAMESPACE_TYPE, id, { namespace: 'bar-namespace' }); + expect(client.get).toHaveBeenCalledTimes(1); }); }); @@ -2419,68 +2541,93 @@ describe('SavedObjectsRepository', () => { const isMultiNamespace = registry.isMultiNamespace(type); if (isMultiNamespace) { const response = getMockGetResponse({ type, id, namespace: options?.namespace }); - callAdminCluster.mockResolvedValueOnce(response); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); } - callAdminCluster.mockImplementation((method, params) => ({ - _id: params.id, - ...mockVersionProps, - _index: '.kibana', - get: { - found: true, - _source: { - type, - ...mockTimestampFields, - [type]: { - [field]: 8468, - defaultIndex: 'logstash-*', + client.update.mockImplementation((params) => + elasticsearchClientMock.createSuccessTransportRequestPromise({ + _id: params.id, + ...mockVersionProps, + _index: '.kibana', + get: { + found: true, + _source: { + type, + ...mockTimestampFields, + [type]: { + [field]: 8468, + defaultIndex: 'logstash-*', + }, }, }, - }, - })); + }) + ); + const result = await savedObjectsRepository.incrementCounter(type, id, field, options); - expect(callAdminCluster).toHaveBeenCalledTimes(isMultiNamespace ? 2 : 1); + expect(client.get).toHaveBeenCalledTimes(isMultiNamespace ? 1 : 0); return result; }; - describe('cluster calls', () => { + describe('client calls', () => { it(`should use the ES update action if type is not multi-namespace`, async () => { await incrementCounterSuccess(type, id, field, { namespace }); - expectClusterCalls('update'); + expect(client.update).toHaveBeenCalledTimes(1); }); it(`should use the ES get action then update action if type is multi-namespace, ID is defined, and overwrite=true`, async () => { await incrementCounterSuccess(MULTI_NAMESPACE_TYPE, id, field, { namespace }); - expectClusterCalls('get', 'update'); + expect(client.get).toHaveBeenCalledTimes(1); + expect(client.update).toHaveBeenCalledTimes(1); }); it(`defaults to a refresh setting of wait_for`, async () => { await incrementCounterSuccess(type, id, field, { namespace }); - expectClusterCallArgs({ refresh: 'wait_for' }); - }); - - it(`accepts a custom refresh setting`, async () => { - const refresh = 'foo'; - await incrementCounterSuccess(type, id, field, { namespace, refresh }); - expectClusterCallArgs({ refresh }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + refresh: 'wait_for', + }), + expect.anything() + ); }); it(`prepends namespace to the id when providing namespace for single-namespace type`, async () => { await incrementCounterSuccess(type, id, field, { namespace }); - expectClusterCallArgs({ id: `${namespace}:${type}:${id}` }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${namespace}:${type}:${id}`, + }), + expect.anything() + ); }); it(`doesn't prepend namespace to the id when providing no namespace for single-namespace type`, async () => { await incrementCounterSuccess(type, id, field); - expectClusterCallArgs({ id: `${type}:${id}` }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${type}:${id}`, + }), + expect.anything() + ); }); it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { await incrementCounterSuccess(NAMESPACE_AGNOSTIC_TYPE, id, field, { namespace }); - expectClusterCallArgs({ id: `${NAMESPACE_AGNOSTIC_TYPE}:${id}` }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${NAMESPACE_AGNOSTIC_TYPE}:${id}`, + }), + expect.anything() + ); - callAdminCluster.mockReset(); + client.update.mockClear(); await incrementCounterSuccess(MULTI_NAMESPACE_TYPE, id, field, { namespace }); - expectClusterCallArgs({ id: `${MULTI_NAMESPACE_TYPE}:${id}` }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${MULTI_NAMESPACE_TYPE}:${id}`, + }), + expect.anything() + ); }); }); @@ -2496,7 +2643,7 @@ describe('SavedObjectsRepository', () => { await expect( savedObjectsRepository.incrementCounter(type, id, field) ).rejects.toThrowError(`"type" argument must be a string`); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }; await test(null); @@ -2510,7 +2657,7 @@ describe('SavedObjectsRepository', () => { await expect( savedObjectsRepository.incrementCounter(type, id, field) ).rejects.toThrowError(`"counterFieldName" argument must be a string`); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }; await test(null); @@ -2521,12 +2668,12 @@ describe('SavedObjectsRepository', () => { it(`throws when type is invalid`, async () => { await expectUnsupportedTypeError('unknownType', id, field); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }); it(`throws when type is hidden`, async () => { await expectUnsupportedTypeError(HIDDEN_TYPE, id, field); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }); it(`throws when there is a conflict with an existing multi-namespace saved object (get)`, async () => { @@ -2535,11 +2682,13 @@ describe('SavedObjectsRepository', () => { id, namespace: 'bar-namespace', }); - callAdminCluster.mockResolvedValue(response); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); await expect( savedObjectsRepository.incrementCounter(MULTI_NAMESPACE_TYPE, id, field, { namespace }) ).rejects.toThrowError(createConflictError(MULTI_NAMESPACE_TYPE, id)); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); }); @@ -2548,16 +2697,6 @@ describe('SavedObjectsRepository', () => { migrator.migrateDocument.mockImplementation(mockMigrateDocument); }); - it(`waits until migrations are complete before proceeding`, async () => { - migrator.runMigrations = jest.fn(async () => - expect(callAdminCluster).not.toHaveBeenCalled() - ); - await expect( - incrementCounterSuccess(type, id, field, { namespace }) - ).resolves.toBeDefined(); - expect(migrator.runMigrations).toHaveBeenCalledTimes(1); - }); - it(`migrates a document and serializes the migrated doc`, async () => { const migrationVersion = mockMigrationVersion; await incrementCounterSuccess(type, id, field, { migrationVersion }); @@ -2572,22 +2711,24 @@ describe('SavedObjectsRepository', () => { describe('returns', () => { it(`formats the ES response`, async () => { - callAdminCluster.mockImplementation((method, params) => ({ - _id: params.id, - ...mockVersionProps, - _index: '.kibana', - get: { - found: true, - _source: { - type: 'config', - ...mockTimestampFields, - config: { - buildNum: 8468, - defaultIndex: 'logstash-*', + client.update.mockImplementation((params) => + elasticsearchClientMock.createSuccessTransportRequestPromise({ + _id: params.id, + ...mockVersionProps, + _index: '.kibana', + get: { + found: true, + _source: { + type: 'config', + ...mockTimestampFields, + config: { + buildNum: 8468, + defaultIndex: 'logstash-*', + }, }, }, - }, - })); + }) + ); const response = await savedObjectsRepository.incrementCounter( 'config', @@ -2623,7 +2764,9 @@ describe('SavedObjectsRepository', () => { // mock a document that exists in two namespaces const mockResponse = getMockGetResponse({ type, id }); mockResponse._source.namespaces = namespaces; - callAdminCluster.mockResolvedValueOnce(mockResponse); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(mockResponse) + ); }; const deleteFromNamespacesSuccess = async ( @@ -2633,71 +2776,96 @@ describe('SavedObjectsRepository', () => { currentNamespaces, options ) => { - mockGetResponse(type, id, currentNamespaces); // this._callCluster('get', ...) - const isDelete = currentNamespaces.every((namespace) => namespaces.includes(namespace)); - callAdminCluster.mockResolvedValue({ - _id: `${type}:${id}`, - ...mockVersionProps, - result: isDelete ? 'deleted' : 'updated', - }); // this._writeToCluster('delete', ...) *or* this._writeToCluster('update', ...) - const result = await savedObjectsRepository.deleteFromNamespaces( - type, - id, - namespaces, - options + mockGetResponse(type, id, currentNamespaces); + client.delete.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + _id: `${type}:${id}`, + ...mockVersionProps, + result: 'deleted', + }) ); - expect(callAdminCluster).toHaveBeenCalledTimes(2); - return result; + client.update.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + _id: `${type}:${id}`, + ...mockVersionProps, + result: 'updated', + }) + ); + + return await savedObjectsRepository.deleteFromNamespaces(type, id, namespaces, options); }; - describe('cluster calls', () => { + describe('client calls', () => { describe('delete action', () => { const deleteFromNamespacesSuccessDelete = async (expectFn, options, _type = type) => { const test = async (namespaces) => { await deleteFromNamespacesSuccess(_type, id, namespaces, namespaces, options); expectFn(); - callAdminCluster.mockReset(); + client.delete.mockClear(); + client.get.mockClear(); }; await test([namespace1]); await test([namespace1, namespace2]); }; it(`should use ES get action then delete action if the object has no namespaces remaining`, async () => { - const expectFn = () => expectClusterCalls('get', 'delete'); + const expectFn = () => { + expect(client.delete).toHaveBeenCalledTimes(1); + expect(client.get).toHaveBeenCalledTimes(1); + }; await deleteFromNamespacesSuccessDelete(expectFn); }); it(`formats the ES requests`, async () => { const expectFn = () => { - expectClusterCallArgs({ id: `${type}:${id}` }, 1); + expect(client.delete).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${type}:${id}`, + }), + expect.anything() + ); + const versionProperties = { if_seq_no: mockVersionProps._seq_no, if_primary_term: mockVersionProps._primary_term, }; - expectClusterCallArgs({ id: `${type}:${id}`, ...versionProperties }, 2); + expect(client.delete).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${type}:${id}`, + ...versionProperties, + }), + expect.anything() + ); }; await deleteFromNamespacesSuccessDelete(expectFn); }); it(`defaults to a refresh setting of wait_for`, async () => { await deleteFromNamespacesSuccessDelete(() => - expectClusterCallArgs({ refresh: 'wait_for' }, 2) + expect(client.delete).toHaveBeenCalledWith( + expect.objectContaining({ + refresh: 'wait_for', + }), + expect.anything() + ) ); }); - it(`accepts a custom refresh setting`, async () => { - const refresh = 'foo'; - const expectFn = () => expectClusterCallArgs({ refresh }, 2); - await deleteFromNamespacesSuccessDelete(expectFn, { refresh }); - }); - it(`should use default index`, async () => { - const expectFn = () => expectClusterCallArgs({ index: '.kibana-test' }, 2); + const expectFn = () => + expect(client.delete).toHaveBeenCalledWith( + expect.objectContaining({ index: '.kibana-test' }), + expect.anything() + ); await deleteFromNamespacesSuccessDelete(expectFn); }); it(`should use custom index`, async () => { - const expectFn = () => expectClusterCallArgs({ index: 'custom' }, 2); + const expectFn = () => + expect(client.delete).toHaveBeenCalledWith( + expect.objectContaining({ index: 'custom' }), + expect.anything() + ); await deleteFromNamespacesSuccessDelete(expectFn, {}, MULTI_NAMESPACE_CUSTOM_INDEX_TYPE); }); }); @@ -2708,55 +2876,73 @@ describe('SavedObjectsRepository', () => { const currentNamespaces = [namespace1].concat(remaining); await deleteFromNamespacesSuccess(_type, id, [namespace1], currentNamespaces, options); expectFn(); - callAdminCluster.mockReset(); + client.get.mockClear(); + client.update.mockClear(); }; await test([namespace2]); await test([namespace2, namespace3]); }; it(`should use ES get action then update action if the object has one or more namespaces remaining`, async () => { - await deleteFromNamespacesSuccessUpdate(() => expectClusterCalls('get', 'update')); + const expectFn = () => { + expect(client.update).toHaveBeenCalledTimes(1); + expect(client.get).toHaveBeenCalledTimes(1); + }; + await deleteFromNamespacesSuccessUpdate(expectFn); }); it(`formats the ES requests`, async () => { let ctr = 0; const expectFn = () => { - expectClusterCallArgs({ id: `${type}:${id}` }, 1); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${type}:${id}`, + }), + expect.anything() + ); const namespaces = ctr++ === 0 ? [namespace2] : [namespace2, namespace3]; const versionProperties = { if_seq_no: mockVersionProps._seq_no, if_primary_term: mockVersionProps._primary_term, }; - expectClusterCallArgs( - { + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ id: `${type}:${id}`, ...versionProperties, body: { doc: { ...mockTimestampFields, namespaces } }, - }, - 2 + }), + expect.anything() ); }; await deleteFromNamespacesSuccessUpdate(expectFn); }); it(`defaults to a refresh setting of wait_for`, async () => { - const expectFn = () => expectClusterCallArgs({ refresh: 'wait_for' }, 2); + const expectFn = () => + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + refresh: 'wait_for', + }), + expect.anything() + ); await deleteFromNamespacesSuccessUpdate(expectFn); }); - it(`accepts a custom refresh setting`, async () => { - const refresh = 'foo'; - const expectFn = () => expectClusterCallArgs({ refresh }, 2); - await deleteFromNamespacesSuccessUpdate(expectFn, { refresh }); - }); - it(`should use default index`, async () => { - const expectFn = () => expectClusterCallArgs({ index: '.kibana-test' }, 2); + const expectFn = () => + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ index: '.kibana-test' }), + expect.anything() + ); await deleteFromNamespacesSuccessUpdate(expectFn); }); it(`should use custom index`, async () => { - const expectFn = () => expectClusterCallArgs({ index: 'custom' }, 2); + const expectFn = () => + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ index: 'custom' }), + expect.anything() + ); await deleteFromNamespacesSuccessUpdate(expectFn, {}, MULTI_NAMESPACE_CUSTOM_INDEX_TYPE); }); }); @@ -2776,19 +2962,22 @@ describe('SavedObjectsRepository', () => { it(`throws when type is invalid`, async () => { await expectNotFoundError('unknownType', id, [namespace1, namespace2]); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.delete).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }); it(`throws when type is hidden`, async () => { await expectNotFoundError(HIDDEN_TYPE, id, [namespace1, namespace2]); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.delete).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }); it(`throws when type is not namespace-agnostic`, async () => { const test = async (type) => { const message = `${type} doesn't support multiple namespaces`; await expectBadRequestError(type, id, [namespace1, namespace2], message); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.delete).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }; await test('index-pattern'); await test(NAMESPACE_AGNOSTIC_TYPE); @@ -2798,71 +2987,78 @@ describe('SavedObjectsRepository', () => { const test = async (namespaces) => { const message = 'namespaces must be a non-empty array of strings'; await expectBadRequestError(type, id, namespaces, message); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.delete).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }; await test([]); }); it(`throws when ES is unable to find the document during get`, async () => { - callAdminCluster.mockResolvedValue({ found: false }); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ found: false }) + ); await expectNotFoundError(type, id, [namespace1, namespace2]); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the index during get`, async () => { - callAdminCluster.mockResolvedValue({ status: 404 }); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); await expectNotFoundError(type, id, [namespace1, namespace2]); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when the document exists, but not in this namespace`, async () => { - mockGetResponse(type, id, [namespace1]); // this._callCluster('get', ...) + mockGetResponse(type, id, [namespace1]); await expectNotFoundError(type, id, [namespace1], { namespace: 'some-other-namespace' }); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the document during delete`, async () => { - mockGetResponse(type, id, [namespace1]); // this._callCluster('get', ...) - callAdminCluster.mockResolvedValue({ result: 'not_found' }); // this._writeToCluster('delete', ...) + mockGetResponse(type, id, [namespace1]); + client.delete.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ result: 'not_found' }) + ); await expectNotFoundError(type, id, [namespace1]); - expectClusterCalls('get', 'delete'); + expect(client.get).toHaveBeenCalledTimes(1); + expect(client.delete).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the index during delete`, async () => { - mockGetResponse(type, id, [namespace1]); // this._callCluster('get', ...) - callAdminCluster.mockResolvedValue({ error: { type: 'index_not_found_exception' } }); // this._writeToCluster('delete', ...) + mockGetResponse(type, id, [namespace1]); + client.delete.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + error: { type: 'index_not_found_exception' }, + }) + ); await expectNotFoundError(type, id, [namespace1]); - expectClusterCalls('get', 'delete'); + expect(client.get).toHaveBeenCalledTimes(1); + expect(client.delete).toHaveBeenCalledTimes(1); }); it(`throws when ES returns an unexpected response`, async () => { - mockGetResponse(type, id, [namespace1]); // this._callCluster('get', ...) - callAdminCluster.mockResolvedValue({ result: 'something unexpected' }); // this._writeToCluster('delete', ...) + mockGetResponse(type, id, [namespace1]); + client.delete.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + result: 'something unexpected', + }) + ); await expect( savedObjectsRepository.deleteFromNamespaces(type, id, [namespace1]) ).rejects.toThrowError('Unexpected Elasticsearch DELETE response'); - expectClusterCalls('get', 'delete'); + expect(client.get).toHaveBeenCalledTimes(1); + expect(client.delete).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the document during update`, async () => { - mockGetResponse(type, id, [namespace1, namespace2]); // this._callCluster('get', ...) - callAdminCluster.mockResolvedValue({ status: 404 }); // this._writeToCluster('update', ...) - await expectNotFoundError(type, id, [namespace1]); - expectClusterCalls('get', 'update'); - }); - }); - - describe('migration', () => { - it(`waits until migrations are complete before proceeding`, async () => { - let callAdminClusterCount = 0; - migrator.runMigrations = jest.fn(async () => - // runMigrations should resolve before callAdminCluster is initiated - expect(callAdminCluster).toHaveBeenCalledTimes(callAdminClusterCount++) + mockGetResponse(type, id, [namespace1, namespace2]); + client.update.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) ); - await expect( - deleteFromNamespacesSuccess(type, id, [namespace1], [namespace1]) - ).resolves.toBeDefined(); - expect(migrator.runMigrations).toHaveReturnedTimes(2); + await expectNotFoundError(type, id, [namespace1]); + expect(client.get).toHaveBeenCalledTimes(1); + expect(client.update).toHaveBeenCalledTimes(1); }); }); @@ -2871,7 +3067,7 @@ describe('SavedObjectsRepository', () => { const test = async (namespaces) => { const result = await deleteFromNamespacesSuccess(type, id, namespaces, namespaces); expect(result).toEqual({}); - callAdminCluster.mockReset(); + client.delete.mockClear(); }; await test([namespace1]); await test([namespace1, namespace2]); @@ -2887,7 +3083,7 @@ describe('SavedObjectsRepository', () => { currentNamespaces ); expect(result).toEqual({}); - callAdminCluster.mockReset(); + client.delete.mockClear(); }; await test([namespace2]); await test([namespace2, namespace3]); @@ -2918,47 +3114,61 @@ describe('SavedObjectsRepository', () => { const updateSuccess = async (type, id, attributes, options) => { if (registry.isMultiNamespace(type)) { const mockGetResponse = getMockGetResponse({ type, id, namespace: options?.namespace }); - callAdminCluster.mockResolvedValueOnce(mockGetResponse); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(mockGetResponse) + ); } - callAdminCluster.mockResolvedValue({ - _id: `${type}:${id}`, - ...mockVersionProps, - result: 'updated', - // don't need the rest of the source for test purposes, just the namespace and namespaces attributes - get: { - _source: { namespaces: [options?.namespace ?? 'default'], namespace: options?.namespace }, - }, - }); // this._writeToCluster('update', ...) + client.update.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ + _id: `${type}:${id}`, + ...mockVersionProps, + result: 'updated', + // don't need the rest of the source for test purposes, just the namespace and namespaces attributes + get: { + _source: { + namespaces: [options?.namespace ?? 'default'], + namespace: options?.namespace, + }, + }, + }) + ); const result = await savedObjectsRepository.update(type, id, attributes, options); - expect(callAdminCluster).toHaveBeenCalledTimes(registry.isMultiNamespace(type) ? 2 : 1); + expect(client.get).toHaveBeenCalledTimes(registry.isMultiNamespace(type) ? 1 : 0); return result; }; - describe('cluster calls', () => { + describe('client calls', () => { it(`should use the ES get action then update action when type is multi-namespace`, async () => { await updateSuccess(MULTI_NAMESPACE_TYPE, id, attributes); - expectClusterCalls('get', 'update'); + expect(client.get).toHaveBeenCalledTimes(1); + expect(client.update).toHaveBeenCalledTimes(1); }); it(`should use the ES update action when type is not multi-namespace`, async () => { await updateSuccess(type, id, attributes); - expectClusterCalls('update'); + expect(client.update).toHaveBeenCalledTimes(1); }); it(`defaults to no references array`, async () => { await updateSuccess(type, id, attributes); - expectClusterCallArgs({ - body: { doc: expect.not.objectContaining({ references: expect.anything() }) }, - }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + body: { doc: expect.not.objectContaining({ references: expect.anything() }) }, + }), + expect.anything() + ); }); it(`accepts custom references array`, async () => { const test = async (references) => { await updateSuccess(type, id, attributes, { references }); - expectClusterCallArgs({ - body: { doc: expect.objectContaining({ references }) }, - }); - callAdminCluster.mockReset(); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + body: { doc: expect.objectContaining({ references }) }, + }), + expect.anything() + ); + client.update.mockClear(); }; await test(references); await test(['string']); @@ -2968,10 +3178,13 @@ describe('SavedObjectsRepository', () => { it(`doesn't accept custom references if not an array`, async () => { const test = async (references) => { await updateSuccess(type, id, attributes, { references }); - expectClusterCallArgs({ - body: { doc: expect.not.objectContaining({ references: expect.anything() }) }, - }); - callAdminCluster.mockReset(); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + body: { doc: expect.not.objectContaining({ references: expect.anything() }) }, + }), + expect.anything() + ); + client.update.mockClear(); }; await test('string'); await test(123); @@ -2981,13 +3194,12 @@ describe('SavedObjectsRepository', () => { it(`defaults to a refresh setting of wait_for`, async () => { await updateSuccess(type, id, { foo: 'bar' }); - expectClusterCallArgs({ refresh: 'wait_for' }); - }); - - it(`accepts a custom refresh setting`, async () => { - const refresh = 'foo'; - await updateSuccess(type, id, { foo: 'bar' }, { refresh }); - expectClusterCallArgs({ refresh }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + refresh: 'wait_for', + }), + expect.anything() + ); }); it(`defaults to the version of the existing document when type is multi-namespace`, async () => { @@ -2996,47 +3208,70 @@ describe('SavedObjectsRepository', () => { if_seq_no: mockVersionProps._seq_no, if_primary_term: mockVersionProps._primary_term, }; - expectClusterCallArgs(versionProperties, 2); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining(versionProperties), + expect.anything() + ); }); it(`accepts version`, async () => { await updateSuccess(type, id, attributes, { version: encodeHitVersion({ _seq_no: 100, _primary_term: 200 }), }); - expectClusterCallArgs({ if_seq_no: 100, if_primary_term: 200 }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ if_seq_no: 100, if_primary_term: 200 }), + expect.anything() + ); }); it(`prepends namespace to the id when providing namespace for single-namespace type`, async () => { await updateSuccess(type, id, attributes, { namespace }); - expectClusterCallArgs({ id: expect.stringMatching(`${namespace}:${type}:${id}`) }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ id: expect.stringMatching(`${namespace}:${type}:${id}`) }), + expect.anything() + ); }); it(`doesn't prepend namespace to the id when providing no namespace for single-namespace type`, async () => { await updateSuccess(type, id, attributes, { references }); - expectClusterCallArgs({ id: expect.stringMatching(`${type}:${id}`) }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ id: expect.stringMatching(`${type}:${id}`) }), + expect.anything() + ); }); it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { await updateSuccess(NAMESPACE_AGNOSTIC_TYPE, id, attributes, { namespace }); - expectClusterCallArgs({ id: expect.stringMatching(`${NAMESPACE_AGNOSTIC_TYPE}:${id}`) }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + id: expect.stringMatching(`${NAMESPACE_AGNOSTIC_TYPE}:${id}`), + }), + expect.anything() + ); - callAdminCluster.mockReset(); + client.update.mockClear(); await updateSuccess(MULTI_NAMESPACE_TYPE, id, attributes, { namespace }); - expectClusterCallArgs({ id: expect.stringMatching(`${MULTI_NAMESPACE_TYPE}:${id}`) }, 2); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ id: expect.stringMatching(`${MULTI_NAMESPACE_TYPE}:${id}`) }), + expect.anything() + ); }); - it(`includes _sourceIncludes when type is multi-namespace`, async () => { + it(`includes _source_includes when type is multi-namespace`, async () => { await updateSuccess(MULTI_NAMESPACE_TYPE, id, attributes); - expectClusterCallArgs({ _sourceIncludes: ['namespace', 'namespaces'] }, 2); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ _source_includes: ['namespace', 'namespaces'] }), + expect.anything() + ); }); - it(`includes _sourceIncludes when type is not multi-namespace`, async () => { + it(`includes _source_includes when type is not multi-namespace`, async () => { await updateSuccess(type, id, attributes); - expect(callAdminCluster).toHaveBeenLastCalledWith( - expect.any(String), + expect(client.update).toHaveBeenLastCalledWith( expect.objectContaining({ - _sourceIncludes: ['namespace', 'namespaces'], - }) + _source_includes: ['namespace', 'namespaces'], + }), + expect.anything() ); }); }); @@ -3050,49 +3285,45 @@ describe('SavedObjectsRepository', () => { it(`throws when type is invalid`, async () => { await expectNotFoundError('unknownType', id); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }); it(`throws when type is hidden`, async () => { await expectNotFoundError(HIDDEN_TYPE, id); - expect(callAdminCluster).not.toHaveBeenCalled(); + expect(client.update).not.toHaveBeenCalled(); }); it(`throws when ES is unable to find the document during get`, async () => { - callAdminCluster.mockResolvedValue({ found: false }); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ found: false }) + ); await expectNotFoundError(MULTI_NAMESPACE_TYPE, id); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the index during get`, async () => { - callAdminCluster.mockResolvedValue({ status: 404 }); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); await expectNotFoundError(MULTI_NAMESPACE_TYPE, id); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when type is multi-namespace and the document exists, but not in this namespace`, async () => { const response = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id, namespace }); - callAdminCluster.mockResolvedValue(response); // this._callCluster('get', ...) + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise(response) + ); await expectNotFoundError(MULTI_NAMESPACE_TYPE, id, { namespace: 'bar-namespace' }); - expectClusterCalls('get'); + expect(client.get).toHaveBeenCalledTimes(1); }); it(`throws when ES is unable to find the document during update`, async () => { - callAdminCluster.mockResolvedValue({ status: 404 }); // this._writeToCluster('update', ...) + client.update.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }) + ); await expectNotFoundError(type, id); - expectClusterCalls('update'); - }); - }); - - describe('migration', () => { - it(`waits until migrations are complete before proceeding`, async () => { - let callAdminClusterCount = 0; - migrator.runMigrations = jest.fn(async () => - // runMigrations should resolve before callAdminCluster is initiated - expect(callAdminCluster).toHaveBeenCalledTimes(callAdminClusterCount++) - ); - await expect(updateSuccess(type, id, attributes)).resolves.toBeDefined(); - expect(migrator.runMigrations).toHaveReturnedTimes(1); + expect(client.update).toHaveBeenCalledTimes(1); }); }); diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index 7a5ac9204627c..8b7b1d62c1b7d 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -19,13 +19,16 @@ import { omit } from 'lodash'; import uuid from 'uuid'; -import { retryCallCluster } from '../../../elasticsearch/legacy'; -import { LegacyAPICaller } from '../../../elasticsearch/'; - +import { + ElasticsearchClient, + DeleteDocumentResponse, + GetResponse, + SearchResponse, +} from '../../../elasticsearch/'; import { getRootPropertiesObjects, IndexMapping } from '../../mappings'; +import { createRepositoryEsClient, RepositoryEsClient } from './repository_es_client'; import { getSearchDsl } from './search_dsl'; import { includedFields } from './included_fields'; -import { decorateEsError } from './decorate_es_error'; import { SavedObjectsErrorHelpers } from './errors'; import { decodeRequestVersion, encodeVersion, encodeHitVersion } from '../../version'; import { KibanaMigrator } from '../../migrations'; @@ -33,6 +36,7 @@ import { SavedObjectsSerializer, SavedObjectSanitizedDoc, SavedObjectsRawDoc, + SavedObjectsRawDocSource, } from '../../serialization'; import { SavedObjectsBulkCreateObject, @@ -74,7 +78,7 @@ const isRight = (either: Either): either is Right => either.tag === 'Right'; export interface SavedObjectsRepositoryOptions { index: string; mappings: IndexMapping; - callCluster: LegacyAPICaller; + client: ElasticsearchClient; typeRegistry: SavedObjectTypeRegistry; serializer: SavedObjectsSerializer; migrator: KibanaMigrator; @@ -95,8 +99,8 @@ export interface SavedObjectsIncrementCounterOptions extends SavedObjectsBaseOpt * @public */ export interface SavedObjectsDeleteByNamespaceOptions extends SavedObjectsBaseOptions { - /** The Elasticsearch Refresh setting for this operation */ - refresh?: MutatingOperationRefreshSetting; + /** The Elasticsearch supports only boolean flag for this operation */ + refresh?: boolean; } const DEFAULT_REFRESH_SETTING = 'wait_for'; @@ -117,7 +121,7 @@ export class SavedObjectsRepository { private _mappings: IndexMapping; private _registry: SavedObjectTypeRegistry; private _allowedTypes: string[]; - private _unwrappedCallCluster: LegacyAPICaller; + private readonly client: RepositoryEsClient; private _serializer: SavedObjectsSerializer; /** @@ -132,7 +136,7 @@ export class SavedObjectsRepository { migrator: KibanaMigrator, typeRegistry: SavedObjectTypeRegistry, indexName: string, - callCluster: LegacyAPICaller, + client: ElasticsearchClient, includedHiddenTypes: string[] = [], injectedConstructor: any = SavedObjectsRepository ): ISavedObjectsRepository { @@ -157,7 +161,7 @@ export class SavedObjectsRepository { typeRegistry, serializer, allowedTypes, - callCluster: retryCallCluster(callCluster), + client, }); } @@ -165,7 +169,7 @@ export class SavedObjectsRepository { const { index, mappings, - callCluster, + client, typeRegistry, serializer, migrator, @@ -183,15 +187,11 @@ export class SavedObjectsRepository { this._index = index; this._mappings = mappings; this._registry = typeRegistry; + this.client = createRepositoryEsClient(client); if (allowedTypes.length === 0) { throw new Error('Empty or missing types for saved object repository!'); } this._allowedTypes = allowedTypes; - - this._unwrappedCallCluster = async (...args: Parameters) => { - await migrator.runMigrations(); - return callCluster(...args); - }; this._serializer = serializer; } @@ -254,17 +254,21 @@ export class SavedObjectsRepository { const raw = this._serializer.savedObjectToRaw(migrated as SavedObjectSanitizedDoc); - const method = id && overwrite ? 'index' : 'create'; - const response = await this._writeToCluster(method, { + const requestParams = { id: raw._id, index: this.getIndexForType(type), refresh, body: raw._source, - }); + }; + + const { body } = + id && overwrite + ? await this.client.index(requestParams) + : await this.client.create(requestParams); return this._rawToSavedObject({ ...raw, - ...response, + ...body, }); } @@ -322,12 +326,14 @@ export class SavedObjectsRepository { _source: ['type', 'namespaces'], })); const bulkGetResponse = bulkGetDocs.length - ? await this._callCluster('mget', { - body: { - docs: bulkGetDocs, + ? await this.client.mget( + { + body: { + docs: bulkGetDocs, + }, }, - ignore: [404], - }) + { ignore: [404] } + ) : undefined; let bulkRequestIndexCounter = 0; @@ -341,8 +347,8 @@ export class SavedObjectsRepository { let savedObjectNamespaces; const { esRequestIndex, object, method } = expectedBulkGetResult.value; if (esRequestIndex !== undefined) { - const indexFound = bulkGetResponse.status !== 404; - const actualResult = indexFound ? bulkGetResponse.docs[esRequestIndex] : undefined; + const indexFound = bulkGetResponse?.statusCode !== 404; + const actualResult = indexFound ? bulkGetResponse?.body.docs[esRequestIndex] : undefined; const docFound = indexFound && actualResult.found === true; if (docFound && !this.rawDocExistsInNamespace(actualResult, namespace)) { const { id, type } = object; @@ -395,7 +401,7 @@ export class SavedObjectsRepository { }); const bulkResponse = bulkCreateParams.length - ? await this._writeToCluster('bulk', { + ? await this.client.bulk({ refresh, body: bulkCreateParams, }) @@ -409,7 +415,7 @@ export class SavedObjectsRepository { const { requestedId, rawMigratedDoc, esRequestIndex } = expectedResult.value; const { error, ...rawResponse } = Object.values( - bulkResponse.items[esRequestIndex] + bulkResponse?.body.items[esRequestIndex] )[0] as any; if (error) { @@ -466,18 +472,20 @@ export class SavedObjectsRepository { namespaces: remainingNamespaces, }; - const updateResponse = await this._writeToCluster('update', { - id: rawId, - index: this.getIndexForType(type), - ...getExpectedVersionProperties(undefined, preflightResult), - refresh, - ignore: [404], - body: { - doc, + const { statusCode } = await this.client.update( + { + id: rawId, + index: this.getIndexForType(type), + ...getExpectedVersionProperties(undefined, preflightResult), + refresh, + body: { + doc, + }, }, - }); + { ignore: [404] } + ); - if (updateResponse.status === 404) { + if (statusCode === 404) { // see "404s from missing index" above throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } @@ -485,22 +493,23 @@ export class SavedObjectsRepository { } } - const deleteResponse = await this._writeToCluster('delete', { - id: rawId, - index: this.getIndexForType(type), - ...getExpectedVersionProperties(undefined, preflightResult), - refresh, - ignore: [404], - }); + const { body, statusCode } = await this.client.delete( + { + id: rawId, + index: this.getIndexForType(type), + ...getExpectedVersionProperties(undefined, preflightResult), + refresh, + }, + { ignore: [404] } + ); - const deleted = deleteResponse.result === 'deleted'; + const deleted = body.result === 'deleted'; if (deleted) { return {}; } - const deleteDocNotFound = deleteResponse.result === 'not_found'; - const deleteIndexNotFound = - deleteResponse.error && deleteResponse.error.type === 'index_not_found_exception'; + const deleteDocNotFound = body.result === 'not_found'; + const deleteIndexNotFound = body.error && body.error.type === 'index_not_found_exception'; if (deleteDocNotFound || deleteIndexNotFound) { // see "404s from missing index" above throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); @@ -510,7 +519,7 @@ export class SavedObjectsRepository { `Unexpected Elasticsearch DELETE response: ${JSON.stringify({ type, id, - response: deleteResponse, + response: { body, statusCode }, })}` ); } @@ -529,17 +538,16 @@ export class SavedObjectsRepository { throw new TypeError(`namespace is required, and must be a string`); } - const { refresh = DEFAULT_REFRESH_SETTING } = options; const allTypes = Object.keys(getRootPropertiesObjects(this._mappings)); const typesToUpdate = allTypes.filter((type) => !this._registry.isNamespaceAgnostic(type)); - const updateOptions = { - index: this.getIndicesForTypes(typesToUpdate), - ignore: [404], - refresh, - body: { - script: { - source: ` + const { body } = await this.client.updateByQuery( + { + index: this.getIndicesForTypes(typesToUpdate), + refresh: options.refresh, + body: { + script: { + source: ` if (!ctx._source.containsKey('namespaces')) { ctx.op = "delete"; } else { @@ -549,18 +557,20 @@ export class SavedObjectsRepository { } } `, - lang: 'painless', - params: { namespace: getNamespaceString(namespace) }, + lang: 'painless', + params: { namespace: getNamespaceString(namespace) }, + }, + conflicts: 'proceed', + ...getSearchDsl(this._mappings, this._registry, { + namespaces: namespace ? [namespace] : undefined, + type: typesToUpdate, + }), }, - conflicts: 'proceed', - ...getSearchDsl(this._mappings, this._registry, { - namespaces: namespace ? [namespace] : undefined, - type: typesToUpdate, - }), }, - }; + { ignore: [404] } + ); - return await this._writeToCluster('updateByQuery', updateOptions); + return body; } /** @@ -639,7 +649,6 @@ export class SavedObjectsRepository { size: perPage, from: perPage * (page - 1), _source: includedFields(type, fields), - ignore: [404], rest_total_hits_as_int: true, preference, body: { @@ -658,9 +667,10 @@ export class SavedObjectsRepository { }, }; - const response = await this._callCluster('search', esOptions); - - if (response.status === 404) { + const { body, statusCode } = await this.client.search>(esOptions, { + ignore: [404], + }); + if (statusCode === 404) { // 404 is only possible here if the index is missing, which // we don't want to leak, see "404s from missing index" above return { @@ -674,14 +684,14 @@ export class SavedObjectsRepository { return { page, per_page: perPage, - total: response.hits.total, - saved_objects: response.hits.hits.map( + total: body.hits.total, + saved_objects: body.hits.hits.map( (hit: SavedObjectsRawDoc): SavedObjectsFindResult => ({ ...this._rawToSavedObject(hit), score: (hit as any)._score, }) ), - }; + } as SavedObjectsFindResponse; } /** @@ -742,12 +752,14 @@ export class SavedObjectsRepository { _source: includedFields(type, fields), })); const bulkGetResponse = bulkGetDocs.length - ? await this._callCluster('mget', { - body: { - docs: bulkGetDocs, + ? await this.client.mget( + { + body: { + docs: bulkGetDocs, + }, }, - ignore: [404], - }) + { ignore: [404] } + ) : undefined; return { @@ -757,7 +769,7 @@ export class SavedObjectsRepository { } const { type, id, esRequestIndex } = expectedResult.value; - const doc = bulkGetResponse.docs[esRequestIndex]; + const doc = bulkGetResponse?.body.docs[esRequestIndex]; if (!doc.found || !this.rawDocExistsInNamespace(doc, namespace)) { return ({ @@ -808,24 +820,26 @@ export class SavedObjectsRepository { const { namespace } = options; - const response = await this._callCluster('get', { - id: this._serializer.generateRawId(namespace, type, id), - index: this.getIndexForType(type), - ignore: [404], - }); + const { body, statusCode } = await this.client.get>( + { + id: this._serializer.generateRawId(namespace, type, id), + index: this.getIndexForType(type), + }, + { ignore: [404] } + ); - const docNotFound = response.found === false; - const indexNotFound = response.status === 404; - if (docNotFound || indexNotFound || !this.rawDocExistsInNamespace(response, namespace)) { + const docNotFound = body.found === false; + const indexNotFound = statusCode === 404; + if (docNotFound || indexNotFound || !this.rawDocExistsInNamespace(body, namespace)) { // see "404s from missing index" above throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } - const { updated_at: updatedAt } = response._source; + const { updated_at: updatedAt } = body._source; - let namespaces = []; + let namespaces: string[] = []; if (!this._registry.isNamespaceAgnostic(type)) { - namespaces = response._source.namespaces ?? [getNamespaceString(response._source.namespace)]; + namespaces = body._source.namespaces ?? [getNamespaceString(body._source.namespace)]; } return { @@ -833,10 +847,10 @@ export class SavedObjectsRepository { type, namespaces, ...(updatedAt && { updated_at: updatedAt }), - version: encodeHitVersion(response), - attributes: response._source[type], - references: response._source.references || [], - migrationVersion: response._source.migrationVersion, + version: encodeHitVersion(body), + attributes: body._source[type], + references: body._source.references || [], + migrationVersion: body._source.migrationVersion, }; } @@ -876,35 +890,37 @@ export class SavedObjectsRepository { ...(Array.isArray(references) && { references }), }; - const updateResponse = await this._writeToCluster('update', { - id: this._serializer.generateRawId(namespace, type, id), - index: this.getIndexForType(type), - ...getExpectedVersionProperties(version, preflightResult), - refresh, - ignore: [404], - body: { - doc, + const { body, statusCode } = await this.client.update( + { + id: this._serializer.generateRawId(namespace, type, id), + index: this.getIndexForType(type), + ...getExpectedVersionProperties(version, preflightResult), + refresh, + + body: { + doc, + }, + _source_includes: ['namespace', 'namespaces'], }, - _sourceIncludes: ['namespace', 'namespaces'], - }); + { ignore: [404] } + ); - if (updateResponse.status === 404) { + if (statusCode === 404) { // see "404s from missing index" above throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } let namespaces = []; if (!this._registry.isNamespaceAgnostic(type)) { - namespaces = updateResponse.get._source.namespaces ?? [ - getNamespaceString(updateResponse.get._source.namespace), - ]; + namespaces = body.get._source.namespaces ?? [getNamespaceString(body.get._source.namespace)]; } return { id, type, updated_at: time, - version: encodeHitVersion(updateResponse), + // @ts-expect-error update doesn't have _seq_no, _primary_term as Record / any in LP + version: encodeHitVersion(body), namespaces, references, attributes, @@ -952,18 +968,20 @@ export class SavedObjectsRepository { namespaces: existingNamespaces ? unique(existingNamespaces.concat(namespaces)) : namespaces, }; - const updateResponse = await this._writeToCluster('update', { - id: rawId, - index: this.getIndexForType(type), - ...getExpectedVersionProperties(version, preflightResult), - refresh, - ignore: [404], - body: { - doc, + const { statusCode } = await this.client.update( + { + id: rawId, + index: this.getIndexForType(type), + ...getExpectedVersionProperties(version, preflightResult), + refresh, + body: { + doc, + }, }, - }); + { ignore: [404] } + ); - if (updateResponse.status === 404) { + if (statusCode === 404) { // see "404s from missing index" above throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } @@ -1015,40 +1033,48 @@ export class SavedObjectsRepository { namespaces: remainingNamespaces, }; - const updateResponse = await this._writeToCluster('update', { - id: rawId, - index: this.getIndexForType(type), - ...getExpectedVersionProperties(undefined, preflightResult), - refresh, - ignore: [404], - body: { - doc, + const { statusCode } = await this.client.update( + { + id: rawId, + index: this.getIndexForType(type), + ...getExpectedVersionProperties(undefined, preflightResult), + refresh, + + body: { + doc, + }, }, - }); + { + ignore: [404], + } + ); - if (updateResponse.status === 404) { + if (statusCode === 404) { // see "404s from missing index" above throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } return {}; } else { // if there are no namespaces remaining, delete the saved object - const deleteResponse = await this._writeToCluster('delete', { - id: this._serializer.generateRawId(undefined, type, id), - index: this.getIndexForType(type), - ...getExpectedVersionProperties(undefined, preflightResult), - refresh, - ignore: [404], - }); + const { body, statusCode } = await this.client.delete( + { + id: this._serializer.generateRawId(undefined, type, id), + refresh, + ...getExpectedVersionProperties(undefined, preflightResult), + index: this.getIndexForType(type), + }, + { + ignore: [404], + } + ); - const deleted = deleteResponse.result === 'deleted'; + const deleted = body.result === 'deleted'; if (deleted) { return {}; } - const deleteDocNotFound = deleteResponse.result === 'not_found'; - const deleteIndexNotFound = - deleteResponse.error && deleteResponse.error.type === 'index_not_found_exception'; + const deleteDocNotFound = body.result === 'not_found'; + const deleteIndexNotFound = body.error && body.error.type === 'index_not_found_exception'; if (deleteDocNotFound || deleteIndexNotFound) { // see "404s from missing index" above throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); @@ -1058,7 +1084,7 @@ export class SavedObjectsRepository { `Unexpected Elasticsearch DELETE response: ${JSON.stringify({ type, id, - response: deleteResponse, + response: { body, statusCode }, })}` ); } @@ -1125,12 +1151,16 @@ export class SavedObjectsRepository { _source: ['type', 'namespaces'], })); const bulkGetResponse = bulkGetDocs.length - ? await this._callCluster('mget', { - body: { - docs: bulkGetDocs, + ? await this.client.mget( + { + body: { + docs: bulkGetDocs, + }, }, - ignore: [404], - }) + { + ignore: [404], + } + ) : undefined; let bulkUpdateRequestIndexCounter = 0; @@ -1145,8 +1175,8 @@ export class SavedObjectsRepository { let namespaces; let versionProperties; if (esRequestIndex !== undefined) { - const indexFound = bulkGetResponse.status !== 404; - const actualResult = indexFound ? bulkGetResponse.docs[esRequestIndex] : undefined; + const indexFound = bulkGetResponse?.statusCode !== 404; + const actualResult = indexFound ? bulkGetResponse?.body.docs[esRequestIndex] : undefined; const docFound = indexFound && actualResult.found === true; if (!docFound || !this.rawDocExistsInNamespace(actualResult, namespace)) { return { @@ -1194,11 +1224,11 @@ export class SavedObjectsRepository { const { refresh = DEFAULT_REFRESH_SETTING } = options; const bulkUpdateResponse = bulkUpdateParams.length - ? await this._writeToCluster('bulk', { + ? await this.client.bulk({ refresh, body: bulkUpdateParams, }) - : {}; + : undefined; return { saved_objects: expectedBulkUpdateResults.map((expectedResult) => { @@ -1207,7 +1237,7 @@ export class SavedObjectsRepository { } const { type, id, namespaces, documentToSave, esRequestIndex } = expectedResult.value; - const response = bulkUpdateResponse.items[esRequestIndex]; + const response = bulkUpdateResponse?.body.items[esRequestIndex]; const { error, _seq_no: seqNo, _primary_term: primaryTerm } = Object.values( response )[0] as any; @@ -1283,11 +1313,11 @@ export class SavedObjectsRepository { const raw = this._serializer.savedObjectToRaw(migrated as SavedObjectSanitizedDoc); - const response = await this._writeToCluster('update', { + const { body } = await this.client.update({ id: raw._id, index: this.getIndexForType(type), refresh, - _source: true, + _source: 'true', body: { script: { source: ` @@ -1315,28 +1345,13 @@ export class SavedObjectsRepository { id, type, updated_at: time, - references: response.get._source.references, - version: encodeHitVersion(response), - attributes: response.get._source[type], + references: body.get._source.references, + // @ts-expect-error + version: encodeHitVersion(body), + attributes: body.get._source[type], }; } - private async _writeToCluster(...args: Parameters) { - try { - return await this._callCluster(...args); - } catch (err) { - throw decorateEsError(err); - } - } - - private async _callCluster(...args: Parameters) { - try { - return await this._unwrappedCallCluster(...args); - } catch (err) { - throw decorateEsError(err); - } - } - /** * Returns index specified by the given type or the default index * @@ -1408,19 +1423,23 @@ export class SavedObjectsRepository { throw new Error(`Cannot make preflight get request for non-multi-namespace type '${type}'.`); } - const response = await this._callCluster('get', { - id: this._serializer.generateRawId(undefined, type, id), - index: this.getIndexForType(type), - ignore: [404], - }); + const { body, statusCode } = await this.client.get>( + { + id: this._serializer.generateRawId(undefined, type, id), + index: this.getIndexForType(type), + }, + { + ignore: [404], + } + ); - const indexFound = response.status !== 404; - const docFound = indexFound && response.found === true; + const indexFound = statusCode !== 404; + const docFound = indexFound && body.found === true; if (docFound) { - if (!this.rawDocExistsInNamespace(response, namespace)) { + if (!this.rawDocExistsInNamespace(body, namespace)) { throw SavedObjectsErrorHelpers.createConflictError(type, id); } - return getSavedObjectNamespaces(namespace, response); + return getSavedObjectNamespaces(namespace, body); } return getSavedObjectNamespaces(namespace); } @@ -1441,18 +1460,20 @@ export class SavedObjectsRepository { } const rawId = this._serializer.generateRawId(undefined, type, id); - const response = await this._callCluster('get', { - id: rawId, - index: this.getIndexForType(type), - ignore: [404], - }); + const { body, statusCode } = await this.client.get>( + { + id: rawId, + index: this.getIndexForType(type), + }, + { ignore: [404] } + ); - const indexFound = response.status !== 404; - const docFound = indexFound && response.found === true; - if (!docFound || !this.rawDocExistsInNamespace(response, namespace)) { + const indexFound = statusCode !== 404; + const docFound = indexFound && body.found === true; + if (!docFound || !this.rawDocExistsInNamespace(body, namespace)) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } - return response as SavedObjectsRawDoc; + return body as SavedObjectsRawDoc; } } diff --git a/packages/kbn-plugin-helpers/src/tasks/test/all/test_all_task.ts b/src/core/server/saved_objects/service/lib/repository_es_client.test.mock.ts similarity index 81% rename from packages/kbn-plugin-helpers/src/tasks/test/all/test_all_task.ts rename to src/core/server/saved_objects/service/lib/repository_es_client.test.mock.ts index d07c19291d2cb..3dcf82dae5e46 100644 --- a/packages/kbn-plugin-helpers/src/tasks/test/all/test_all_task.ts +++ b/src/core/server/saved_objects/service/lib/repository_es_client.test.mock.ts @@ -16,10 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import { TaskContext } from '../../../lib'; - -export function testAllTask({ run }: TaskContext) { - run('testMocha'); - run('testKarma'); -} +export const retryCallClusterMock = jest.fn((fn) => fn()); +jest.doMock('../../../elasticsearch/client/retry_call_cluster', () => ({ + retryCallCluster: retryCallClusterMock, +})); diff --git a/src/core/server/saved_objects/service/lib/repository_es_client.test.ts b/src/core/server/saved_objects/service/lib/repository_es_client.test.ts new file mode 100644 index 0000000000000..86a984fb67124 --- /dev/null +++ b/src/core/server/saved_objects/service/lib/repository_es_client.test.ts @@ -0,0 +1,64 @@ +/* + * 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 { retryCallClusterMock } from './repository_es_client.test.mock'; + +import { createRepositoryEsClient, RepositoryEsClient } from './repository_es_client'; +import { elasticsearchClientMock } from '../../../elasticsearch/client/mocks'; +import { SavedObjectsErrorHelpers } from './errors'; + +describe('RepositoryEsClient', () => { + let client: ReturnType; + let repositoryClient: RepositoryEsClient; + + beforeEach(() => { + client = elasticsearchClientMock.createElasticSearchClient(); + repositoryClient = createRepositoryEsClient(client); + retryCallClusterMock.mockClear(); + }); + + it('delegates call to ES client method', async () => { + expect(repositoryClient.bulk).toStrictEqual(expect.any(Function)); + await repositoryClient.bulk({ body: [] }); + expect(client.bulk).toHaveBeenCalledTimes(1); + }); + + it('wraps a method call in retryCallCluster', async () => { + await repositoryClient.bulk({ body: [] }); + expect(retryCallClusterMock).toHaveBeenCalledTimes(1); + }); + + it('sets maxRetries: 0 to delegate retry logic to retryCallCluster', async () => { + expect(repositoryClient.bulk).toStrictEqual(expect.any(Function)); + await repositoryClient.bulk({ body: [] }); + expect(client.bulk).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ maxRetries: 0 }) + ); + }); + + it('transform elasticsearch errors into saved objects errors', async () => { + expect.assertions(1); + client.bulk = jest.fn().mockRejectedValue(new Error('reason')); + try { + await repositoryClient.bulk({ body: [] }); + } catch (e) { + expect(SavedObjectsErrorHelpers.isSavedObjectsClientError(e)).toBe(true); + } + }); +}); diff --git a/src/core/server/saved_objects/service/lib/repository_es_client.ts b/src/core/server/saved_objects/service/lib/repository_es_client.ts new file mode 100644 index 0000000000000..0a759669b1af8 --- /dev/null +++ b/src/core/server/saved_objects/service/lib/repository_es_client.ts @@ -0,0 +1,56 @@ +/* + * 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 type { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport'; + +import { ElasticsearchClient } from '../../../elasticsearch/'; +import { retryCallCluster } from '../../../elasticsearch/client/retry_call_cluster'; +import { decorateEsError } from './decorate_es_error'; + +const methods = [ + 'bulk', + 'create', + 'delete', + 'get', + 'index', + 'mget', + 'search', + 'update', + 'updateByQuery', +] as const; + +type MethodName = typeof methods[number]; + +export type RepositoryEsClient = Pick; + +export function createRepositoryEsClient(client: ElasticsearchClient): RepositoryEsClient { + return methods.reduce((acc: RepositoryEsClient, key: MethodName) => { + Object.defineProperty(acc, key, { + value: async (params?: unknown, options?: TransportRequestOptions) => { + try { + return await retryCallCluster(() => + (client[key] as Function)(params, { maxRetries: 0, ...options }) + ); + } catch (e) { + throw decorateEsError(e); + } + }, + }); + return acc; + }, {} as RepositoryEsClient); +} diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index 4b6bcbc8ad7a0..c94151f8cee17 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -45,7 +45,7 @@ import { ExplainParams } from 'elasticsearch'; import { FieldStatsParams } from 'elasticsearch'; import { GenericParams } from 'elasticsearch'; import { GetParams } from 'elasticsearch'; -import { GetResponse } from 'elasticsearch'; +import { GetResponse as GetResponse_2 } from 'elasticsearch'; import { GetScriptParams } from 'elasticsearch'; import { GetSourceParams } from 'elasticsearch'; import { GetTemplateParams } from 'elasticsearch'; @@ -121,7 +121,7 @@ import { ResponseToolkit } from 'hapi'; import { SchemaTypeError } from '@kbn/config-schema'; import { ScrollParams } from 'elasticsearch'; import { SearchParams } from 'elasticsearch'; -import { SearchResponse } from 'elasticsearch'; +import { SearchResponse as SearchResponse_2 } from 'elasticsearch'; import { SearchShardsParams } from 'elasticsearch'; import { SearchTemplateParams } from 'elasticsearch'; import { Server } from 'hapi'; @@ -532,6 +532,14 @@ export interface CoreStatus { savedObjects: ServiceStatus; } +// @public (undocumented) +export interface CountResponse { + // (undocumented) + count: number; + // (undocumented) + _shards: ShardsInfo; +} + // @public export class CspConfig implements ICspConfig { // @internal @@ -592,6 +600,28 @@ export const DEFAULT_APP_CATEGORIES: Readonly<{ }; }>; +// @public (undocumented) +export interface DeleteDocumentResponse { + // (undocumented) + error?: { + type: string; + }; + // (undocumented) + found: boolean; + // (undocumented) + _id: string; + // (undocumented) + _index: string; + // (undocumented) + result: string; + // (undocumented) + _shards: ShardsResponse; + // (undocumented) + _type: string; + // (undocumented) + _version: number; +} + // @public (undocumented) export interface DeprecationAPIClientParams extends GenericParams { // (undocumented) @@ -642,6 +672,13 @@ export interface DiscoveredPlugin { readonly requiredPlugins: readonly PluginName[]; } +// @public +export type ElasticsearchClient = Omit & { + transport: { + request(params: TransportRequestParams, options?: TransportRequestOptions): TransportRequestPromise; + }; +}; + // @public export class ElasticsearchConfig { constructor(rawConfig: ElasticsearchConfigType); @@ -709,6 +746,16 @@ export interface ErrorHttpResponseOptions { headers?: ResponseHeaders; } +// @public (undocumented) +export interface Explanation { + // (undocumented) + description: string; + // (undocumented) + details: Explanation[]; + // (undocumented) + value: number; +} + // @public export function exportSavedObjectsToStream({ types, objects, search, savedObjectsClient, exportSizeLimit, includeReferencesDeep, excludeExportDetails, namespace, }: SavedObjectsExportOptions): Promise; @@ -736,6 +783,28 @@ export function getFlattenedObject(rootValue: Record): { [key: string]: any; }; +// @public (undocumented) +export interface GetResponse { + // (undocumented) + found: boolean; + // (undocumented) + _id: string; + // (undocumented) + _index: string; + // (undocumented) + _primary_term: number; + // (undocumented) + _routing?: string; + // (undocumented) + _seq_no: number; + // (undocumented) + _source: T; + // (undocumented) + _type: string; + // (undocumented) + _version: number; +} + // @public export type HandlerContextType> = T extends HandlerFunction ? U : never; @@ -1042,7 +1111,7 @@ export interface LegacyAPICaller { // (undocumented) (endpoint: 'fieldStats', params: FieldStatsParams, options?: LegacyCallAPIOptions): ReturnType; // (undocumented) - (endpoint: 'get', params: GetParams, options?: LegacyCallAPIOptions): Promise>; + (endpoint: 'get', params: GetParams, options?: LegacyCallAPIOptions): Promise>; // (undocumented) (endpoint: 'getScript', params: GetScriptParams, options?: LegacyCallAPIOptions): ReturnType; // (undocumented) @@ -1074,9 +1143,9 @@ export interface LegacyAPICaller { // (undocumented) (endpoint: 'renderSearchTemplate', params: RenderSearchTemplateParams, options?: LegacyCallAPIOptions): ReturnType; // (undocumented) - (endpoint: 'scroll', params: ScrollParams, options?: LegacyCallAPIOptions): Promise>; + (endpoint: 'scroll', params: ScrollParams, options?: LegacyCallAPIOptions): Promise>; // (undocumented) - (endpoint: 'search', params: SearchParams, options?: LegacyCallAPIOptions): Promise>; + (endpoint: 'search', params: SearchParams, options?: LegacyCallAPIOptions): Promise>; // (undocumented) (endpoint: 'searchShards', params: SearchShardsParams, options?: LegacyCallAPIOptions): ReturnType; // (undocumented) @@ -1790,6 +1859,7 @@ export interface RouteConfigOptions { authRequired?: boolean | 'optional'; body?: Method extends 'get' | 'options' ? undefined : RouteConfigOptionsBody; tags?: readonly string[]; + timeout?: number; xsrfRequired?: Method extends 'get' ? never : boolean; } @@ -2082,7 +2152,7 @@ export interface SavedObjectsCreateOptions extends SavedObjectsBaseOptions { // @public (undocumented) export interface SavedObjectsDeleteByNamespaceOptions extends SavedObjectsBaseOptions { - refresh?: MutatingOperationRefreshSetting; + refresh?: boolean; } // @public (undocumented) @@ -2396,7 +2466,7 @@ export class SavedObjectsRepository { // Warning: (ae-forgotten-export) The symbol "KibanaMigrator" needs to be exported by the entry point index.d.ts // // @internal - static createRepository(migrator: KibanaMigrator, typeRegistry: SavedObjectTypeRegistry, indexName: string, callCluster: LegacyAPICaller, includedHiddenTypes?: string[], injectedConstructor?: any): ISavedObjectsRepository; + static createRepository(migrator: KibanaMigrator, typeRegistry: SavedObjectTypeRegistry, indexName: string, client: ElasticsearchClient, includedHiddenTypes?: string[], injectedConstructor?: any): ISavedObjectsRepository; delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>; deleteByNamespace(namespace: string, options?: SavedObjectsDeleteByNamespaceOptions): Promise; deleteFromNamespaces(type: string, id: string, namespaces: string[], options?: SavedObjectsDeleteFromNamespacesOptions): Promise<{}>; @@ -2412,7 +2482,7 @@ export class SavedObjectsRepository { attributes: any; }>; update(type: string, id: string, attributes: Partial, options?: SavedObjectsUpdateOptions): Promise>; - } +} // @public export interface SavedObjectsRepositoryFactory { @@ -2552,6 +2622,39 @@ export type SavedObjectUnsanitizedDoc = SavedObjectDoc & Partial // @public export type ScopeableRequest = KibanaRequest | LegacyRequest | FakeRequest; +// @public (undocumented) +export interface SearchResponse { + // (undocumented) + aggregations?: any; + // (undocumented) + hits: { + total: number; + max_score: number; + hits: Array<{ + _index: string; + _type: string; + _id: string; + _score: number; + _source: T; + _version?: number; + _explanation?: Explanation; + fields?: any; + highlight?: any; + inner_hits?: any; + matched_queries?: string[]; + sort?: string[]; + }>; + }; + // (undocumented) + _scroll_id?: string; + // (undocumented) + _shards: ShardsResponse; + // (undocumented) + timed_out: boolean; + // (undocumented) + took: number; +} + // @public export interface ServiceStatus | unknown = unknown> { detail?: string; @@ -2612,6 +2715,30 @@ export interface SessionStorageFactory { asScoped: (request: KibanaRequest) => SessionStorage; } +// @public (undocumented) +export interface ShardsInfo { + // (undocumented) + failed: number; + // (undocumented) + skipped: number; + // (undocumented) + successful: number; + // (undocumented) + total: number; +} + +// @public (undocumented) +export interface ShardsResponse { + // (undocumented) + failed: number; + // (undocumented) + skipped: number; + // (undocumented) + successful: number; + // (undocumented) + total: number; +} + // @public (undocumented) export type SharedGlobalConfig = RecursiveReadonly<{ kibana: Pick; diff --git a/src/core/server/server.ts b/src/core/server/server.ts index 86b8c550b2d9b..2dae7f8f38f23 100644 --- a/src/core/server/server.ts +++ b/src/core/server/server.ts @@ -17,15 +17,7 @@ * under the License. */ -import { Type } from '@kbn/config-schema'; - -import { - ConfigService, - Env, - ConfigPath, - RawConfigurationProvider, - coreDeprecationProvider, -} from './config'; +import { ConfigService, Env, RawConfigurationProvider, coreDeprecationProvider } from './config'; import { CoreApp } from './core_app'; import { AuditTrailService } from './audit_trail'; import { ElasticsearchService } from './elasticsearch'; @@ -51,10 +43,11 @@ import { config as pathConfig } from './path'; import { config as kibanaConfig } from './kibana_config'; import { savedObjectsConfig, savedObjectsMigrationConfig } from './saved_objects'; import { config as uiSettingsConfig } from './ui_settings'; +import { config as statusConfig } from './status'; import { mapToObject } from '../utils'; import { ContextService } from './context'; import { RequestHandlerContext } from '.'; -import { InternalCoreSetup, InternalCoreStart } from './internal_types'; +import { InternalCoreSetup, InternalCoreStart, ServiceConfigDescriptor } from './internal_types'; const coreId = Symbol('core'); const rootConfigPath = ''; @@ -156,8 +149,14 @@ export class Server { await this.metrics.setup({ http: httpSetup }); + const statusSetup = await this.status.setup({ + elasticsearch: elasticsearchServiceSetup, + savedObjects: savedObjectsSetup, + }); + const renderingSetup = await this.rendering.setup({ http: httpSetup, + status: statusSetup, legacyPlugins, uiPlugins, }); @@ -167,11 +166,6 @@ export class Server { rendering: renderingSetup, }); - const statusSetup = this.status.setup({ - elasticsearch: elasticsearchServiceSetup, - savedObjects: savedObjectsSetup, - }); - const loggingSetup = this.logging.setup({ loggingSystem: this.loggingSystem, }); @@ -295,33 +289,28 @@ export class Server { } public async setupCoreConfig() { - const schemas: Array<[ConfigPath, Type]> = [ - [pathConfig.path, pathConfig.schema], - [cspConfig.path, cspConfig.schema], - [elasticsearchConfig.path, elasticsearchConfig.schema], - [loggingConfig.path, loggingConfig.schema], - [httpConfig.path, httpConfig.schema], - [pluginsConfig.path, pluginsConfig.schema], - [devConfig.path, devConfig.schema], - [kibanaConfig.path, kibanaConfig.schema], - [savedObjectsConfig.path, savedObjectsConfig.schema], - [savedObjectsMigrationConfig.path, savedObjectsMigrationConfig.schema], - [uiSettingsConfig.path, uiSettingsConfig.schema], - [opsConfig.path, opsConfig.schema], + const configDescriptors: Array> = [ + pathConfig, + cspConfig, + elasticsearchConfig, + loggingConfig, + httpConfig, + pluginsConfig, + devConfig, + kibanaConfig, + savedObjectsConfig, + savedObjectsMigrationConfig, + uiSettingsConfig, + opsConfig, + statusConfig, ]; this.configService.addDeprecationProvider(rootConfigPath, coreDeprecationProvider); - this.configService.addDeprecationProvider( - elasticsearchConfig.path, - elasticsearchConfig.deprecations! - ); - this.configService.addDeprecationProvider( - uiSettingsConfig.path, - uiSettingsConfig.deprecations! - ); - - for (const [path, schema] of schemas) { - await this.configService.setSchema(path, schema); + for (const descriptor of configDescriptors) { + if (descriptor.deprecations) { + this.configService.addDeprecationProvider(descriptor.path, descriptor.deprecations); + } + await this.configService.setSchema(descriptor.path, descriptor.schema); } } } diff --git a/src/core/server/status/index.ts b/src/core/server/status/index.ts index c39115d55a682..79d62390b3d47 100644 --- a/src/core/server/status/index.ts +++ b/src/core/server/status/index.ts @@ -18,4 +18,5 @@ */ export { StatusService } from './status_service'; +export { config } from './status_config'; export * from './types'; diff --git a/src/legacy/core_plugins/status_page/public/components/server_status.test.js b/src/core/server/status/status_config.ts similarity index 67% rename from src/legacy/core_plugins/status_page/public/components/server_status.test.js rename to src/core/server/status/status_config.ts index 79f217e18ecb5..34e61dc2bb1fb 100644 --- a/src/legacy/core_plugins/status_page/public/components/server_status.test.js +++ b/src/core/server/status/status_config.ts @@ -17,17 +17,16 @@ * under the License. */ -import React from 'react'; -import { shallow } from 'enzyme'; -import ServerStatus from './server_status'; +import { schema, TypeOf } from '@kbn/config-schema'; +import { ServiceConfigDescriptor } from '../internal_types'; -const STATE = { - id: 'green', - title: 'Green', - uiColor: 'secondary', -}; - -test('render', () => { - const component = shallow(); - expect(component).toMatchSnapshot(); // eslint-disable-line +const statusConfigSchema = schema.object({ + allowAnonymous: schema.boolean({ defaultValue: false }), }); + +export type StatusConfigType = TypeOf; + +export const config: ServiceConfigDescriptor = { + path: 'status', + schema: statusConfigSchema, +}; diff --git a/src/core/server/status/status_service.mock.ts b/src/core/server/status/status_service.mock.ts index d550c2f06750b..c6eb11be6967c 100644 --- a/src/core/server/status/status_service.mock.ts +++ b/src/core/server/status/status_service.mock.ts @@ -48,6 +48,7 @@ const createInternalSetupContractMock = () => { const setupContract: jest.Mocked = { core$: new BehaviorSubject(availableCoreStatus), overall$: new BehaviorSubject(available), + isStatusPageAnonymous: jest.fn().mockReturnValue(false), }; return setupContract; diff --git a/src/core/server/status/status_service.test.ts b/src/core/server/status/status_service.test.ts index b692cf3161901..863fe34e8ecea 100644 --- a/src/core/server/status/status_service.test.ts +++ b/src/core/server/status/status_service.test.ts @@ -28,6 +28,12 @@ import { ServiceStatusLevelSnapshotSerializer } from './test_utils'; expect.addSnapshotSerializer(ServiceStatusLevelSnapshotSerializer); describe('StatusService', () => { + let service: StatusService; + + beforeEach(() => { + service = new StatusService(mockCoreContext.create()); + }); + const available: ServiceStatus = { level: ServiceStatusLevels.available, summary: 'Available', @@ -40,7 +46,7 @@ describe('StatusService', () => { describe('setup', () => { describe('core$', () => { it('rolls up core status observables into single observable', async () => { - const setup = new StatusService(mockCoreContext.create()).setup({ + const setup = await service.setup({ elasticsearch: { status$: of(available), }, @@ -55,7 +61,7 @@ describe('StatusService', () => { }); it('replays last event', async () => { - const setup = new StatusService(mockCoreContext.create()).setup({ + const setup = await service.setup({ elasticsearch: { status$: of(available), }, @@ -80,10 +86,10 @@ describe('StatusService', () => { }); }); - it('does not emit duplicate events', () => { + it('does not emit duplicate events', async () => { const elasticsearch$ = new BehaviorSubject(available); const savedObjects$ = new BehaviorSubject(degraded); - const setup = new StatusService(mockCoreContext.create()).setup({ + const setup = await service.setup({ elasticsearch: { status$: elasticsearch$, }, @@ -145,7 +151,7 @@ describe('StatusService', () => { describe('overall$', () => { it('exposes an overall summary', async () => { - const setup = new StatusService(mockCoreContext.create()).setup({ + const setup = await service.setup({ elasticsearch: { status$: of(degraded), }, @@ -160,7 +166,7 @@ describe('StatusService', () => { }); it('replays last event', async () => { - const setup = new StatusService(mockCoreContext.create()).setup({ + const setup = await service.setup({ elasticsearch: { status$: of(degraded), }, @@ -185,10 +191,10 @@ describe('StatusService', () => { }); }); - it('does not emit duplicate events', () => { + it('does not emit duplicate events', async () => { const elasticsearch$ = new BehaviorSubject(available); const savedObjects$ = new BehaviorSubject(degraded); - const setup = new StatusService(mockCoreContext.create()).setup({ + const setup = await service.setup({ elasticsearch: { status$: elasticsearch$, }, diff --git a/src/core/server/status/status_service.ts b/src/core/server/status/status_service.ts index ef7bed9587245..569b044a4fb27 100644 --- a/src/core/server/status/status_service.ts +++ b/src/core/server/status/status_service.ts @@ -20,7 +20,7 @@ /* eslint-disable max-classes-per-file */ import { Observable, combineLatest } from 'rxjs'; -import { map, distinctUntilChanged, shareReplay } from 'rxjs/operators'; +import { map, distinctUntilChanged, shareReplay, take } from 'rxjs/operators'; import { isDeepStrictEqual } from 'util'; import { CoreService } from '../../types'; @@ -29,6 +29,7 @@ import { Logger } from '../logging'; import { InternalElasticsearchServiceSetup } from '../elasticsearch'; import { InternalSavedObjectsServiceSetup } from '../saved_objects'; +import { config, StatusConfigType } from './status_config'; import { ServiceStatus, CoreStatus, InternalStatusServiceSetup } from './types'; import { getSummaryStatus } from './get_summary_status'; @@ -39,12 +40,15 @@ interface SetupDeps { export class StatusService implements CoreService { private readonly logger: Logger; + private readonly config$: Observable; constructor(coreContext: CoreContext) { this.logger = coreContext.logger.get('status'); + this.config$ = coreContext.configService.atPath(config.path); } - public setup(core: SetupDeps) { + public async setup(core: SetupDeps) { + const statusConfig = await this.config$.pipe(take(1)).toPromise(); const core$ = this.setupCoreStatus(core); const overall$: Observable = core$.pipe( map((coreStatus) => { @@ -58,6 +62,7 @@ export class StatusService implements CoreService { return { core$, overall$, + isStatusPageAnonymous: () => statusConfig.allowAnonymous, }; } diff --git a/src/core/server/status/types.ts b/src/core/server/status/types.ts index 84a7356c66bbf..b04c25a1eee93 100644 --- a/src/core/server/status/types.ts +++ b/src/core/server/status/types.ts @@ -131,4 +131,5 @@ export interface InternalStatusServiceSetup extends StatusServiceSetup { * Overall system status used for HTTP API */ overall$: Observable; + isStatusPageAnonymous: () => boolean; } diff --git a/src/dev/build/lib/platform.js b/src/core/types/status.ts similarity index 56% rename from src/dev/build/lib/platform.js rename to src/core/types/status.ts index ab2672615e1c5..20b012e960a6a 100644 --- a/src/dev/build/lib/platform.js +++ b/src/core/types/status.ts @@ -17,34 +17,36 @@ * under the License. */ -export function createPlatform(name, architecture, buildName) { - return new (class Platform { - getName() { - return name; - } +import type { OpsMetrics } from '../server/metrics'; - getArchitecture() { - return architecture; - } - - getBuildName() { - return buildName; - } - - getNodeArch() { - return `${name}-${architecture}`; - } +export interface ServerStatus { + id: string; + title: string; + state: string; + message: string; + uiColor: string; + icon?: string; + since?: string; +} - isWindows() { - return name === 'win32'; - } +export type ServerMetrics = OpsMetrics & { + collection_interval_in_millis: number; +}; - isMac() { - return name === 'darwin'; - } +export interface ServerVersion { + number: string; + build_hash: string; + build_number: string; + build_snapshot: string; +} - isLinux() { - return name === 'linux'; - } - })(); +export interface StatusResponse { + name: string; + uuid: string; + version: ServerVersion; + status: { + overall: ServerStatus; + statuses: ServerStatus[]; + }; + metrics: ServerMetrics; } diff --git a/src/dev/build/args.test.ts b/src/dev/build/args.test.ts index 6a464eef209ec..bd118b8887c72 100644 --- a/src/dev/build/args.test.ts +++ b/src/dev/build/args.test.ts @@ -17,160 +17,158 @@ * under the License. */ -import { ToolingLog } from '@kbn/dev-utils'; +import { ToolingLog, createAnyInstanceSerializer } from '@kbn/dev-utils'; import { readCliArgs } from './args'; -const fn = (...subArgs: string[]) => { - const result = readCliArgs(['node', 'scripts/build', ...subArgs]); - (result as any).log = result.log instanceof ToolingLog ? '' : String(result.log); - return result; -}; +expect.addSnapshotSerializer(createAnyInstanceSerializer(ToolingLog)); it('renders help if `--help` passed', () => { - expect(fn('--help')).toMatchInlineSnapshot(` -Object { - "log": "undefined", - "showHelp": true, - "unknownFlags": Array [], -} -`); + expect(readCliArgs(['node', 'scripts/build', '--help'])).toMatchInlineSnapshot(` + Object { + "log": , + "showHelp": true, + "unknownFlags": Array [], + } + `); }); it('build default and oss dist for current platform, without packages, by default', () => { - expect(fn()).toMatchInlineSnapshot(` -Object { - "buildArgs": Object { - "buildDefaultDist": true, - "buildOssDist": true, - "createArchives": true, - "createDebPackage": false, - "createDockerPackage": false, - "createDockerUbiPackage": false, - "createRpmPackage": false, - "downloadFreshNode": true, - "isRelease": false, - "targetAllPlatforms": false, - "versionQualifier": "", - }, - "log": "", - "showHelp": false, - "unknownFlags": Array [], -} -`); + expect(readCliArgs(['node', 'scripts/build'])).toMatchInlineSnapshot(` + Object { + "buildOptions": Object { + "buildDefaultDist": true, + "buildOssDist": true, + "createArchives": true, + "createDebPackage": false, + "createDockerPackage": false, + "createDockerUbiPackage": false, + "createRpmPackage": false, + "downloadFreshNode": true, + "isRelease": false, + "targetAllPlatforms": false, + "versionQualifier": "", + }, + "log": , + "showHelp": false, + "unknownFlags": Array [], + } + `); }); it('builds packages if --all-platforms is passed', () => { - expect(fn('--all-platforms')).toMatchInlineSnapshot(` -Object { - "buildArgs": Object { - "buildDefaultDist": true, - "buildOssDist": true, - "createArchives": true, - "createDebPackage": true, - "createDockerPackage": true, - "createDockerUbiPackage": true, - "createRpmPackage": true, - "downloadFreshNode": true, - "isRelease": false, - "targetAllPlatforms": true, - "versionQualifier": "", - }, - "log": "", - "showHelp": false, - "unknownFlags": Array [], -} -`); + expect(readCliArgs(['node', 'scripts/build', '--all-platforms'])).toMatchInlineSnapshot(` + Object { + "buildOptions": Object { + "buildDefaultDist": true, + "buildOssDist": true, + "createArchives": true, + "createDebPackage": true, + "createDockerPackage": true, + "createDockerUbiPackage": true, + "createRpmPackage": true, + "downloadFreshNode": true, + "isRelease": false, + "targetAllPlatforms": true, + "versionQualifier": "", + }, + "log": , + "showHelp": false, + "unknownFlags": Array [], + } + `); }); it('limits packages if --rpm passed with --all-platforms', () => { - expect(fn('--all-platforms', '--rpm')).toMatchInlineSnapshot(` -Object { - "buildArgs": Object { - "buildDefaultDist": true, - "buildOssDist": true, - "createArchives": true, - "createDebPackage": false, - "createDockerPackage": false, - "createDockerUbiPackage": false, - "createRpmPackage": true, - "downloadFreshNode": true, - "isRelease": false, - "targetAllPlatforms": true, - "versionQualifier": "", - }, - "log": "", - "showHelp": false, - "unknownFlags": Array [], -} -`); + expect(readCliArgs(['node', 'scripts/build', '--all-platforms', '--rpm'])).toMatchInlineSnapshot(` + Object { + "buildOptions": Object { + "buildDefaultDist": true, + "buildOssDist": true, + "createArchives": true, + "createDebPackage": false, + "createDockerPackage": false, + "createDockerUbiPackage": false, + "createRpmPackage": true, + "downloadFreshNode": true, + "isRelease": false, + "targetAllPlatforms": true, + "versionQualifier": "", + }, + "log": , + "showHelp": false, + "unknownFlags": Array [], + } + `); }); it('limits packages if --deb passed with --all-platforms', () => { - expect(fn('--all-platforms', '--deb')).toMatchInlineSnapshot(` -Object { - "buildArgs": Object { - "buildDefaultDist": true, - "buildOssDist": true, - "createArchives": true, - "createDebPackage": true, - "createDockerPackage": false, - "createDockerUbiPackage": false, - "createRpmPackage": false, - "downloadFreshNode": true, - "isRelease": false, - "targetAllPlatforms": true, - "versionQualifier": "", - }, - "log": "", - "showHelp": false, - "unknownFlags": Array [], -} -`); + expect(readCliArgs(['node', 'scripts/build', '--all-platforms', '--deb'])).toMatchInlineSnapshot(` + Object { + "buildOptions": Object { + "buildDefaultDist": true, + "buildOssDist": true, + "createArchives": true, + "createDebPackage": true, + "createDockerPackage": false, + "createDockerUbiPackage": false, + "createRpmPackage": false, + "downloadFreshNode": true, + "isRelease": false, + "targetAllPlatforms": true, + "versionQualifier": "", + }, + "log": , + "showHelp": false, + "unknownFlags": Array [], + } + `); }); it('limits packages if --docker passed with --all-platforms', () => { - expect(fn('--all-platforms', '--docker')).toMatchInlineSnapshot(` -Object { - "buildArgs": Object { - "buildDefaultDist": true, - "buildOssDist": true, - "createArchives": true, - "createDebPackage": false, - "createDockerPackage": true, - "createDockerUbiPackage": true, - "createRpmPackage": false, - "downloadFreshNode": true, - "isRelease": false, - "targetAllPlatforms": true, - "versionQualifier": "", - }, - "log": "", - "showHelp": false, - "unknownFlags": Array [], -} -`); + expect(readCliArgs(['node', 'scripts/build', '--all-platforms', '--docker'])) + .toMatchInlineSnapshot(` + Object { + "buildOptions": Object { + "buildDefaultDist": true, + "buildOssDist": true, + "createArchives": true, + "createDebPackage": false, + "createDockerPackage": true, + "createDockerUbiPackage": true, + "createRpmPackage": false, + "downloadFreshNode": true, + "isRelease": false, + "targetAllPlatforms": true, + "versionQualifier": "", + }, + "log": , + "showHelp": false, + "unknownFlags": Array [], + } + `); }); it('limits packages if --docker passed with --skip-docker-ubi and --all-platforms', () => { - expect(fn('--all-platforms', '--docker', '--skip-docker-ubi')).toMatchInlineSnapshot(` -Object { - "buildArgs": Object { - "buildDefaultDist": true, - "buildOssDist": true, - "createArchives": true, - "createDebPackage": false, - "createDockerPackage": true, - "createDockerUbiPackage": false, - "createRpmPackage": false, - "downloadFreshNode": true, - "isRelease": false, - "targetAllPlatforms": true, - "versionQualifier": "", - }, - "log": "", - "showHelp": false, - "unknownFlags": Array [], -} -`); + expect(readCliArgs(['node', 'scripts/build', '--all-platforms', '--docker', '--skip-docker-ubi'])) + .toMatchInlineSnapshot(` + Object { + "buildOptions": Object { + "buildDefaultDist": true, + "buildOssDist": true, + "createArchives": true, + "createDebPackage": false, + "createDockerPackage": true, + "createDockerUbiPackage": false, + "createRpmPackage": false, + "downloadFreshNode": true, + "isRelease": false, + "targetAllPlatforms": true, + "versionQualifier": "", + }, + "log": , + "showHelp": false, + "unknownFlags": Array [], + } + `); }); diff --git a/src/dev/build/args.ts b/src/dev/build/args.ts index 1ff42d524c596..8e77024a7e8ae 100644 --- a/src/dev/build/args.ts +++ b/src/dev/build/args.ts @@ -20,16 +20,9 @@ import getopts from 'getopts'; import { ToolingLog, pickLevelFromFlags } from '@kbn/dev-utils'; -interface ParsedArgs { - showHelp: boolean; - unknownFlags: string[]; - log?: ToolingLog; - buildArgs?: { - [key: string]: any; - }; -} +import { BuildOptions } from './build_distributables'; -export function readCliArgs(argv: string[]): ParsedArgs { +export function readCliArgs(argv: string[]) { const unknownFlags: string[] = []; const flags = getopts(argv, { boolean: [ @@ -70,8 +63,16 @@ export function readCliArgs(argv: string[]): ParsedArgs { }, }); + const log = new ToolingLog({ + level: pickLevelFromFlags(flags, { + default: flags.debug === false ? 'info' : 'debug', + }), + writeTo: process.stdout, + }); + if (unknownFlags.length || flags.help) { return { + log, showHelp: true, unknownFlags, }; @@ -83,13 +84,6 @@ export function readCliArgs(argv: string[]): ParsedArgs { flags['all-platforms'] = true; } - const log = new ToolingLog({ - level: pickLevelFromFlags(flags, { - default: flags.debug === false ? 'info' : 'debug', - }), - writeTo: process.stdout, - }); - function isOsPackageDesired(name: string) { if (flags['skip-os-packages'] || !flags['all-platforms']) { return false; @@ -103,22 +97,24 @@ export function readCliArgs(argv: string[]): ParsedArgs { return Boolean(flags[name]); } + const buildOptions: BuildOptions = { + isRelease: Boolean(flags.release), + versionQualifier: flags['version-qualifier'], + buildOssDist: flags.oss !== false, + buildDefaultDist: !flags.oss, + downloadFreshNode: !Boolean(flags['skip-node-download']), + createArchives: !Boolean(flags['skip-archives']), + createRpmPackage: isOsPackageDesired('rpm'), + createDebPackage: isOsPackageDesired('deb'), + createDockerPackage: isOsPackageDesired('docker'), + createDockerUbiPackage: isOsPackageDesired('docker') && !Boolean(flags['skip-docker-ubi']), + targetAllPlatforms: Boolean(flags['all-platforms']), + }; + return { + log, showHelp: false, unknownFlags: [], - log, - buildArgs: { - isRelease: Boolean(flags.release), - versionQualifier: flags['version-qualifier'], - buildOssDist: flags.oss !== false, - buildDefaultDist: !flags.oss, - downloadFreshNode: !Boolean(flags['skip-node-download']), - createArchives: !Boolean(flags['skip-archives']), - createRpmPackage: isOsPackageDesired('rpm'), - createDebPackage: isOsPackageDesired('deb'), - createDockerPackage: isOsPackageDesired('docker'), - createDockerUbiPackage: isOsPackageDesired('docker') && !Boolean(flags['skip-docker-ubi']), - targetAllPlatforms: Boolean(flags['all-platforms']), - }, + buildOptions, }; } diff --git a/src/dev/build/build_distributables.js b/src/dev/build/build_distributables.js deleted file mode 100644 index 39a32fff891c2..0000000000000 --- a/src/dev/build/build_distributables.js +++ /dev/null @@ -1,174 +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 { getConfig, createRunner } from './lib'; - -import { - BuildKibanaPlatformPluginsTask, - BuildPackagesTask, - CleanEmptyFoldersTask, - CleanExtraBinScriptsTask, - CleanExtraFilesFromModulesTask, - CleanNodeBuildsTask, - CleanPackagesTask, - CleanTask, - CleanTypescriptTask, - CopyBinScriptsTask, - CopySourceTask, - CreateArchivesSourcesTask, - CreateArchivesTask, - CreateDebPackageTask, - CreateDockerPackageTask, - CreateDockerUbiPackageTask, - CreateEmptyDirsAndFilesTask, - CreateNoticeFileTask, - CreatePackageJsonTask, - CreateReadmeTask, - CreateRpmPackageTask, - DownloadNodeBuildsTask, - ExtractNodeBuildsTask, - InstallChromiumTask, - InstallDependenciesTask, - OptimizeBuildTask, - PatchNativeModulesTask, - PathLengthTask, - RemovePackageJsonDepsTask, - RemoveWorkspacesTask, - TranspileBabelTask, - TranspileScssTask, - UpdateLicenseFileTask, - UuidVerificationTask, - VerifyEnvTask, - VerifyExistingNodeBuildsTask, - WriteShaSumsTask, -} from './tasks'; - -export async function buildDistributables(options) { - const { - log, - isRelease, - buildOssDist, - buildDefaultDist, - downloadFreshNode, - createArchives, - createRpmPackage, - createDebPackage, - createDockerPackage, - createDockerUbiPackage, - versionQualifier, - targetAllPlatforms, - } = options; - - log.verbose('building distributables with options:', { - isRelease, - buildOssDist, - buildDefaultDist, - downloadFreshNode, - createArchives, - createRpmPackage, - createDebPackage, - versionQualifier, - }); - - const config = await getConfig({ - isRelease, - versionQualifier, - targetAllPlatforms, - }); - - const run = createRunner({ - config, - log, - buildOssDist, - buildDefaultDist, - }); - - /** - * verify, reset, and initialize the build environment - */ - await run(VerifyEnvTask); - await run(CleanTask); - await run(downloadFreshNode ? DownloadNodeBuildsTask : VerifyExistingNodeBuildsTask); - await run(ExtractNodeBuildsTask); - - /** - * run platform-generic build tasks - */ - await run(CopySourceTask); - await run(CopyBinScriptsTask); - await run(CreateEmptyDirsAndFilesTask); - await run(CreateReadmeTask); - await run(TranspileBabelTask); - await run(BuildPackagesTask); - await run(CreatePackageJsonTask); - await run(InstallDependenciesTask); - await run(RemoveWorkspacesTask); - await run(CleanPackagesTask); - await run(CreateNoticeFileTask); - await run(UpdateLicenseFileTask); - await run(RemovePackageJsonDepsTask); - await run(TranspileScssTask); - await run(BuildKibanaPlatformPluginsTask); - await run(OptimizeBuildTask); - await run(CleanTypescriptTask); - await run(CleanExtraFilesFromModulesTask); - await run(CleanEmptyFoldersTask); - - /** - * copy generic build outputs into platform-specific build - * directories and perform platform/architecture-specific steps - */ - await run(CreateArchivesSourcesTask); - await run(PatchNativeModulesTask); - await run(InstallChromiumTask); - await run(CleanExtraBinScriptsTask); - await run(CleanNodeBuildsTask); - - await run(PathLengthTask); - await run(UuidVerificationTask); - - /** - * package platform-specific builds into archives - * or os-specific packages in the target directory - */ - if (createArchives) { - // control w/ --skip-archives - await run(CreateArchivesTask); - } - if (createDebPackage) { - // control w/ --deb or --skip-os-packages - await run(CreateDebPackageTask); - } - if (createRpmPackage) { - // control w/ --rpm or --skip-os-packages - await run(CreateRpmPackageTask); - } - if (createDockerPackage) { - // control w/ --docker or --skip-docker-ubi or --skip-os-packages - await run(CreateDockerPackageTask); - if (createDockerUbiPackage) { - await run(CreateDockerUbiPackageTask); - } - } - - /** - * finalize artifacts by writing sha1sums of each into the target directory - */ - await run(WriteShaSumsTask); -} diff --git a/src/dev/build/build_distributables.ts b/src/dev/build/build_distributables.ts new file mode 100644 index 0000000000000..bfcc98d6cd9a8 --- /dev/null +++ b/src/dev/build/build_distributables.ts @@ -0,0 +1,123 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { ToolingLog } from '@kbn/dev-utils'; + +import { Config, createRunner } from './lib'; +import * as Tasks from './tasks'; + +export interface BuildOptions { + isRelease: boolean; + buildOssDist: boolean; + buildDefaultDist: boolean; + downloadFreshNode: boolean; + createArchives: boolean; + createRpmPackage: boolean; + createDebPackage: boolean; + createDockerPackage: boolean; + createDockerUbiPackage: boolean; + versionQualifier: string | undefined; + targetAllPlatforms: boolean; +} + +export async function buildDistributables(log: ToolingLog, options: BuildOptions) { + log.verbose('building distributables with options:', options); + + const config = await Config.create(options); + + const run = createRunner({ + config, + log, + buildDefaultDist: options.buildDefaultDist, + buildOssDist: options.buildOssDist, + }); + + /** + * verify, reset, and initialize the build environment + */ + await run(Tasks.VerifyEnv); + await run(Tasks.Clean); + await run(options.downloadFreshNode ? Tasks.DownloadNodeBuilds : Tasks.VerifyExistingNodeBuilds); + await run(Tasks.ExtractNodeBuilds); + + /** + * run platform-generic build tasks + */ + await run(Tasks.CopySource); + await run(Tasks.CopyBinScripts); + await run(Tasks.CreateEmptyDirsAndFiles); + await run(Tasks.CreateReadme); + await run(Tasks.TranspileBabel); + await run(Tasks.BuildPackages); + await run(Tasks.CreatePackageJson); + await run(Tasks.InstallDependencies); + await run(Tasks.RemoveWorkspaces); + await run(Tasks.CleanPackages); + await run(Tasks.CreateNoticeFile); + await run(Tasks.UpdateLicenseFile); + await run(Tasks.RemovePackageJsonDeps); + await run(Tasks.TranspileScss); + await run(Tasks.BuildKibanaPlatformPlugins); + await run(Tasks.OptimizeBuild); + await run(Tasks.CleanTypescript); + await run(Tasks.CleanExtraFilesFromModules); + await run(Tasks.CleanEmptyFolders); + + /** + * copy generic build outputs into platform-specific build + * directories and perform platform/architecture-specific steps + */ + await run(Tasks.CreateArchivesSources); + await run(Tasks.PatchNativeModules); + await run(Tasks.InstallChromium); + await run(Tasks.CleanExtraBinScripts); + await run(Tasks.CleanNodeBuilds); + + await run(Tasks.PathLength); + await run(Tasks.UuidVerification); + + /** + * package platform-specific builds into archives + * or os-specific packages in the target directory + */ + if (options.createArchives) { + // control w/ --skip-archives + await run(Tasks.CreateArchives); + } + if (options.createDebPackage) { + // control w/ --deb or --skip-os-packages + await run(Tasks.CreateDebPackage); + } + if (options.createRpmPackage) { + // control w/ --rpm or --skip-os-packages + await run(Tasks.CreateRpmPackage); + } + if (options.createDockerPackage) { + // control w/ --docker or --skip-docker-ubi or --skip-os-packages + await run(Tasks.CreateDockerPackage); + if (options.createDockerUbiPackage) { + await run(Tasks.CreateDockerUbiPackage); + } + } + + /** + * finalize artifacts by writing sha1sums of each into the target directory + */ + await run(Tasks.WriteShaSums); +} diff --git a/src/dev/build/cli.js b/src/dev/build/cli.ts similarity index 91% rename from src/dev/build/cli.js rename to src/dev/build/cli.ts index 9d23f92a3bafd..5811fc42d2009 100644 --- a/src/dev/build/cli.js +++ b/src/dev/build/cli.ts @@ -29,15 +29,15 @@ import { readCliArgs } from './args'; // ensure the cwd() is always the repo root process.chdir(resolve(__dirname, '../../../')); -const { showHelp, unknownFlags, log, buildArgs } = readCliArgs(process.argv); +const { showHelp, unknownFlags, log, buildOptions } = readCliArgs(process.argv); if (unknownFlags.length) { const pluralized = unknownFlags.length > 1 ? 'flags' : 'flag'; - console.log(chalk`\n{red Unknown ${pluralized}: ${unknownFlags.join(', ')}}\n`); + log.error(`Unknown ${pluralized}: ${unknownFlags.join(', ')}}`); } if (showHelp) { - console.log( + log.write( dedent(chalk` {dim usage:} node scripts/build @@ -63,7 +63,7 @@ if (showHelp) { process.exit(1); } -buildDistributables({ log, ...buildArgs }).catch((error) => { +buildDistributables(log, buildOptions!).catch((error) => { if (!isErrorLogged(error)) { log.error('Uncaught error'); log.error(error); diff --git a/src/dev/build/lib/__tests__/fixtures/bin/world_executable b/src/dev/build/lib/__fixtures__/bin/world_executable similarity index 100% rename from src/dev/build/lib/__tests__/fixtures/bin/world_executable rename to src/dev/build/lib/__fixtures__/bin/world_executable diff --git a/src/dev/build/lib/__tests__/fixtures/foo.txt.gz b/src/dev/build/lib/__fixtures__/foo.txt.gz similarity index 100% rename from src/dev/build/lib/__tests__/fixtures/foo.txt.gz rename to src/dev/build/lib/__fixtures__/foo.txt.gz diff --git a/src/dev/build/lib/__tests__/fixtures/foo_dir.tar.gz b/src/dev/build/lib/__fixtures__/foo_dir.tar.gz similarity index 100% rename from src/dev/build/lib/__tests__/fixtures/foo_dir.tar.gz rename to src/dev/build/lib/__fixtures__/foo_dir.tar.gz diff --git a/src/dev/build/lib/__tests__/fixtures/foo_dir/.bar b/src/dev/build/lib/__fixtures__/foo_dir/.bar similarity index 100% rename from src/dev/build/lib/__tests__/fixtures/foo_dir/.bar rename to src/dev/build/lib/__fixtures__/foo_dir/.bar diff --git a/src/dev/build/lib/__tests__/fixtures/foo_dir/bar.txt b/src/dev/build/lib/__fixtures__/foo_dir/bar.txt similarity index 100% rename from src/dev/build/lib/__tests__/fixtures/foo_dir/bar.txt rename to src/dev/build/lib/__fixtures__/foo_dir/bar.txt diff --git a/src/dev/build/lib/__tests__/fixtures/foo_dir/foo/foo.txt b/src/dev/build/lib/__fixtures__/foo_dir/foo/foo.txt similarity index 100% rename from src/dev/build/lib/__tests__/fixtures/foo_dir/foo/foo.txt rename to src/dev/build/lib/__fixtures__/foo_dir/foo/foo.txt diff --git a/src/legacy/utils/__tests__/fixtures/log_on_sigint.js b/src/dev/build/lib/__fixtures__/log_on_sigint.js similarity index 100% rename from src/legacy/utils/__tests__/fixtures/log_on_sigint.js rename to src/dev/build/lib/__fixtures__/log_on_sigint.js diff --git a/src/dev/build/lib/__tests__/build.js b/src/dev/build/lib/__tests__/build.js deleted file mode 100644 index af9479e73f3dc..0000000000000 --- a/src/dev/build/lib/__tests__/build.js +++ /dev/null @@ -1,168 +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 expect from '@kbn/expect'; -import sinon from 'sinon'; - -import { createBuild } from '../build'; - -describe('dev/build/lib/build', () => { - describe('Build instance', () => { - describe('#isOss()', () => { - it('returns true if passed oss: true', () => { - const build = createBuild({ - oss: true, - }); - - expect(build.isOss()).to.be(true); - }); - - it('returns false if passed oss: false', () => { - const build = createBuild({ - oss: false, - }); - - expect(build.isOss()).to.be(false); - }); - }); - - describe('#getName()', () => { - it('returns kibana when oss: false', () => { - const build = createBuild({ - oss: false, - }); - - expect(build.getName()).to.be('kibana'); - }); - it('returns kibana-oss when oss: true', () => { - const build = createBuild({ - oss: true, - }); - - expect(build.getName()).to.be('kibana-oss'); - }); - }); - - describe('#getLogTag()', () => { - it('returns string with build name in it', () => { - const build = createBuild({}); - - expect(build.getLogTag()).to.contain(build.getName()); - }); - }); - - describe('#resolvePath()', () => { - it('uses passed config to resolve a path relative to the build', () => { - const resolveFromRepo = sinon.stub(); - const build = createBuild({ - config: { resolveFromRepo }, - }); - - build.resolvePath('bar'); - sinon.assert.calledWithExactly(resolveFromRepo, 'build', 'kibana', 'bar'); - }); - - it('passes all arguments to config.resolveFromRepo()', () => { - const resolveFromRepo = sinon.stub(); - const build = createBuild({ - config: { resolveFromRepo }, - }); - - build.resolvePath('bar', 'baz', 'box'); - sinon.assert.calledWithExactly(resolveFromRepo, 'build', 'kibana', 'bar', 'baz', 'box'); - }); - }); - - describe('#resolvePathForPlatform()', () => { - it('uses config.resolveFromRepo(), config.getBuildVersion(), and platform.getBuildName() to create path', () => { - const resolveFromRepo = sinon.stub(); - const getBuildVersion = sinon.stub().returns('buildVersion'); - const build = createBuild({ - oss: true, - config: { resolveFromRepo, getBuildVersion }, - }); - - const getBuildName = sinon.stub().returns('platformName'); - const platform = { - getBuildName, - }; - - build.resolvePathForPlatform(platform, 'foo', 'bar'); - sinon.assert.calledWithExactly(getBuildName); - sinon.assert.calledWithExactly(getBuildVersion); - sinon.assert.calledWithExactly( - resolveFromRepo, - 'build', - 'oss', - `kibana-buildVersion-platformName`, - 'foo', - 'bar' - ); - }); - }); - - describe('#getPlatformArchivePath()', () => { - const sandbox = sinon.createSandbox(); - - const config = { - resolveFromRepo: sandbox.stub(), - getBuildVersion: sandbox.stub().returns('buildVersion'), - }; - - const build = createBuild({ - oss: false, - config, - }); - - const platform = { - getBuildName: sandbox.stub().returns('platformName'), - isWindows: sandbox.stub().returns(false), - }; - - beforeEach(() => { - sandbox.resetHistory(); - }); - - it('uses config.resolveFromRepo(), config.getBuildVersion, and platform.getBuildName() to create path', () => { - build.getPlatformArchivePath(platform); - sinon.assert.calledWithExactly(platform.getBuildName); - sinon.assert.calledWithExactly(platform.isWindows); - sinon.assert.calledWithExactly(config.getBuildVersion); - sinon.assert.calledWithExactly( - config.resolveFromRepo, - 'target', - `kibana-buildVersion-platformName.tar.gz` - ); - }); - - it('creates .zip path if platform is windows', () => { - platform.isWindows.returns(true); - build.getPlatformArchivePath(platform); - sinon.assert.calledWithExactly(platform.getBuildName); - sinon.assert.calledWithExactly(platform.isWindows); - sinon.assert.calledWithExactly(config.getBuildVersion); - sinon.assert.calledWithExactly( - config.resolveFromRepo, - 'target', - `kibana-buildVersion-platformName.zip` - ); - }); - }); - }); -}); diff --git a/src/dev/build/lib/__tests__/config.js b/src/dev/build/lib/__tests__/config.js deleted file mode 100644 index 9544fc84dc6ff..0000000000000 --- a/src/dev/build/lib/__tests__/config.js +++ /dev/null @@ -1,174 +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 { resolve } from 'path'; - -import expect from '@kbn/expect'; - -import pkg from '../../../../../package.json'; -import { getConfig } from '../config'; -import { getVersionInfo } from '../version_info'; - -describe('dev/build/lib/config', () => { - const setup = async function ({ targetAllPlatforms = true } = {}) { - const isRelease = Boolean(Math.round(Math.random())); - const config = await getConfig({ - isRelease, - targetAllPlatforms, - }); - const buildInfo = await getVersionInfo({ - isRelease, - pkg, - }); - return { config, buildInfo }; - }; - - describe('#getKibanaPkg()', () => { - it('returns the parsed package.json from the Kibana repo', async () => { - const { config } = await setup(); - expect(config.getKibanaPkg()).to.eql(pkg); - }); - }); - - describe('#getNodeVersion()', () => { - it('returns the node version from the kibana package.json', async () => { - const { config } = await setup(); - expect(config.getNodeVersion()).to.eql(pkg.engines.node); - }); - }); - - describe('#getRepoRelativePath()', () => { - it('converts an absolute path to relative path, from the root of the repo', async () => { - const { config } = await setup(); - expect(config.getRepoRelativePath(__dirname)).to.match(/^src[\/\\]dev[\/\\]build/); - }); - }); - - describe('#resolveFromRepo()', () => { - it('resolves a relative path', async () => { - const { config } = await setup(); - expect(config.resolveFromRepo('src/dev/build/lib/__tests__')).to.be(__dirname); - }); - - it('resolves a series of relative paths', async () => { - const { config } = await setup(); - expect(config.resolveFromRepo('src', 'dev', 'build', 'lib', '__tests__')).to.be(__dirname); - }); - }); - - describe('#getPlatform()', () => { - it('throws error when platform does not exist', async () => { - const { config } = await setup(); - const fn = () => config.getPlatform('foo', 'x64'); - - expect(fn).to.throwException(/Unable to find platform/); - }); - - it('throws error when architecture does not exist', async () => { - const { config } = await setup(); - const fn = () => config.getPlatform('linux', 'foo'); - - expect(fn).to.throwException(/Unable to find platform/); - }); - }); - - describe('#getTargetPlatforms()', () => { - it('returns an array of all platform objects', async () => { - const { config } = await setup(); - expect( - config - .getTargetPlatforms() - .map((p) => p.getNodeArch()) - .sort() - ).to.eql(['darwin-x64', 'linux-arm64', 'linux-x64', 'win32-x64']); - }); - - it('returns just this platform when targetAllPlatforms = false', async () => { - const { config } = await setup({ targetAllPlatforms: false }); - const platforms = config.getTargetPlatforms(); - - expect(platforms).to.be.an('array'); - expect(platforms).to.have.length(1); - expect(platforms[0]).to.be(config.getPlatformForThisOs()); - }); - }); - - describe('#getNodePlatforms()', () => { - it('returns all platforms', async () => { - const { config } = await setup(); - expect( - config - .getTargetPlatforms() - .map((p) => p.getNodeArch()) - .sort() - ).to.eql(['darwin-x64', 'linux-arm64', 'linux-x64', 'win32-x64']); - }); - - it('returns this platform and linux, when targetAllPlatforms = false', async () => { - const { config } = await setup({ targetAllPlatforms: false }); - const platforms = config.getNodePlatforms(); - expect(platforms).to.be.an('array'); - if (process.platform !== 'linux') { - expect(platforms).to.have.length(2); - expect(platforms[0]).to.be(config.getPlatformForThisOs()); - expect(platforms[1]).to.be(config.getPlatform('linux', 'x64')); - } else { - expect(platforms).to.have.length(1); - expect(platforms[0]).to.be(config.getPlatform('linux', 'x64')); - } - }); - }); - - describe('#getPlatformForThisOs()', () => { - it('returns the platform that matches the arch of this machine', async () => { - const { config } = await setup(); - const currentPlatform = config.getPlatformForThisOs(); - expect(currentPlatform.getName()).to.be(process.platform); - expect(currentPlatform.getArchitecture()).to.be(process.arch); - }); - }); - - describe('#getBuildVersion()', () => { - it('returns the version from the build info', async () => { - const { config, buildInfo } = await setup(); - expect(config.getBuildVersion()).to.be(buildInfo.buildVersion); - }); - }); - - describe('#getBuildNumber()', () => { - it('returns the number from the build info', async () => { - const { config, buildInfo } = await setup(); - expect(config.getBuildNumber()).to.be(buildInfo.buildNumber); - }); - }); - - describe('#getBuildSha()', () => { - it('returns the sha from the build info', async () => { - const { config, buildInfo } = await setup(); - expect(config.getBuildSha()).to.be(buildInfo.buildSha); - }); - }); - - describe('#resolveFromTarget()', () => { - it('resolves a relative path, from the target directory', async () => { - const { config } = await setup(); - expect(config.resolveFromTarget()).to.be(resolve(__dirname, '../../../../../target')); - }); - }); -}); diff --git a/src/dev/build/lib/__tests__/download.js b/src/dev/build/lib/__tests__/download.js deleted file mode 100644 index 49cb9caaaf4ec..0000000000000 --- a/src/dev/build/lib/__tests__/download.js +++ /dev/null @@ -1,237 +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 { createServer } from 'http'; -import { join } from 'path'; -import { tmpdir } from 'os'; -import { mkdirp, readFileSync } from 'fs-extra'; - -import del from 'del'; -import sinon from 'sinon'; -import { CI_PARALLEL_PROCESS_PREFIX } from '@kbn/test'; -import expect from '@kbn/expect'; -import Wreck from '@hapi/wreck'; - -import { ToolingLog } from '@kbn/dev-utils'; -import { download } from '../download'; - -const getTempFolder = async () => { - const dir = join(tmpdir(), CI_PARALLEL_PROCESS_PREFIX, 'download-js-test-tmp-dir'); - console.log(dir); - await mkdirp(dir); - return dir; -}; - -describe('src/dev/build/tasks/nodejs/download', () => { - const sandbox = sinon.createSandbox(); - let TMP_DESTINATION; - let TMP_DIR; - - beforeEach(async () => { - TMP_DIR = await getTempFolder(); - TMP_DESTINATION = join(TMP_DIR, '__tmp_download_js_test_file__'); - }); - - afterEach(async () => { - await del(TMP_DIR, { force: true }); - }); - afterEach(() => sandbox.reset()); - - const onLogLine = sandbox.stub(); - const log = new ToolingLog({ - level: 'verbose', - writeTo: { - write: onLogLine, - }, - }); - - const FOO_SHA256 = '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'; - const createSendHandler = (send) => (req, res) => { - res.statusCode = 200; - res.end(send); - }; - const sendErrorHandler = (req, res) => { - res.statusCode = 500; - res.end(); - }; - - let server; - let serverUrl; - let nextHandler; - afterEach(() => (nextHandler = null)); - - before(async () => { - server = createServer((req, res) => { - if (!nextHandler) { - nextHandler = sendErrorHandler; - } - - const handler = nextHandler; - nextHandler = null; - handler(req, res); - }); - - await Promise.race([ - new Promise((resolve, reject) => { - server.once('error', reject); - }), - new Promise((resolve) => { - server.listen(resolve); - }), - ]); - - serverUrl = `http://localhost:${server.address().port}/`; - }); - - after(async () => { - server.close(); - server = null; - }); - - it('downloads from URL and checks that content matches sha256', async () => { - nextHandler = createSendHandler('foo'); - await download({ - log, - url: serverUrl, - destination: TMP_DESTINATION, - sha256: FOO_SHA256, - }); - expect(readFileSync(TMP_DESTINATION, 'utf8')).to.be('foo'); - }); - - it('rejects and deletes destination if sha256 does not match', async () => { - nextHandler = createSendHandler('foo'); - - try { - await download({ - log, - url: serverUrl, - destination: TMP_DESTINATION, - sha256: 'bar', - }); - throw new Error('Expected download() to reject'); - } catch (error) { - expect(error) - .to.have.property('message') - .contain('does not match the expected sha256 checksum'); - } - - try { - readFileSync(TMP_DESTINATION); - throw new Error('Expected download to be deleted'); - } catch (error) { - expect(error).to.have.property('code', 'ENOENT'); - } - }); - - describe('reties download retries: number of times', () => { - it('resolves if retries = 1 and first attempt fails', async () => { - let reqCount = 0; - nextHandler = function sequenceHandler(req, res) { - switch (++reqCount) { - case 1: - nextHandler = sequenceHandler; - return sendErrorHandler(req, res); - default: - return createSendHandler('foo')(req, res); - } - }; - - await download({ - log, - url: serverUrl, - destination: TMP_DESTINATION, - sha256: FOO_SHA256, - retries: 2, - }); - - expect(readFileSync(TMP_DESTINATION, 'utf8')).to.be('foo'); - }); - - it('resolves if first fails, second is bad shasum, but third succeeds', async () => { - let reqCount = 0; - nextHandler = function sequenceHandler(req, res) { - switch (++reqCount) { - case 1: - nextHandler = sequenceHandler; - return sendErrorHandler(req, res); - case 2: - nextHandler = sequenceHandler; - return createSendHandler('bar')(req, res); - default: - return createSendHandler('foo')(req, res); - } - }; - - await download({ - log, - url: serverUrl, - destination: TMP_DESTINATION, - sha256: FOO_SHA256, - retries: 2, - }); - }); - - it('makes 6 requests if `retries: 5` and all failed', async () => { - let reqCount = 0; - nextHandler = function sequenceHandler(req, res) { - reqCount += 1; - nextHandler = sequenceHandler; - sendErrorHandler(req, res); - }; - - try { - await download({ - log, - url: serverUrl, - destination: TMP_DESTINATION, - sha256: FOO_SHA256, - retries: 5, - }); - throw new Error('Expected download() to reject'); - } catch (error) { - expect(error).to.have.property('message').contain('Request failed with status code 500'); - expect(reqCount).to.be(6); - } - }); - }); - - describe('sha256 option not supplied', () => { - before(() => { - sinon.stub(Wreck, 'request'); - }); - after(() => { - Wreck.request.restore(); - }); - - it('refuses to download', async () => { - try { - await download({ - log, - url: 'http://google.com', - destination: TMP_DESTINATION, - }); - - throw new Error('expected download() to reject'); - } catch (error) { - expect(error).to.have.property('message').contain('refusing to download'); - } - }); - }); -}); diff --git a/src/dev/build/lib/__tests__/exec.js b/src/dev/build/lib/__tests__/exec.js deleted file mode 100644 index 8e122c65132ac..0000000000000 --- a/src/dev/build/lib/__tests__/exec.js +++ /dev/null @@ -1,58 +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 sinon from 'sinon'; -import stripAnsi from 'strip-ansi'; - -import { ToolingLog } from '@kbn/dev-utils'; -import { exec } from '../exec'; - -describe('dev/build/lib/exec', () => { - const sandbox = sinon.createSandbox(); - afterEach(() => sandbox.reset()); - - const onLogLine = sandbox.stub(); - const log = new ToolingLog({ - level: 'verbose', - writeTo: { - write: (chunk) => { - onLogLine(stripAnsi(chunk)); - }, - }, - }); - - it('executes a command, logs the command, and logs the output', async () => { - await exec(log, process.execPath, ['-e', 'console.log("hi")']); - - // logs the command before execution - sinon.assert.calledWithExactly(onLogLine, sinon.match(`$ ${process.execPath}`)); - - // log output of the process - sinon.assert.calledWithExactly(onLogLine, sinon.match(/debg\s+hi/)); - }); - - it('logs using level: option', async () => { - await exec(log, process.execPath, ['-e', 'console.log("hi")'], { - level: 'info', - }); - - // log output of the process - sinon.assert.calledWithExactly(onLogLine, sinon.match(/info\s+hi/)); - }); -}); diff --git a/src/dev/build/lib/__tests__/fs.js b/src/dev/build/lib/__tests__/fs.js deleted file mode 100644 index bf7596b012f79..0000000000000 --- a/src/dev/build/lib/__tests__/fs.js +++ /dev/null @@ -1,362 +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 { resolve } from 'path'; -import { chmodSync, statSync } from 'fs'; - -import del from 'del'; -import expect from '@kbn/expect'; - -import { mkdirp, write, read, getChildPaths, copyAll, getFileHash, untar, gunzip } from '../fs'; - -const TMP = resolve(__dirname, '__tmp__'); -const FIXTURES = resolve(__dirname, 'fixtures'); -const FOO_TAR_PATH = resolve(FIXTURES, 'foo_dir.tar.gz'); -const FOO_GZIP_PATH = resolve(FIXTURES, 'foo.txt.gz'); -const BAR_TXT_PATH = resolve(FIXTURES, 'foo_dir/bar.txt'); -const WORLD_EXECUTABLE = resolve(FIXTURES, 'bin/world_executable'); - -const isWindows = /^win/.test(process.platform); - -// get the mode of a file as a string, like 777, or 644, -function getCommonMode(path) { - return statSync(path).mode.toString(8).slice(-3); -} - -function assertNonAbsoluteError(error) { - expect(error).to.be.an(Error); - expect(error.message).to.contain('Please use absolute paths'); -} - -describe('dev/build/lib/fs', () => { - // ensure WORLD_EXECUTABLE is actually executable by all - before(async () => { - chmodSync(WORLD_EXECUTABLE, 0o777); - }); - - // clean and recreate TMP directory - beforeEach(async () => { - await del(TMP); - await mkdirp(TMP); - }); - - // cleanup TMP directory - after(async () => { - await del(TMP); - }); - - describe('mkdirp()', () => { - it('rejects if path is not absolute', async () => { - try { - await mkdirp('foo/bar'); - throw new Error('Expected mkdirp() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('makes directory and necessary parent directories', async () => { - const destination = resolve(TMP, 'a/b/c/d/e/f/g'); - - expect(await mkdirp(destination)).to.be(undefined); - - expect(statSync(destination).isDirectory()).to.be(true); - }); - }); - - describe('write()', () => { - it('rejects if path is not absolute', async () => { - try { - await write('foo/bar'); - throw new Error('Expected write() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('writes content to a file with existing parent directory', async () => { - const destination = resolve(TMP, 'a'); - - expect(await write(destination, 'bar')).to.be(undefined); - expect(await read(destination)).to.be('bar'); - }); - - it('writes content to a file with missing parents', async () => { - const destination = resolve(TMP, 'a/b/c/d/e'); - - expect(await write(destination, 'bar')).to.be(undefined); - expect(await read(destination)).to.be('bar'); - }); - }); - - describe('read()', () => { - it('rejects if path is not absolute', async () => { - try { - await read('foo/bar'); - throw new Error('Expected read() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('reads file, resolves with result', async () => { - expect(await read(BAR_TXT_PATH)).to.be('bar\n'); - }); - }); - - describe('getChildPaths()', () => { - it('rejects if path is not absolute', async () => { - try { - await getChildPaths('foo/bar'); - throw new Error('Expected getChildPaths() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('resolves with absolute paths to the children of directory', async () => { - const path = resolve(FIXTURES, 'foo_dir'); - expect((await getChildPaths(path)).sort()).to.eql([ - resolve(FIXTURES, 'foo_dir/.bar'), - BAR_TXT_PATH, - resolve(FIXTURES, 'foo_dir/foo'), - ]); - }); - - it('rejects with ENOENT if path does not exist', async () => { - try { - await getChildPaths(resolve(FIXTURES, 'notrealpath')); - throw new Error('Expected getChildPaths() to reject'); - } catch (error) { - expect(error).to.have.property('code', 'ENOENT'); - } - }); - }); - - describe('copyAll()', () => { - it('rejects if source path is not absolute', async () => { - try { - await copyAll('foo/bar', __dirname); - throw new Error('Expected copyAll() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('rejects if destination path is not absolute', async () => { - try { - await copyAll(__dirname, 'foo/bar'); - throw new Error('Expected copyAll() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('rejects if neither path is not absolute', async () => { - try { - await copyAll('foo/bar', 'foo/bar'); - throw new Error('Expected copyAll() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('copies files and directories from source to dest, creating dest if necessary, respecting mode', async () => { - const destination = resolve(TMP, 'a/b/c'); - await copyAll(FIXTURES, destination); - - expect((await getChildPaths(resolve(destination, 'foo_dir'))).sort()).to.eql([ - resolve(destination, 'foo_dir/bar.txt'), - resolve(destination, 'foo_dir/foo'), - ]); - - expect(getCommonMode(resolve(destination, 'bin/world_executable'))).to.be( - isWindows ? '666' : '777' - ); - expect(getCommonMode(resolve(destination, 'foo_dir/bar.txt'))).to.be( - isWindows ? '666' : '644' - ); - }); - - it('applies select globs if specified, ignores dot files', async () => { - const destination = resolve(TMP, 'a/b/c/d'); - await copyAll(FIXTURES, destination, { - select: ['**/*bar*'], - }); - - try { - statSync(resolve(destination, 'bin/world_executable')); - throw new Error('expected bin/world_executable to not by copied'); - } catch (error) { - expect(error).to.have.property('code', 'ENOENT'); - } - - try { - statSync(resolve(destination, 'foo_dir/.bar')); - throw new Error('expected foo_dir/.bar to not by copied'); - } catch (error) { - expect(error).to.have.property('code', 'ENOENT'); - } - - expect(await read(resolve(destination, 'foo_dir/bar.txt'))).to.be('bar\n'); - }); - - it('supports select globs and dot option together', async () => { - const destination = resolve(TMP, 'a/b/c/d'); - await copyAll(FIXTURES, destination, { - select: ['**/*bar*'], - dot: true, - }); - - try { - statSync(resolve(destination, 'bin/world_executable')); - throw new Error('expected bin/world_executable to not by copied'); - } catch (error) { - expect(error).to.have.property('code', 'ENOENT'); - } - - expect(await read(resolve(destination, 'foo_dir/bar.txt'))).to.be('bar\n'); - expect(await read(resolve(destination, 'foo_dir/.bar'))).to.be('dotfile\n'); - }); - - it('supports atime and mtime', async () => { - const destination = resolve(TMP, 'a/b/c/d/e'); - const time = new Date(1425298511000); - await copyAll(FIXTURES, destination, { - time, - }); - const barTxt = statSync(resolve(destination, 'foo_dir/bar.txt')); - const fooDir = statSync(resolve(destination, 'foo_dir')); - - // precision is platform specific - const oneDay = 86400000; - expect(Math.abs(barTxt.atimeMs - time.getTime())).to.be.below(oneDay); - expect(Math.abs(fooDir.atimeMs - time.getTime())).to.be.below(oneDay); - expect(Math.abs(barTxt.mtimeMs - time.getTime())).to.be.below(oneDay); - }); - }); - - describe('getFileHash()', () => { - it('rejects if path is not absolute', async () => { - try { - await getFileHash('foo/bar'); - throw new Error('Expected getFileHash() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('resolves with the sha1 hash of a file', async () => { - expect(await getFileHash(BAR_TXT_PATH, 'sha1')).to.be( - 'e242ed3bffccdf271b7fbaf34ed72d089537b42f' - ); - }); - it('resolves with the sha256 hash of a file', async () => { - expect(await getFileHash(BAR_TXT_PATH, 'sha256')).to.be( - '7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730' - ); - }); - it('resolves with the md5 hash of a file', async () => { - expect(await getFileHash(BAR_TXT_PATH, 'md5')).to.be('c157a79031e1c40f85931829bc5fc552'); - }); - }); - - describe('untar()', () => { - it('rejects if source path is not absolute', async () => { - try { - await untar('foo/bar', '**/*', __dirname); - throw new Error('Expected untar() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('rejects if destination path is not absolute', async () => { - try { - await untar(__dirname, '**/*', 'foo/bar'); - throw new Error('Expected untar() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('rejects if neither path is not absolute', async () => { - try { - await untar('foo/bar', '**/*', 'foo/bar'); - throw new Error('Expected untar() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('extracts tarbar from source into destination, creating destination if necessary', async () => { - const destination = resolve(TMP, 'a/b/c/d/e/f'); - await untar(FOO_TAR_PATH, destination); - expect(await read(resolve(destination, 'foo_dir/bar.txt'))).to.be('bar\n'); - expect(await read(resolve(destination, 'foo_dir/foo/foo.txt'))).to.be('foo\n'); - }); - - it('passed thrid argument to Extract class, overriding path with destination', async () => { - const destination = resolve(TMP, 'a/b/c'); - - await untar(FOO_TAR_PATH, destination, { - path: '/dev/null', - strip: 1, - }); - - expect(await read(resolve(destination, 'bar.txt'))).to.be('bar\n'); - expect(await read(resolve(destination, 'foo/foo.txt'))).to.be('foo\n'); - }); - }); - - describe('gunzip()', () => { - it('rejects if source path is not absolute', async () => { - try { - await gunzip('foo/bar', '**/*', __dirname); - throw new Error('Expected gunzip() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('rejects if destination path is not absolute', async () => { - try { - await gunzip(__dirname, '**/*', 'foo/bar'); - throw new Error('Expected gunzip() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('rejects if neither path is not absolute', async () => { - try { - await gunzip('foo/bar', '**/*', 'foo/bar'); - throw new Error('Expected gunzip() to reject'); - } catch (error) { - assertNonAbsoluteError(error); - } - }); - - it('extracts gzip from source into destination, creating destination if necessary', async () => { - const destination = resolve(TMP, 'z/y/x/v/u/t/foo.txt'); - await gunzip(FOO_GZIP_PATH, destination); - expect(await read(resolve(destination))).to.be('foo\n'); - }); - }); -}); diff --git a/src/dev/build/lib/__tests__/platform.js b/src/dev/build/lib/__tests__/platform.js deleted file mode 100644 index a7bb5670ee412..0000000000000 --- a/src/dev/build/lib/__tests__/platform.js +++ /dev/null @@ -1,68 +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 expect from '@kbn/expect'; - -import { createPlatform } from '../platform'; - -describe('src/dev/build/lib/platform', () => { - describe('getName()', () => { - it('returns the name argument', () => { - expect(createPlatform('foo').getName()).to.be('foo'); - }); - }); - - describe('getNodeArch()', () => { - it('returns the node arch for the passed name', () => { - expect(createPlatform('win32', 'x64').getNodeArch()).to.be('win32-x64'); - }); - }); - - describe('getBuildName()', () => { - it('returns the build name for the passed name', () => { - expect(createPlatform('linux', 'arm64', 'linux-aarch64').getBuildName()).to.be( - 'linux-aarch64' - ); - }); - }); - - describe('isWindows()', () => { - it('returns true if name is win32', () => { - expect(createPlatform('win32', 'x64').isWindows()).to.be(true); - expect(createPlatform('linux', 'x64').isWindows()).to.be(false); - expect(createPlatform('darwin', 'x64').isWindows()).to.be(false); - }); - }); - - describe('isLinux()', () => { - it('returns true if name is linux', () => { - expect(createPlatform('win32', 'x64').isLinux()).to.be(false); - expect(createPlatform('linux', 'x64').isLinux()).to.be(true); - expect(createPlatform('darwin', 'x64').isLinux()).to.be(false); - }); - }); - - describe('isMac()', () => { - it('returns true if name is darwin', () => { - expect(createPlatform('win32', 'x64').isMac()).to.be(false); - expect(createPlatform('linux', 'x64').isMac()).to.be(false); - expect(createPlatform('darwin', 'x64').isMac()).to.be(true); - }); - }); -}); diff --git a/src/dev/build/lib/__tests__/runner.js b/src/dev/build/lib/__tests__/runner.js deleted file mode 100644 index 314c2dd45d50f..0000000000000 --- a/src/dev/build/lib/__tests__/runner.js +++ /dev/null @@ -1,184 +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 sinon from 'sinon'; -import expect from '@kbn/expect'; - -import { ToolingLog } from '@kbn/dev-utils'; -import { createRunner } from '../runner'; -import { isErrorLogged, markErrorLogged } from '../errors'; - -describe('dev/build/lib/runner', () => { - const sandbox = sinon.createSandbox(); - - const config = {}; - - const onLogLine = sandbox.stub(); - const log = new ToolingLog({ - level: 'verbose', - writeTo: { - write: onLogLine, - }, - }); - - const buildMatcher = sinon.match({ - isOss: sinon.match.func, - resolvePath: sinon.match.func, - resolvePathForPlatform: sinon.match.func, - getPlatformArchivePath: sinon.match.func, - getName: sinon.match.func, - getLogTag: sinon.match.func, - }); - - const ossBuildMatcher = buildMatcher.and(sinon.match((b) => b.isOss(), 'is oss build')); - const defaultBuildMatcher = buildMatcher.and(sinon.match((b) => !b.isOss(), 'is not oss build')); - - afterEach(() => sandbox.reset()); - - describe('defaults', () => { - const run = createRunner({ - config, - log, - }); - - it('returns a promise', () => { - expect(run({ run: sinon.stub() })).to.be.a(Promise); - }); - - it('runs global task once, passing config and log', async () => { - const runTask = sinon.stub(); - await run({ global: true, run: runTask }); - sinon.assert.calledOnce(runTask); - sinon.assert.calledWithExactly(runTask, config, log, sinon.match.array); - }); - - it('does not call local tasks', async () => { - const runTask = sinon.stub(); - await run({ run: runTask }); - sinon.assert.notCalled(runTask); - }); - }); - - describe('buildOssDist = true, buildDefaultDist = true', () => { - const run = createRunner({ - config, - log, - buildOssDist: true, - buildDefaultDist: true, - }); - - it('runs global task once, passing config and log', async () => { - const runTask = sinon.stub(); - await run({ global: true, run: runTask }); - sinon.assert.calledOnce(runTask); - sinon.assert.calledWithExactly(runTask, config, log, sinon.match.array); - }); - - it('runs local tasks twice, passing config log and both builds', async () => { - const runTask = sinon.stub(); - await run({ run: runTask }); - sinon.assert.calledTwice(runTask); - sinon.assert.calledWithExactly(runTask, config, log, ossBuildMatcher); - sinon.assert.calledWithExactly(runTask, config, log, defaultBuildMatcher); - }); - }); - - describe('just default dist', () => { - const run = createRunner({ - config, - log, - buildDefaultDist: true, - }); - - it('runs global task once, passing config and log', async () => { - const runTask = sinon.stub(); - await run({ global: true, run: runTask }); - sinon.assert.calledOnce(runTask); - sinon.assert.calledWithExactly(runTask, config, log, sinon.match.array); - }); - - it('runs local tasks once, passing config log and default build', async () => { - const runTask = sinon.stub(); - await run({ run: runTask }); - sinon.assert.calledOnce(runTask); - sinon.assert.calledWithExactly(runTask, config, log, defaultBuildMatcher); - }); - }); - - describe('just oss dist', () => { - const run = createRunner({ - config, - log, - buildOssDist: true, - }); - - it('runs global task once, passing config and log', async () => { - const runTask = sinon.stub(); - await run({ global: true, run: runTask }); - sinon.assert.calledOnce(runTask); - sinon.assert.calledWithExactly(runTask, config, log, sinon.match.array); - }); - - it('runs local tasks once, passing config log and oss build', async () => { - const runTask = sinon.stub(); - await run({ run: runTask }); - sinon.assert.calledOnce(runTask); - sinon.assert.calledWithExactly(runTask, config, log, ossBuildMatcher); - }); - }); - - describe('task rejects', () => { - const run = createRunner({ - config, - log, - buildOssDist: true, - }); - - it('rejects, logs error, and marks error logged', async () => { - try { - await run({ - async run() { - throw new Error('FOO'); - }, - }); - throw new Error('expected run() to reject'); - } catch (error) { - expect(error).to.have.property('message').be('FOO'); - sinon.assert.calledWith(onLogLine, sinon.match(/FOO/)); - expect(isErrorLogged(error)).to.be(true); - } - }); - - it('just rethrows errors that have already been logged', async () => { - try { - await run({ - async run() { - throw markErrorLogged(new Error('FOO')); - }, - }); - - throw new Error('expected run() to reject'); - } catch (error) { - expect(error).to.have.property('message').be('FOO'); - sinon.assert.neverCalledWith(onLogLine, sinon.match(/FOO/)); - expect(isErrorLogged(error)).to.be(true); - } - }); - }); -}); diff --git a/src/dev/build/lib/__tests__/version_info.js b/src/dev/build/lib/__tests__/version_info.js deleted file mode 100644 index a7329642e4f9a..0000000000000 --- a/src/dev/build/lib/__tests__/version_info.js +++ /dev/null @@ -1,70 +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 expect from '@kbn/expect'; - -import pkg from '../../../../../package.json'; -import { getVersionInfo } from '../version_info'; - -describe('dev/build/lib/version_info', () => { - describe('isRelease = true', () => { - it('returns unchanged package.version, build sha, and build number', async () => { - const versionInfo = await getVersionInfo({ - isRelease: true, - pkg, - }); - - expect(versionInfo).to.have.property('buildVersion', pkg.version); - expect(versionInfo) - .to.have.property('buildSha') - .match(/^[0-9a-f]{40}$/); - expect(versionInfo).to.have.property('buildNumber').a('number').greaterThan(1000); - }); - }); - describe('isRelease = false', () => { - it('returns snapshot version, build sha, and build number', async () => { - const versionInfo = await getVersionInfo({ - isRelease: false, - pkg, - }); - - expect(versionInfo) - .to.have.property('buildVersion') - .contain(pkg.version) - .match(/-SNAPSHOT$/); - expect(versionInfo) - .to.have.property('buildSha') - .match(/^[0-9a-f]{40}$/); - expect(versionInfo).to.have.property('buildNumber').a('number').greaterThan(1000); - }); - }); - - describe('versionQualifier', () => { - it('appends a version qualifier', async () => { - const versionInfo = await getVersionInfo({ - isRelease: true, - versionQualifier: 'beta55', - pkg, - }); - expect(versionInfo) - .to.have.property('buildVersion') - .be(pkg.version + '-beta55'); - }); - }); -}); diff --git a/src/dev/build/lib/build.js b/src/dev/build/lib/build.js deleted file mode 100644 index fe5111ad1377a..0000000000000 --- a/src/dev/build/lib/build.js +++ /dev/null @@ -1,60 +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 chalk from 'chalk'; - -export function createBuild({ config, oss }) { - const name = oss ? 'kibana-oss' : 'kibana'; - const logTag = oss ? chalk`{magenta [kibana-oss]}` : chalk`{cyan [ kibana ]}`; - - return new (class Build { - isOss() { - return !!oss; - } - - resolvePath(...args) { - return config.resolveFromRepo('build', name, ...args); - } - - resolvePathForPlatform(platform, ...args) { - return config.resolveFromRepo( - 'build', - oss ? 'oss' : 'default', - `kibana-${config.getBuildVersion()}-${platform.getBuildName()}`, - ...args - ); - } - - getPlatformArchivePath(platform) { - const ext = platform.isWindows() ? 'zip' : 'tar.gz'; - return config.resolveFromRepo( - 'target', - `${name}-${config.getBuildVersion()}-${platform.getBuildName()}.${ext}` - ); - } - - getName() { - return name; - } - - getLogTag() { - return logTag; - } - })(); -} diff --git a/src/dev/build/lib/build.test.ts b/src/dev/build/lib/build.test.ts new file mode 100644 index 0000000000000..9fdf21cee6567 --- /dev/null +++ b/src/dev/build/lib/build.test.ts @@ -0,0 +1,120 @@ +/* + * 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 { REPO_ROOT, createAbsolutePathSerializer } from '@kbn/dev-utils'; + +import { Config } from './config'; +import { Build } from './build'; + +expect.addSnapshotSerializer(createAbsolutePathSerializer()); + +const config = new Config( + true, + { + version: '8.0.0', + engines: { + node: '*', + }, + workspaces: { + packages: [], + }, + }, + '1.2.3', + REPO_ROOT, + { + buildNumber: 1234, + buildSha: 'abcd1234', + buildVersion: '8.0.0', + }, + true +); + +const linuxPlatform = config.getPlatform('linux', 'x64'); +const linuxArmPlatform = config.getPlatform('linux', 'arm64'); +const windowsPlatform = config.getPlatform('win32', 'x64'); + +beforeEach(() => { + jest.clearAllMocks(); +}); + +const ossBuild = new Build(config, true); +const defaultBuild = new Build(config, false); + +describe('#isOss()', () => { + it('returns true for oss', () => { + expect(ossBuild.isOss()).toBe(true); + }); + + it('returns false for default build', () => { + expect(defaultBuild.isOss()).toBe(false); + }); +}); + +describe('#getName()', () => { + it('returns kibana for default build', () => { + expect(defaultBuild.getName()).toBe('kibana'); + }); + + it('returns kibana-oss for oss', () => { + expect(ossBuild.getName()).toBe('kibana-oss'); + }); +}); + +describe('#getLogTag()', () => { + it('returns string with build name in it', () => { + expect(defaultBuild.getLogTag()).toContain(defaultBuild.getName()); + expect(ossBuild.getLogTag()).toContain(ossBuild.getName()); + }); +}); + +describe('#resolvePath()', () => { + it('uses passed config to resolve a path relative to the repo', () => { + expect(ossBuild.resolvePath('bar')).toMatchInlineSnapshot( + `/build/kibana-oss/bar` + ); + }); + + it('passes all arguments to config.resolveFromRepo()', () => { + expect(defaultBuild.resolvePath('bar', 'baz', 'box')).toMatchInlineSnapshot( + `/build/kibana/bar/baz/box` + ); + }); +}); + +describe('#resolvePathForPlatform()', () => { + it('uses config.resolveFromRepo(), config.getBuildVersion(), and platform.getBuildName() to create path', () => { + expect(ossBuild.resolvePathForPlatform(linuxPlatform, 'foo', 'bar')).toMatchInlineSnapshot( + `/build/oss/kibana-8.0.0-linux-x86_64/foo/bar` + ); + }); +}); + +describe('#getPlatformArchivePath()', () => { + it('creates correct path for different platforms', () => { + expect(ossBuild.getPlatformArchivePath(linuxPlatform)).toMatchInlineSnapshot( + `/target/kibana-oss-8.0.0-linux-x86_64.tar.gz` + ); + expect(ossBuild.getPlatformArchivePath(linuxArmPlatform)).toMatchInlineSnapshot( + `/target/kibana-oss-8.0.0-linux-aarch64.tar.gz` + ); + expect(ossBuild.getPlatformArchivePath(windowsPlatform)).toMatchInlineSnapshot( + `/target/kibana-oss-8.0.0-windows-x86_64.zip` + ); + }); +}); diff --git a/src/dev/build/lib/build.ts b/src/dev/build/lib/build.ts new file mode 100644 index 0000000000000..d0b03b4c5e4b2 --- /dev/null +++ b/src/dev/build/lib/build.ts @@ -0,0 +1,63 @@ +/* + * 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 chalk from 'chalk'; + +import { Config } from './config'; +import { Platform } from './platform'; + +export class Build { + private name = this.oss ? 'kibana-oss' : 'kibana'; + private logTag = this.oss ? chalk`{magenta [kibana-oss]}` : chalk`{cyan [ kibana ]}`; + + constructor(private config: Config, private oss: boolean) {} + + isOss() { + return !!this.oss; + } + + resolvePath(...args: string[]) { + return this.config.resolveFromRepo('build', this.name, ...args); + } + + resolvePathForPlatform(platform: Platform, ...args: string[]) { + return this.config.resolveFromRepo( + 'build', + this.oss ? 'oss' : 'default', + `kibana-${this.config.getBuildVersion()}-${platform.getBuildName()}`, + ...args + ); + } + + getPlatformArchivePath(platform: Platform) { + const ext = platform.isWindows() ? 'zip' : 'tar.gz'; + return this.config.resolveFromRepo( + 'target', + `${this.name}-${this.config.getBuildVersion()}-${platform.getBuildName()}.${ext}` + ); + } + + getName() { + return this.name; + } + + getLogTag() { + return this.logTag; + } +} diff --git a/src/dev/build/lib/config.js b/src/dev/build/lib/config.js deleted file mode 100644 index 36621f1c2d4ac..0000000000000 --- a/src/dev/build/lib/config.js +++ /dev/null @@ -1,168 +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 { dirname, resolve, relative } from 'path'; -import os from 'os'; - -import { getVersionInfo } from './version_info'; -import { createPlatform } from './platform'; - -export async function getConfig({ isRelease, targetAllPlatforms, versionQualifier }) { - const pkgPath = resolve(__dirname, '../../../../package.json'); - const pkg = require(pkgPath); // eslint-disable-line import/no-dynamic-require - const repoRoot = dirname(pkgPath); - const nodeVersion = pkg.engines.node; - - const platforms = [ - createPlatform('linux', 'x64', 'linux-x86_64'), - createPlatform('linux', 'arm64', 'linux-aarch64'), - createPlatform('darwin', 'x64', 'darwin-x86_64'), - createPlatform('win32', 'x64', 'windows-x86_64'), - ]; - - const versionInfo = await getVersionInfo({ - isRelease, - versionQualifier, - pkg, - }); - - return new (class Config { - /** - * Get Kibana's parsed package.json file - * @return {Object} - */ - getKibanaPkg() { - return pkg; - } - - isRelease() { - return isRelease; - } - - /** - * Get the node version required by Kibana - * @return {String} - */ - getNodeVersion() { - return nodeVersion; - } - - /** - * Convert an absolute path to a relative path, based from the repo - * @param {String} absolutePath - * @return {String} - */ - getRepoRelativePath(absolutePath) { - return relative(repoRoot, absolutePath); - } - - /** - * Resolve a set of relative paths based from the directory of the Kibana repo - * @param {...String} ...subPaths - * @return {String} - */ - resolveFromRepo(...subPaths) { - return resolve(repoRoot, ...subPaths); - } - - /** - * Return the list of Platforms we are targeting, if --this-platform flag is - * specified only the platform for this OS will be returned - * @return {Array} - */ - getTargetPlatforms() { - if (targetAllPlatforms) { - return platforms; - } - - return [this.getPlatformForThisOs()]; - } - - /** - * Return the list of Platforms we need/have node downloads for. We always - * include the linux platform even if we aren't targeting linux so we can - * reliably get the LICENSE file, which isn't included in the windows version - * @return {Array} - */ - getNodePlatforms() { - if (targetAllPlatforms) { - return platforms; - } - - if (process.platform === 'linux') { - return [this.getPlatform('linux', 'x64')]; - } - - return [this.getPlatformForThisOs(), this.getPlatform('linux', 'x64')]; - } - - getPlatform(name, arch) { - const selected = platforms.find((p) => { - return name === p.getName() && arch === p.getArchitecture(); - }); - - if (!selected) { - throw new Error(`Unable to find platform (${name}) with architecture (${arch})`); - } - - return selected; - } - - /** - * Get the platform object representing the OS on this machine - * @return {Platform} - */ - getPlatformForThisOs() { - return this.getPlatform(os.platform(), os.arch()); - } - - /** - * Get the version to use for this build - * @return {String} - */ - getBuildVersion() { - return versionInfo.buildVersion; - } - - /** - * Get the build number of this build - * @return {Number} - */ - getBuildNumber() { - return versionInfo.buildNumber; - } - - /** - * Get the git sha for this build - * @return {String} - */ - getBuildSha() { - return versionInfo.buildSha; - } - - /** - * Resolve a set of paths based from the target directory for this build. - * @param {...String} ...subPaths - * @return {String} - */ - resolveFromTarget(...subPaths) { - return resolve(repoRoot, 'target', ...subPaths); - } - })(); -} diff --git a/src/dev/build/lib/config.test.ts b/src/dev/build/lib/config.test.ts new file mode 100644 index 0000000000000..0539adc840a6a --- /dev/null +++ b/src/dev/build/lib/config.test.ts @@ -0,0 +1,201 @@ +/* + * 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 { resolve } from 'path'; + +import { createAbsolutePathSerializer, REPO_ROOT } from '@kbn/dev-utils'; + +import pkg from '../../../../package.json'; +import { Config } from './config'; + +jest.mock('./version_info', () => ({ + getVersionInfo: () => ({ + buildSha: 'abc1234', + buildVersion: '8.0.0', + buildNumber: 1234, + }), +})); + +const versionInfo = jest.requireMock('./version_info').getVersionInfo(); + +expect.addSnapshotSerializer(createAbsolutePathSerializer()); + +const setup = async ({ targetAllPlatforms = true }: { targetAllPlatforms?: boolean } = {}) => { + return await Config.create({ + isRelease: true, + targetAllPlatforms, + }); +}; + +describe('#getKibanaPkg()', () => { + it('returns the parsed package.json from the Kibana repo', async () => { + const config = await setup(); + expect(config.getKibanaPkg()).toEqual(pkg); + }); +}); + +describe('#getNodeVersion()', () => { + it('returns the node version from the kibana package.json', async () => { + const config = await setup(); + expect(config.getNodeVersion()).toEqual(pkg.engines.node); + }); +}); + +describe('#getRepoRelativePath()', () => { + it('converts an absolute path to relative path, from the root of the repo', async () => { + const config = await setup(); + expect(config.getRepoRelativePath(__dirname)).toMatchInlineSnapshot(`"src/dev/build/lib"`); + }); +}); + +describe('#resolveFromRepo()', () => { + it('resolves a relative path', async () => { + const config = await setup(); + expect(config.resolveFromRepo('src/dev/build')).toMatchInlineSnapshot( + `/src/dev/build` + ); + }); + + it('resolves a series of relative paths', async () => { + const config = await setup(); + expect(config.resolveFromRepo('src', 'dev', 'build')).toMatchInlineSnapshot( + `/src/dev/build` + ); + }); +}); + +describe('#getPlatform()', () => { + it('throws error when platform does not exist', async () => { + const config = await setup(); + expect(() => { + config.getPlatform( + // @ts-expect-error invalid platform name + 'foo', + 'x64' + ); + }).toThrowErrorMatchingInlineSnapshot( + `"Unable to find platform (foo) with architecture (x64)"` + ); + }); + + it('throws error when architecture does not exist', async () => { + const config = await setup(); + expect(() => { + config.getPlatform( + 'linux', + // @ts-expect-error invalid platform arch + 'foo' + ); + }).toThrowErrorMatchingInlineSnapshot( + `"Unable to find platform (linux) with architecture (foo)"` + ); + }); +}); + +describe('#getTargetPlatforms()', () => { + it('returns an array of all platform objects', async () => { + const config = await setup(); + expect( + config + .getTargetPlatforms() + .map((p) => p.getNodeArch()) + .sort() + ).toMatchInlineSnapshot(` + Array [ + "darwin-x64", + "linux-arm64", + "linux-x64", + "win32-x64", + ] + `); + }); + + it('returns just this platform when targetAllPlatforms = false', async () => { + const config = await setup({ + targetAllPlatforms: false, + }); + + expect(config.getTargetPlatforms()).toEqual([config.getPlatformForThisOs()]); + }); +}); + +describe('#getNodePlatforms()', () => { + it('returns all platforms', async () => { + const config = await setup(); + expect( + config + .getTargetPlatforms() + .map((p) => p.getNodeArch()) + .sort() + ).toEqual(['darwin-x64', 'linux-arm64', 'linux-x64', 'win32-x64']); + }); + + it('returns this platform and linux, when targetAllPlatforms = false', async () => { + const config = await setup({ + targetAllPlatforms: false, + }); + const platforms = config.getNodePlatforms(); + expect(platforms).toBeInstanceOf(Array); + if (process.platform !== 'linux') { + expect(platforms).toHaveLength(2); + expect(platforms[0]).toBe(config.getPlatformForThisOs()); + expect(platforms[1]).toBe(config.getPlatform('linux', 'x64')); + } else { + expect(platforms).toHaveLength(1); + expect(platforms[0]).toBe(config.getPlatform('linux', 'x64')); + } + }); +}); + +describe('#getPlatformForThisOs()', () => { + it('returns the platform that matches the arch of this machine', async () => { + const config = await setup(); + const currentPlatform = config.getPlatformForThisOs(); + expect(currentPlatform.getName()).toBe(process.platform); + expect(currentPlatform.getArchitecture()).toBe(process.arch); + }); +}); + +describe('#getBuildVersion()', () => { + it('returns the version from the build info', async () => { + const config = await setup(); + expect(config.getBuildVersion()).toBe(versionInfo.buildVersion); + }); +}); + +describe('#getBuildNumber()', () => { + it('returns the number from the build info', async () => { + const config = await setup(); + expect(config.getBuildNumber()).toBe(versionInfo.buildNumber); + }); +}); + +describe('#getBuildSha()', () => { + it('returns the sha from the build info', async () => { + const config = await setup(); + expect(config.getBuildSha()).toBe(versionInfo.buildSha); + }); +}); + +describe('#resolveFromTarget()', () => { + it('resolves a relative path, from the target directory', async () => { + const config = await setup(); + expect(config.resolveFromTarget()).toBe(resolve(REPO_ROOT, 'target')); + }); +}); diff --git a/src/dev/build/lib/config.ts b/src/dev/build/lib/config.ts new file mode 100644 index 0000000000000..338c89b1930d8 --- /dev/null +++ b/src/dev/build/lib/config.ts @@ -0,0 +1,173 @@ +/* + * 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 { dirname, resolve, relative } from 'path'; +import os from 'os'; +import loadJsonFile from 'load-json-file'; + +import { getVersionInfo, VersionInfo } from './version_info'; +import { PlatformName, PlatformArchitecture, ALL_PLATFORMS } from './platform'; + +interface Options { + isRelease: boolean; + targetAllPlatforms: boolean; + versionQualifier?: string; +} + +interface Package { + version: string; + engines: { node: string }; + workspaces: { + packages: string[]; + }; + [key: string]: unknown; +} + +export class Config { + static async create({ isRelease, targetAllPlatforms, versionQualifier }: Options) { + const pkgPath = resolve(__dirname, '../../../../package.json'); + const pkg: Package = loadJsonFile.sync(pkgPath); + + return new Config( + targetAllPlatforms, + pkg, + pkg.engines.node, + dirname(pkgPath), + await getVersionInfo({ + isRelease, + versionQualifier, + pkg, + }), + isRelease + ); + } + + constructor( + private readonly targetAllPlatforms: boolean, + private readonly pkg: Package, + private readonly nodeVersion: string, + private readonly repoRoot: string, + private readonly versionInfo: VersionInfo, + public readonly isRelease: boolean + ) {} + + /** + * Get Kibana's parsed package.json file + */ + getKibanaPkg() { + return this.pkg; + } + + /** + * Get the node version required by Kibana + */ + getNodeVersion() { + return this.nodeVersion; + } + + /** + * Convert an absolute path to a relative path, based from the repo + */ + getRepoRelativePath(absolutePath: string) { + return relative(this.repoRoot, absolutePath); + } + + /** + * Resolve a set of relative paths based from the directory of the Kibana repo + */ + resolveFromRepo(...subPaths: string[]) { + return resolve(this.repoRoot, ...subPaths); + } + + /** + * Return the list of Platforms we are targeting, if --this-platform flag is + * specified only the platform for this OS will be returned + */ + getTargetPlatforms() { + if (this.targetAllPlatforms) { + return ALL_PLATFORMS; + } + + return [this.getPlatformForThisOs()]; + } + + /** + * Return the list of Platforms we need/have node downloads for. We always + * include the linux platform even if we aren't targeting linux so we can + * reliably get the LICENSE file, which isn't included in the windows version + */ + getNodePlatforms() { + if (this.targetAllPlatforms) { + return ALL_PLATFORMS; + } + + if (process.platform === 'linux') { + return [this.getPlatform('linux', 'x64')]; + } + + return [this.getPlatformForThisOs(), this.getPlatform('linux', 'x64')]; + } + + getPlatform(name: PlatformName, arch: PlatformArchitecture) { + const selected = ALL_PLATFORMS.find((p) => { + return name === p.getName() && arch === p.getArchitecture(); + }); + + if (!selected) { + throw new Error(`Unable to find platform (${name}) with architecture (${arch})`); + } + + return selected; + } + + /** + * Get the platform object representing the OS on this machine + */ + getPlatformForThisOs() { + return this.getPlatform(os.platform() as PlatformName, os.arch() as PlatformArchitecture); + } + + /** + * Get the version to use for this build + */ + getBuildVersion() { + return this.versionInfo.buildVersion; + } + + /** + * Get the build number of this build + */ + getBuildNumber() { + return this.versionInfo.buildNumber; + } + + /** + * Get the git sha for this build + */ + getBuildSha() { + return this.versionInfo.buildSha; + } + + /** + * Resolve a set of paths based from the target directory for this build. + */ + resolveFromTarget(...subPaths: string[]) { + return resolve(this.repoRoot, 'target', ...subPaths); + } +} diff --git a/src/dev/build/lib/download.js b/src/dev/build/lib/download.ts similarity index 81% rename from src/dev/build/lib/download.js rename to src/dev/build/lib/download.ts index fbd2d47ff7b06..7c1618b833b45 100644 --- a/src/dev/build/lib/download.js +++ b/src/dev/build/lib/download.ts @@ -23,10 +23,15 @@ import { dirname } from 'path'; import chalk from 'chalk'; import { createHash } from 'crypto'; import Axios from 'axios'; +import { ToolingLog } from '@kbn/dev-utils'; + +// https://github.com/axios/axios/tree/ffea03453f77a8176c51554d5f6c3c6829294649/lib/adapters +// @ts-expect-error untyped internal module used to prevent axios from using xhr adapter in tests +import AxiosHttpAdapter from 'axios/lib/adapters/http'; import { mkdirp } from './fs'; -function tryUnlink(path) { +function tryUnlink(path: string) { try { unlinkSync(path); } catch (error) { @@ -36,7 +41,14 @@ function tryUnlink(path) { } } -export async function download(options) { +interface DownloadOptions { + log: ToolingLog; + url: string; + destination: string; + sha256: string; + retries?: number; +} +export async function download(options: DownloadOptions): Promise { const { log, url, destination, sha256, retries = 0 } = options; if (!sha256) { @@ -52,8 +64,9 @@ export async function download(options) { log.debug(`Attempting download of ${url}`, chalk.dim(sha256)); const response = await Axios.request({ - url: url, + url, responseType: 'stream', + adapter: AxiosHttpAdapter, }); if (response.status !== 200) { @@ -62,7 +75,7 @@ export async function download(options) { const hash = createHash('sha256'); await new Promise((resolve, reject) => { - response.data.on('data', (chunk) => { + response.data.on('data', (chunk: Buffer) => { hash.update(chunk); writeSync(fileHandle, chunk); }); diff --git a/src/dev/build/lib/__tests__/errors.js b/src/dev/build/lib/errors.test.ts similarity index 67% rename from src/dev/build/lib/__tests__/errors.js rename to src/dev/build/lib/errors.test.ts index dc23b3e372bc6..0bf96463555fe 100644 --- a/src/dev/build/lib/__tests__/errors.js +++ b/src/dev/build/lib/errors.test.ts @@ -17,28 +17,26 @@ * under the License. */ -import expect from '@kbn/expect'; - -import { isErrorLogged, markErrorLogged } from '../errors'; +import { isErrorLogged, markErrorLogged } from './errors'; describe('dev/build/lib/errors', () => { describe('isErrorLogged()/markErrorLogged()', () => { it('returns true if error has been passed to markErrorLogged()', () => { const error = new Error(); - expect(isErrorLogged(error)).to.be(false); + expect(isErrorLogged(error)).toBe(false); markErrorLogged(error); - expect(isErrorLogged(error)).to.be(true); + expect(isErrorLogged(error)).toBe(true); }); describe('isErrorLogged()', () => { it('handles any value type', () => { - expect(isErrorLogged(null)).to.be(false); - expect(isErrorLogged(undefined)).to.be(false); - expect(isErrorLogged(1)).to.be(false); - expect(isErrorLogged([])).to.be(false); - expect(isErrorLogged({})).to.be(false); - expect(isErrorLogged(/foo/)).to.be(false); - expect(isErrorLogged(new Date())).to.be(false); + expect(isErrorLogged(null)).toBe(false); + expect(isErrorLogged(undefined)).toBe(false); + expect(isErrorLogged(1)).toBe(false); + expect(isErrorLogged([])).toBe(false); + expect(isErrorLogged({})).toBe(false); + expect(isErrorLogged(/foo/)).toBe(false); + expect(isErrorLogged(new Date())).toBe(false); }); }); }); diff --git a/src/dev/build/lib/errors.js b/src/dev/build/lib/errors.ts similarity index 86% rename from src/dev/build/lib/errors.js rename to src/dev/build/lib/errors.ts index 7fb8e2dc070d1..8405e9d29a033 100644 --- a/src/dev/build/lib/errors.js +++ b/src/dev/build/lib/errors.ts @@ -17,13 +17,13 @@ * under the License. */ -const loggedErrors = new WeakSet(); +const loggedErrors = new WeakSet(); -export function markErrorLogged(error) { +export function markErrorLogged(error: T): T { loggedErrors.add(error); return error; } -export function isErrorLogged(error) { +export function isErrorLogged(error: any) { return loggedErrors.has(error); } diff --git a/src/dev/build/lib/exec.test.ts b/src/dev/build/lib/exec.test.ts new file mode 100644 index 0000000000000..6f6ec4f26afbb --- /dev/null +++ b/src/dev/build/lib/exec.test.ts @@ -0,0 +1,67 @@ +/* + * 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 Path from 'path'; + +import { + ToolingLog, + ToolingLogCollectingWriter, + createStripAnsiSerializer, + createRecursiveSerializer, +} from '@kbn/dev-utils'; + +import { exec } from './exec'; + +const testWriter = new ToolingLogCollectingWriter(); +const log = new ToolingLog(); +log.setWriters([testWriter]); + +expect.addSnapshotSerializer(createStripAnsiSerializer()); +expect.addSnapshotSerializer( + createRecursiveSerializer( + (v) => v.includes(process.execPath), + (v) => v.split(Path.dirname(process.execPath)).join('') + ) +); + +beforeEach(() => { + testWriter.messages.length = 0; +}); + +it('executes a command, logs the command, and logs the output', async () => { + await exec(log, process.execPath, ['-e', 'console.log("hi")']); + expect(testWriter.messages).toMatchInlineSnapshot(` + Array [ + " debg $ /node -e console.log(\\"hi\\")", + " debg hi", + ] + `); +}); + +it('logs using level: option', async () => { + await exec(log, process.execPath, ['-e', 'console.log("hi")'], { + level: 'info', + }); + expect(testWriter.messages).toMatchInlineSnapshot(` + Array [ + " info $ /node -e console.log(\\"hi\\")", + " info hi", + ] + `); +}); diff --git a/src/dev/build/lib/exec.js b/src/dev/build/lib/exec.ts similarity index 73% rename from src/dev/build/lib/exec.js rename to src/dev/build/lib/exec.ts index 5e47500c72c5c..c3870230b8f31 100644 --- a/src/dev/build/lib/exec.js +++ b/src/dev/build/lib/exec.ts @@ -19,12 +19,23 @@ import execa from 'execa'; import chalk from 'chalk'; +import { ToolingLog, LogLevel } from '@kbn/dev-utils'; -import { watchStdioForLine } from '../../../legacy/utils'; +import { watchStdioForLine } from './watch_stdio_for_line'; -export async function exec(log, cmd, args, options = {}) { - const { level = 'debug', cwd, env, exitAfter } = options; +interface Options { + level?: Exclude; + cwd?: string; + env?: Record; + exitAfter?: RegExp; +} +export async function exec( + log: ToolingLog, + cmd: string, + args: string[], + { level = 'debug', cwd, env, exitAfter }: Options = {} +) { log[level](chalk.dim('$'), cmd, ...args); const proc = execa(cmd, args, { diff --git a/src/dev/build/lib/fs.js b/src/dev/build/lib/fs.ts similarity index 56% rename from src/dev/build/lib/fs.js rename to src/dev/build/lib/fs.ts index b905f40d0de1e..d86901c41e436 100644 --- a/src/dev/build/lib/fs.js +++ b/src/dev/build/lib/fs.ts @@ -17,28 +17,31 @@ * under the License. */ -import archiver from 'archiver'; import fs from 'fs'; import { createHash } from 'crypto'; +import { pipeline, Writable } from 'stream'; import { resolve, dirname, isAbsolute, sep } from 'path'; import { createGunzip } from 'zlib'; -import { inspect } from 'util'; +import { inspect, promisify } from 'util'; +import archiver from 'archiver'; import vfs from 'vinyl-fs'; -import { promisify } from 'bluebird'; +import File from 'vinyl'; import del from 'del'; import deleteEmpty from 'delete-empty'; -import { createPromiseFromStreams, createMapStream } from '../../../legacy/utils'; - -import tar from 'tar'; +import tar, { ExtractOptions } from 'tar'; +import { ToolingLog } from '@kbn/dev-utils'; +const pipelineAsync = promisify(pipeline); const mkdirAsync = promisify(fs.mkdir); const writeFileAsync = promisify(fs.writeFile); const readFileAsync = promisify(fs.readFile); const readdirAsync = promisify(fs.readdir); const utimesAsync = promisify(fs.utimes); +const copyFileAsync = promisify(fs.copyFile); +const statAsync = promisify(fs.stat); -export function assertAbsolute(path) { +export function assertAbsolute(path: string) { if (!isAbsolute(path)) { throw new TypeError( 'Please use absolute paths to keep things explicit. You probably want to use `build.resolvePath()` or `config.resolveFromRepo()`.' @@ -46,7 +49,7 @@ export function assertAbsolute(path) { } } -export function isFileAccessible(path) { +export function isFileAccessible(path: string) { assertAbsolute(path); try { @@ -57,35 +60,35 @@ export function isFileAccessible(path) { } } -function longInspect(value) { +function longInspect(value: any) { return inspect(value, { maxArrayLength: Infinity, }); } -export async function mkdirp(path) { +export async function mkdirp(path: string) { assertAbsolute(path); await mkdirAsync(path, { recursive: true }); } -export async function write(path, contents) { +export async function write(path: string, contents: string) { assertAbsolute(path); await mkdirp(dirname(path)); await writeFileAsync(path, contents); } -export async function read(path) { +export async function read(path: string) { assertAbsolute(path); return await readFileAsync(path, 'utf8'); } -export async function getChildPaths(path) { +export async function getChildPaths(path: string) { assertAbsolute(path); const childNames = await readdirAsync(path); return childNames.map((name) => resolve(path, name)); } -export async function deleteAll(patterns, log) { +export async function deleteAll(patterns: string[], log: ToolingLog) { if (!Array.isArray(patterns)) { throw new TypeError('Expected patterns to be an array'); } @@ -108,7 +111,11 @@ export async function deleteAll(patterns, log) { } } -export async function deleteEmptyFolders(log, rootFolderPath, foldersToKeep) { +export async function deleteEmptyFolders( + log: ToolingLog, + rootFolderPath: string, + foldersToKeep: string[] +) { if (typeof rootFolderPath !== 'string') { throw new TypeError('Expected root folder to be a string path'); } @@ -121,7 +128,11 @@ export async function deleteEmptyFolders(log, rootFolderPath, foldersToKeep) { // Delete empty is used to gather all the empty folders and // then we use del to actually delete them - const emptyFoldersList = await deleteEmpty(rootFolderPath, { dryRun: true }); + const emptyFoldersList = await deleteEmpty(rootFolderPath, { + // @ts-expect-error DT package has incorrect types https://github.com/jonschlinkert/delete-empty/blob/6ae34547663e6845c3c98b184c606fa90ef79c0a/index.js#L160 + dryRun: true, + }); + const foldersToDelete = emptyFoldersList.filter((folderToDelete) => { return !foldersToKeep.some((folderToKeep) => folderToDelete.includes(folderToKeep)); }); @@ -133,85 +144,153 @@ export async function deleteEmptyFolders(log, rootFolderPath, foldersToKeep) { log.verbose('Deleted:', longInspect(deletedEmptyFolders)); } -export async function copyAll(sourceDir, destination, options = {}) { - const { select = ['**/*'], dot = false, time } = options; +interface CopyOptions { + clone?: boolean; +} +export async function copy(source: string, destination: string, options: CopyOptions = {}) { + assertAbsolute(source); + assertAbsolute(destination); + + // ensure source exists before creating destination directory and copying source + await statAsync(source); + await mkdirp(dirname(destination)); + return await copyFileAsync( + source, + destination, + options.clone ? fs.constants.COPYFILE_FICLONE : 0 + ); +} + +interface CopyAllOptions { + select?: string[]; + dot?: boolean; + time?: string | number | Date; +} + +export async function copyAll( + sourceDir: string, + destination: string, + options: CopyAllOptions = {} +) { + const { select = ['**/*'], dot = false, time = Date.now() } = options; assertAbsolute(sourceDir); assertAbsolute(destination); - await createPromiseFromStreams([ + await pipelineAsync( vfs.src(select, { buffer: false, cwd: sourceDir, base: sourceDir, dot, }), - vfs.dest(destination), - ]); + vfs.dest(destination) + ); // we must update access and modified file times after the file copy // has completed, otherwise the copy action can effect modify times. if (Boolean(time)) { - await createPromiseFromStreams([ + await pipelineAsync( vfs.src(select, { buffer: false, cwd: destination, base: destination, dot, }), - createMapStream((file) => utimesAsync(file.path, time, time)), - ]); + new Writable({ + objectMode: true, + write(file: File, _, cb) { + utimesAsync(file.path, time, time).then(() => cb(), cb); + }, + }) + ); } } -export async function getFileHash(path, algo) { +export async function getFileHash(path: string, algo: string) { assertAbsolute(path); const hash = createHash(algo); const readStream = fs.createReadStream(path); - await new Promise((resolve, reject) => { + await new Promise((res, rej) => { readStream .on('data', (chunk) => hash.update(chunk)) - .on('error', reject) - .on('end', resolve); + .on('error', rej) + .on('end', res); }); return hash.digest('hex'); } -export async function untar(source, destination, extractOptions = {}) { +export async function untar( + source: string, + destination: string, + extractOptions: ExtractOptions = {} +) { assertAbsolute(source); assertAbsolute(destination); await mkdirAsync(destination, { recursive: true }); - await createPromiseFromStreams([ + await pipelineAsync( fs.createReadStream(source), createGunzip(), tar.extract({ ...extractOptions, cwd: destination, - }), - ]); + }) + ); } -export async function gunzip(source, destination) { +export async function gunzip(source: string, destination: string) { assertAbsolute(source); assertAbsolute(destination); await mkdirAsync(dirname(destination), { recursive: true }); - await createPromiseFromStreams([ + await pipelineAsync( fs.createReadStream(source), createGunzip(), - fs.createWriteStream(destination), - ]); + fs.createWriteStream(destination) + ); +} + +interface CompressTarOptions { + createRootDirectory: boolean; + source: string; + destination: string; + archiverOptions?: archiver.TarOptions & archiver.CoreOptions; } +export async function compressTar({ + source, + destination, + archiverOptions, + createRootDirectory, +}: CompressTarOptions) { + const output = fs.createWriteStream(destination); + const archive = archiver('tar', archiverOptions); + const name = createRootDirectory ? source.split(sep).slice(-1)[0] : false; + + archive.pipe(output); -export async function compress(type, options = {}, source, destination) { + return archive.directory(source, name).finalize(); +} + +interface CompressZipOptions { + createRootDirectory: boolean; + source: string; + destination: string; + archiverOptions?: archiver.ZipOptions & archiver.CoreOptions; +} +export async function compressZip({ + source, + destination, + archiverOptions, + createRootDirectory, +}: CompressZipOptions) { const output = fs.createWriteStream(destination); - const archive = archiver(type, options.archiverOptions); - const name = options.createRootDirectory ? source.split(sep).slice(-1)[0] : false; + const archive = archiver('zip', archiverOptions); + const name = createRootDirectory ? source.split(sep).slice(-1)[0] : false; archive.pipe(output); diff --git a/src/dev/build/lib/index.js b/src/dev/build/lib/index.js deleted file mode 100644 index 6540db6f37a72..0000000000000 --- a/src/dev/build/lib/index.js +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -export { getConfig } from './config'; -export { createRunner } from './runner'; -export { isErrorLogged } from './errors'; -export { exec } from './exec'; -export { - read, - write, - mkdirp, - copyAll, - getFileHash, - untar, - gunzip, - deleteAll, - deleteEmptyFolders, - compress, - isFileAccessible, -} from './fs'; -export { download } from './download'; -export { scanDelete } from './scan_delete'; -export { scanCopy } from './scan_copy'; diff --git a/src/plugins/status_page/public/index.ts b/src/dev/build/lib/index.ts similarity index 73% rename from src/plugins/status_page/public/index.ts rename to src/dev/build/lib/index.ts index db1f05cac076f..339dc41cc6ccf 100644 --- a/src/plugins/status_page/public/index.ts +++ b/src/dev/build/lib/index.ts @@ -17,8 +17,14 @@ * under the License. */ -import { PluginInitializer } from 'kibana/public'; -import { StatusPagePlugin, StatusPagePluginSetup, StatusPagePluginStart } from './plugin'; - -export const plugin: PluginInitializer = () => - new StatusPagePlugin(); +export * from './config'; +export * from './build'; +export * from './runner'; +export * from './errors'; +export * from './exec'; +export * from './fs'; +export * from './download'; +export * from './scan_delete'; +export * from './scan_copy'; +export * from './platform'; +export * from './scan'; diff --git a/src/dev/build/lib/integration_tests/download.test.ts b/src/dev/build/lib/integration_tests/download.test.ts new file mode 100644 index 0000000000000..a86d5292501f5 --- /dev/null +++ b/src/dev/build/lib/integration_tests/download.test.ts @@ -0,0 +1,226 @@ +/* + * 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 { createServer, IncomingMessage, ServerResponse } from 'http'; +import { join } from 'path'; +import { tmpdir } from 'os'; +import { readFileSync } from 'fs'; + +import del from 'del'; +import { CI_PARALLEL_PROCESS_PREFIX } from '@kbn/test'; +import { ToolingLog } from '@kbn/dev-utils'; + +import { mkdirp } from '../fs'; +import { download } from '../download'; + +const TMP_DIR = join(tmpdir(), CI_PARALLEL_PROCESS_PREFIX, 'download-js-test-tmp-dir'); +const TMP_DESTINATION = join(TMP_DIR, '__tmp_download_js_test_file__'); + +beforeEach(async () => { + await del(TMP_DIR, { force: true }); + await mkdirp(TMP_DIR); + jest.clearAllMocks(); +}); + +afterEach(async () => { + await del(TMP_DIR, { force: true }); +}); + +const onLogLine = jest.fn(); +const log = new ToolingLog({ + level: 'verbose', + writeTo: { + write: onLogLine, + }, +}); + +type Handler = (req: IncomingMessage, res: ServerResponse) => void; + +const FOO_SHA256 = '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'; +const createSendHandler = (send: any): Handler => (req, res) => { + res.statusCode = 200; + res.end(send); +}; +const sendErrorHandler: Handler = (req, res) => { + res.statusCode = 500; + res.end(); +}; + +let serverUrl: string; +let nextHandler: Handler | null = null; +const server = createServer((req, res) => { + if (!nextHandler) { + nextHandler = sendErrorHandler; + } + + const handler = nextHandler; + nextHandler = null; + handler(req, res); +}); + +afterEach(() => (nextHandler = null)); + +beforeAll(async () => { + await Promise.race([ + new Promise((_, reject) => { + server.once('error', reject); + }), + new Promise((resolve) => { + server.listen(resolve); + }), + ]); + + // address is only a string when listening to a UNIX socket, and undefined when we haven't called listen() yet + const address = server.address() as { port: number }; + + serverUrl = `http://localhost:${address.port}/`; +}); + +afterAll(async () => { + server.close(); +}); + +it('downloads from URL and checks that content matches sha256', async () => { + nextHandler = createSendHandler('foo'); + await download({ + log, + url: serverUrl, + destination: TMP_DESTINATION, + sha256: FOO_SHA256, + }); + expect(readFileSync(TMP_DESTINATION, 'utf8')).toBe('foo'); +}); + +it('rejects and deletes destination if sha256 does not match', async () => { + nextHandler = createSendHandler('foo'); + + try { + await download({ + log, + url: serverUrl, + destination: TMP_DESTINATION, + sha256: 'bar', + }); + throw new Error('Expected download() to reject'); + } catch (error) { + expect(error).toHaveProperty( + 'message', + expect.stringContaining('does not match the expected sha256 checksum') + ); + } + + try { + readFileSync(TMP_DESTINATION); + throw new Error('Expected download to be deleted'); + } catch (error) { + expect(error).toHaveProperty('code', 'ENOENT'); + } +}); + +describe('reties download retries: number of times', () => { + it('resolves if retries = 1 and first attempt fails', async () => { + let reqCount = 0; + nextHandler = function sequenceHandler(req, res) { + switch (++reqCount) { + case 1: + nextHandler = sequenceHandler; + return sendErrorHandler(req, res); + default: + return createSendHandler('foo')(req, res); + } + }; + + await download({ + log, + url: serverUrl, + destination: TMP_DESTINATION, + sha256: FOO_SHA256, + retries: 2, + }); + + expect(readFileSync(TMP_DESTINATION, 'utf8')).toBe('foo'); + }); + + it('resolves if first fails, second is bad shasum, but third succeeds', async () => { + let reqCount = 0; + nextHandler = function sequenceHandler(req, res) { + switch (++reqCount) { + case 1: + nextHandler = sequenceHandler; + return sendErrorHandler(req, res); + case 2: + nextHandler = sequenceHandler; + return createSendHandler('bar')(req, res); + default: + return createSendHandler('foo')(req, res); + } + }; + + await download({ + log, + url: serverUrl, + destination: TMP_DESTINATION, + sha256: FOO_SHA256, + retries: 2, + }); + }); + + it('makes 6 requests if `retries: 5` and all failed', async () => { + let reqCount = 0; + nextHandler = function sequenceHandler(req, res) { + reqCount += 1; + nextHandler = sequenceHandler; + sendErrorHandler(req, res); + }; + + try { + await download({ + log, + url: serverUrl, + destination: TMP_DESTINATION, + sha256: FOO_SHA256, + retries: 5, + }); + throw new Error('Expected download() to reject'); + } catch (error) { + expect(error).toHaveProperty( + 'message', + expect.stringContaining('Request failed with status code 500') + ); + expect(reqCount).toBe(6); + } + }); +}); + +describe('sha256 option not supplied', () => { + it('refuses to download', async () => { + try { + // @ts-expect-error missing sha256 param is intentional + await download({ + log, + url: 'http://google.com', + destination: TMP_DESTINATION, + }); + + throw new Error('expected download() to reject'); + } catch (error) { + expect(error).toHaveProperty('message', expect.stringContaining('refusing to download')); + } + }); +}); diff --git a/src/dev/build/lib/integration_tests/fs.test.ts b/src/dev/build/lib/integration_tests/fs.test.ts new file mode 100644 index 0000000000000..e9ce09554159b --- /dev/null +++ b/src/dev/build/lib/integration_tests/fs.test.ts @@ -0,0 +1,358 @@ +/* + * 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 { resolve } from 'path'; +import { chmodSync, statSync } from 'fs'; + +import del from 'del'; + +import { mkdirp, write, read, getChildPaths, copyAll, getFileHash, untar, gunzip } from '../fs'; + +const TMP = resolve(__dirname, '../__tmp__'); +const FIXTURES = resolve(__dirname, '../__fixtures__'); +const FOO_TAR_PATH = resolve(FIXTURES, 'foo_dir.tar.gz'); +const FOO_GZIP_PATH = resolve(FIXTURES, 'foo.txt.gz'); +const BAR_TXT_PATH = resolve(FIXTURES, 'foo_dir/bar.txt'); +const WORLD_EXECUTABLE = resolve(FIXTURES, 'bin/world_executable'); + +const isWindows = /^win/.test(process.platform); + +// get the mode of a file as a string, like 777, or 644, +function getCommonMode(path: string) { + return statSync(path).mode.toString(8).slice(-3); +} + +function assertNonAbsoluteError(error: any) { + expect(error).toBeInstanceOf(Error); + expect(error.message).toContain('Please use absolute paths'); +} + +// ensure WORLD_EXECUTABLE is actually executable by all +beforeAll(async () => { + chmodSync(WORLD_EXECUTABLE, 0o777); +}); + +// clean and recreate TMP directory +beforeEach(async () => { + await del(TMP); + await mkdirp(TMP); +}); + +// cleanup TMP directory +afterAll(async () => { + await del(TMP); +}); + +describe('mkdirp()', () => { + it('rejects if path is not absolute', async () => { + try { + await mkdirp('foo/bar'); + throw new Error('Expected mkdirp() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('makes directory and necessary parent directories', async () => { + const destination = resolve(TMP, 'a/b/c/d/e/f/g'); + + expect(await mkdirp(destination)).toBe(undefined); + + expect(statSync(destination).isDirectory()).toBe(true); + }); +}); + +describe('write()', () => { + it('rejects if path is not absolute', async () => { + try { + // @ts-expect-error missing content intentional + await write('foo/bar'); + throw new Error('Expected write() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('writes content to a file with existing parent directory', async () => { + const destination = resolve(TMP, 'a'); + + expect(await write(destination, 'bar')).toBe(undefined); + expect(await read(destination)).toBe('bar'); + }); + + it('writes content to a file with missing parents', async () => { + const destination = resolve(TMP, 'a/b/c/d/e'); + + expect(await write(destination, 'bar')).toBe(undefined); + expect(await read(destination)).toBe('bar'); + }); +}); + +describe('read()', () => { + it('rejects if path is not absolute', async () => { + try { + await read('foo/bar'); + throw new Error('Expected read() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('reads file, resolves with result', async () => { + expect(await read(BAR_TXT_PATH)).toBe('bar\n'); + }); +}); + +describe('getChildPaths()', () => { + it('rejects if path is not absolute', async () => { + try { + await getChildPaths('foo/bar'); + throw new Error('Expected getChildPaths() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('resolves with absolute paths to the children of directory', async () => { + const path = resolve(FIXTURES, 'foo_dir'); + expect((await getChildPaths(path)).sort()).toEqual([ + resolve(FIXTURES, 'foo_dir/.bar'), + BAR_TXT_PATH, + resolve(FIXTURES, 'foo_dir/foo'), + ]); + }); + + it('rejects with ENOENT if path does not exist', async () => { + try { + await getChildPaths(resolve(FIXTURES, 'notrealpath')); + throw new Error('Expected getChildPaths() to reject'); + } catch (error) { + expect(error).toHaveProperty('code', 'ENOENT'); + } + }); +}); + +describe('copyAll()', () => { + it('rejects if source path is not absolute', async () => { + try { + await copyAll('foo/bar', __dirname); + throw new Error('Expected copyAll() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('rejects if destination path is not absolute', async () => { + try { + await copyAll(__dirname, 'foo/bar'); + throw new Error('Expected copyAll() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('rejects if neither path is not absolute', async () => { + try { + await copyAll('foo/bar', 'foo/bar'); + throw new Error('Expected copyAll() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('copies files and directories from source to dest, creating dest if necessary, respecting mode', async () => { + const destination = resolve(TMP, 'a/b/c'); + await copyAll(FIXTURES, destination); + + expect((await getChildPaths(resolve(destination, 'foo_dir'))).sort()).toEqual([ + resolve(destination, 'foo_dir/bar.txt'), + 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'); + }); + + it('applies select globs if specified, ignores dot files', async () => { + const destination = resolve(TMP, 'a/b/c/d'); + await copyAll(FIXTURES, destination, { + select: ['**/*bar*'], + }); + + try { + statSync(resolve(destination, 'bin/world_executable')); + throw new Error('expected bin/world_executable to not by copied'); + } catch (error) { + expect(error).toHaveProperty('code', 'ENOENT'); + } + + try { + statSync(resolve(destination, 'foo_dir/.bar')); + throw new Error('expected foo_dir/.bar to not by copied'); + } catch (error) { + expect(error).toHaveProperty('code', 'ENOENT'); + } + + expect(await read(resolve(destination, 'foo_dir/bar.txt'))).toBe('bar\n'); + }); + + it('supports select globs and dot option together', async () => { + const destination = resolve(TMP, 'a/b/c/d'); + await copyAll(FIXTURES, destination, { + select: ['**/*bar*'], + dot: true, + }); + + try { + statSync(resolve(destination, 'bin/world_executable')); + throw new Error('expected bin/world_executable to not by copied'); + } catch (error) { + expect(error).toHaveProperty('code', 'ENOENT'); + } + + expect(await read(resolve(destination, 'foo_dir/bar.txt'))).toBe('bar\n'); + expect(await read(resolve(destination, 'foo_dir/.bar'))).toBe('dotfile\n'); + }); + + it('supports atime and mtime', async () => { + const destination = resolve(TMP, 'a/b/c/d/e'); + const time = new Date(1425298511000); + await copyAll(FIXTURES, destination, { + time, + }); + const barTxt = statSync(resolve(destination, 'foo_dir/bar.txt')); + const fooDir = statSync(resolve(destination, 'foo_dir')); + + // precision is platform specific + const oneDay = 86400000; + expect(Math.abs(barTxt.atimeMs - time.getTime())).toBeLessThan(oneDay); + expect(Math.abs(fooDir.atimeMs - time.getTime())).toBeLessThan(oneDay); + expect(Math.abs(barTxt.mtimeMs - time.getTime())).toBeLessThan(oneDay); + }); +}); + +describe('getFileHash()', () => { + it('rejects if path is not absolute', async () => { + try { + await getFileHash('foo/bar', 'some content'); + throw new Error('Expected getFileHash() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('resolves with the sha1 hash of a file', async () => { + expect(await getFileHash(BAR_TXT_PATH, 'sha1')).toBe( + 'e242ed3bffccdf271b7fbaf34ed72d089537b42f' + ); + }); + it('resolves with the sha256 hash of a file', async () => { + expect(await getFileHash(BAR_TXT_PATH, 'sha256')).toBe( + '7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730' + ); + }); + it('resolves with the md5 hash of a file', async () => { + expect(await getFileHash(BAR_TXT_PATH, 'md5')).toBe('c157a79031e1c40f85931829bc5fc552'); + }); +}); + +describe('untar()', () => { + it('rejects if source path is not absolute', async () => { + try { + await untar('foo/bar', '**/*'); + throw new Error('Expected untar() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('rejects if destination path is not absolute', async () => { + try { + await untar(__dirname, '**/*'); + throw new Error('Expected untar() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('rejects if neither path is not absolute', async () => { + try { + await untar('foo/bar', '**/*'); + throw new Error('Expected untar() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('extracts tarbar from source into destination, creating destination if necessary', async () => { + const destination = resolve(TMP, 'a/b/c/d/e/f'); + await untar(FOO_TAR_PATH, destination); + expect(await read(resolve(destination, 'foo_dir/bar.txt'))).toBe('bar\n'); + expect(await read(resolve(destination, 'foo_dir/foo/foo.txt'))).toBe('foo\n'); + }); + + it('passed thrid argument to Extract class, overriding path with destination', async () => { + const destination = resolve(TMP, 'a/b/c'); + + await untar(FOO_TAR_PATH, destination, { + path: '/dev/null', + strip: 1, + }); + + expect(await read(resolve(destination, 'bar.txt'))).toBe('bar\n'); + expect(await read(resolve(destination, 'foo/foo.txt'))).toBe('foo\n'); + }); +}); + +describe('gunzip()', () => { + it('rejects if source path is not absolute', async () => { + try { + await gunzip('foo/bar', '**/*'); + throw new Error('Expected gunzip() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('rejects if destination path is not absolute', async () => { + try { + await gunzip(__dirname, '**/*'); + throw new Error('Expected gunzip() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('rejects if neither path is not absolute', async () => { + try { + await gunzip('foo/bar', '**/*'); + throw new Error('Expected gunzip() to reject'); + } catch (error) { + assertNonAbsoluteError(error); + } + }); + + it('extracts gzip from source into destination, creating destination if necessary', async () => { + const destination = resolve(TMP, 'z/y/x/v/u/t/foo.txt'); + await gunzip(FOO_GZIP_PATH, destination); + expect(await read(resolve(destination))).toBe('foo\n'); + }); +}); diff --git a/src/dev/build/lib/scan_copy.test.ts b/src/dev/build/lib/integration_tests/scan_copy.test.ts similarity index 94% rename from src/dev/build/lib/scan_copy.test.ts rename to src/dev/build/lib/integration_tests/scan_copy.test.ts index ba693770445dc..f81951c575313 100644 --- a/src/dev/build/lib/scan_copy.test.ts +++ b/src/dev/build/lib/integration_tests/scan_copy.test.ts @@ -22,14 +22,13 @@ import { resolve } from 'path'; import del from 'del'; -// @ts-ignore -import { getChildPaths, mkdirp, write } from './fs'; -import { scanCopy } from './scan_copy'; +import { getChildPaths } from '../fs'; +import { scanCopy } from '../scan_copy'; const IS_WINDOWS = process.platform === 'win32'; -const FIXTURES = resolve(__dirname, '__tests__/fixtures'); +const FIXTURES = resolve(__dirname, '../__fixtures__'); +const TMP = resolve(__dirname, '../__tmp__'); const WORLD_EXECUTABLE = resolve(FIXTURES, 'bin/world_executable'); -const TMP = resolve(__dirname, '__tests__/__tmp__'); const getCommonMode = (path: string) => statSync(path).mode.toString(8).slice(-3); diff --git a/src/dev/build/lib/integration_tests/watch_stdio_for_line.test.ts b/src/dev/build/lib/integration_tests/watch_stdio_for_line.test.ts new file mode 100644 index 0000000000000..007a3bc631c60 --- /dev/null +++ b/src/dev/build/lib/integration_tests/watch_stdio_for_line.test.ts @@ -0,0 +1,52 @@ +/* + * 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 execa from 'execa'; + +import { watchStdioForLine } from '../watch_stdio_for_line'; + +const onLogLine = jest.fn(); + +beforeEach(() => { + jest.clearAllMocks(); +}); + +it('calls logFn with log lines', async () => { + const proc = execa(process.execPath, ['-e', 'console.log("hi")']); + await watchStdioForLine(proc, onLogLine); + expect(onLogLine.mock.calls).toMatchInlineSnapshot(` + Array [ + Array [ + "hi", + ], + ] + `); +}); + +it('send the proc SIGKILL if it logs a line matching exitAfter regexp', async function () { + const proc = execa(process.execPath, [require.resolve('../__fixtures__/log_on_sigint')]); + await watchStdioForLine(proc, onLogLine, /listening for SIGINT/); + expect(onLogLine.mock.calls).toMatchInlineSnapshot(` + Array [ + Array [ + "listening for SIGINT", + ], + ] + `); +}); diff --git a/src/dev/build/lib/platform.test.ts b/src/dev/build/lib/platform.test.ts new file mode 100644 index 0000000000000..a93333c57e75e --- /dev/null +++ b/src/dev/build/lib/platform.test.ts @@ -0,0 +1,62 @@ +/* + * 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 { Platform } from './platform'; + +describe('getName()', () => { + it('returns the name argument', () => { + expect(new Platform('win32', 'x64', 'foo').getName()).toBe('win32'); + }); +}); + +describe('getNodeArch()', () => { + it('returns the node arch for the passed name', () => { + expect(new Platform('win32', 'x64', 'foo').getNodeArch()).toBe('win32-x64'); + }); +}); + +describe('getBuildName()', () => { + it('returns the build name for the passed name', () => { + expect(new Platform('linux', 'arm64', 'linux-aarch64').getBuildName()).toBe('linux-aarch64'); + }); +}); + +describe('isWindows()', () => { + it('returns true if name is win32', () => { + expect(new Platform('win32', 'x64', 'foo').isWindows()).toBe(true); + expect(new Platform('linux', 'x64', 'foo').isWindows()).toBe(false); + expect(new Platform('darwin', 'x64', 'foo').isWindows()).toBe(false); + }); +}); + +describe('isLinux()', () => { + it('returns true if name is linux', () => { + expect(new Platform('win32', 'x64', 'foo').isLinux()).toBe(false); + expect(new Platform('linux', 'x64', 'foo').isLinux()).toBe(true); + expect(new Platform('darwin', 'x64', 'foo').isLinux()).toBe(false); + }); +}); + +describe('isMac()', () => { + it('returns true if name is darwin', () => { + expect(new Platform('win32', 'x64', 'foo').isMac()).toBe(false); + expect(new Platform('linux', 'x64', 'foo').isMac()).toBe(false); + expect(new Platform('darwin', 'x64', 'foo').isMac()).toBe(true); + }); +}); diff --git a/src/dev/build/lib/platform.ts b/src/dev/build/lib/platform.ts new file mode 100644 index 0000000000000..f42c7eb7fba54 --- /dev/null +++ b/src/dev/build/lib/platform.ts @@ -0,0 +1,64 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export type PlatformName = 'win32' | 'darwin' | 'linux'; +export type PlatformArchitecture = 'x64' | 'arm64'; + +export class Platform { + constructor( + private name: PlatformName, + private architecture: PlatformArchitecture, + private buildName: string + ) {} + + getName() { + return this.name; + } + + getArchitecture() { + return this.architecture; + } + + getBuildName() { + return this.buildName; + } + + getNodeArch() { + return `${this.name}-${this.architecture}`; + } + + isWindows() { + return this.name === 'win32'; + } + + isMac() { + return this.name === 'darwin'; + } + + isLinux() { + return this.name === 'linux'; + } +} + +export const ALL_PLATFORMS = [ + new Platform('linux', 'x64', 'linux-x86_64'), + new Platform('linux', 'arm64', 'linux-aarch64'), + new Platform('darwin', 'x64', 'darwin-x86_64'), + new Platform('win32', 'x64', 'windows-x86_64'), +]; diff --git a/src/dev/build/lib/runner.test.ts b/src/dev/build/lib/runner.test.ts new file mode 100644 index 0000000000000..0e17f2f590e3d --- /dev/null +++ b/src/dev/build/lib/runner.test.ts @@ -0,0 +1,248 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + ToolingLog, + ToolingLogCollectingWriter, + createStripAnsiSerializer, + createRecursiveSerializer, +} from '@kbn/dev-utils'; +import { Config } from './config'; +import { createRunner } from './runner'; +import { Build } from './build'; +import { isErrorLogged, markErrorLogged } from './errors'; + +jest.mock('./version_info'); + +const testWriter = new ToolingLogCollectingWriter(); +const log = new ToolingLog(); +log.setWriters([testWriter]); + +expect.addSnapshotSerializer(createStripAnsiSerializer()); + +const STACK_TRACE = /(\│\s+)at .+ \(.+\)$/; +const isStackTrace = (x: any) => typeof x === 'string' && STACK_TRACE.test(x); + +expect.addSnapshotSerializer( + createRecursiveSerializer( + (v) => Array.isArray(v) && v.some(isStackTrace), + (v) => { + const start = v.findIndex(isStackTrace); + v[start] = v[start].replace(STACK_TRACE, '$1'); + while (isStackTrace(v[start + 1])) v.splice(start + 1, 1); + return v; + } + ) +); + +beforeEach(() => { + testWriter.messages.length = 0; + jest.clearAllMocks(); +}); + +const setup = async (opts: { buildDefaultDist: boolean; buildOssDist: boolean }) => { + const config = await Config.create({ + isRelease: true, + targetAllPlatforms: true, + versionQualifier: '-SNAPSHOT', + }); + + const run = createRunner({ + config, + log, + ...opts, + }); + + return { config, run }; +}; + +describe('buildOssDist = true, buildDefaultDist = true', () => { + it('runs global task once, passing config and log', async () => { + const { config, run } = await setup({ + buildDefaultDist: true, + buildOssDist: true, + }); + + const mock = jest.fn(); + + await run({ + global: true, + description: 'foo', + run: mock, + }); + + expect(mock).toHaveBeenCalledTimes(1); + expect(mock).toHaveBeenLastCalledWith(config, log, [expect.any(Build), expect.any(Build)]); + }); + + it('calls local tasks twice, passing each build', async () => { + const { config, run } = await setup({ + buildDefaultDist: true, + buildOssDist: true, + }); + + const mock = jest.fn(); + + await run({ + description: 'foo', + run: mock, + }); + + expect(mock).toHaveBeenCalledTimes(2); + expect(mock).toHaveBeenCalledWith(config, log, expect.any(Build)); + }); +}); + +describe('just default dist', () => { + it('runs global task once, passing config and log', async () => { + const { config, run } = await setup({ + buildDefaultDist: true, + buildOssDist: false, + }); + + const mock = jest.fn(); + + await run({ + global: true, + description: 'foo', + run: mock, + }); + + expect(mock).toHaveBeenCalledTimes(1); + expect(mock).toHaveBeenLastCalledWith(config, log, [expect.any(Build)]); + }); + + it('calls local tasks once, passing the default build', async () => { + const { config, run } = await setup({ + buildDefaultDist: true, + buildOssDist: false, + }); + + const mock = jest.fn(); + + await run({ + description: 'foo', + run: mock, + }); + + expect(mock).toHaveBeenCalledTimes(1); + expect(mock).toHaveBeenCalledWith(config, log, expect.any(Build)); + const [args] = mock.mock.calls; + const [, , build] = args; + if (build.isOss()) { + throw new Error('expected build to be the default dist, not the oss dist'); + } + }); +}); + +describe('just oss dist', () => { + it('runs global task once, passing config and log', async () => { + const { config, run } = await setup({ + buildDefaultDist: false, + buildOssDist: true, + }); + + const mock = jest.fn(); + + await run({ + global: true, + description: 'foo', + run: mock, + }); + + expect(mock).toHaveBeenCalledTimes(1); + expect(mock).toHaveBeenLastCalledWith(config, log, [expect.any(Build)]); + }); + + it('calls local tasks once, passing the oss build', async () => { + const { config, run } = await setup({ + buildDefaultDist: false, + buildOssDist: true, + }); + + const mock = jest.fn(); + + await run({ + description: 'foo', + run: mock, + }); + + expect(mock).toHaveBeenCalledTimes(1); + expect(mock).toHaveBeenCalledWith(config, log, expect.any(Build)); + const [args] = mock.mock.calls; + const [, , build] = args; + if (!build.isOss()) { + throw new Error('expected build to be the oss dist, not the default dist'); + } + }); +}); + +describe('task rejection', () => { + it('rejects, logs error, and marks error logged', async () => { + const { run } = await setup({ + buildDefaultDist: true, + buildOssDist: false, + }); + + const error = new Error('FOO'); + expect(isErrorLogged(error)).toBe(false); + + const promise = run({ + description: 'foo', + async run() { + throw error; + }, + }); + + await expect(promise).rejects.toThrowErrorMatchingInlineSnapshot(`"FOO"`); + expect(testWriter.messages).toMatchInlineSnapshot(` + Array [ + " info [ kibana ] foo", + " │ERROR failure 0 sec", + " │ERROR Error: FOO", + " │ ", + "", + ] + `); + expect(isErrorLogged(error)).toBe(true); + }); + + it('just rethrows errors that have already been logged', async () => { + const { run } = await setup({ + buildDefaultDist: true, + buildOssDist: false, + }); + + const error = markErrorLogged(new Error('FOO')); + const promise = run({ + description: 'foo', + async run() { + throw error; + }, + }); + + await expect(promise).rejects.toThrowErrorMatchingInlineSnapshot(`"FOO"`); + expect(testWriter.messages).toMatchInlineSnapshot(` + Array [ + " info [ kibana ] foo", + "", + ] + `); + }); +}); diff --git a/src/dev/build/lib/runner.js b/src/dev/build/lib/runner.ts similarity index 72% rename from src/dev/build/lib/runner.js rename to src/dev/build/lib/runner.ts index 363cfbe97afad..6b7d175bb229a 100644 --- a/src/dev/build/lib/runner.js +++ b/src/dev/build/lib/runner.ts @@ -18,13 +18,33 @@ */ import chalk from 'chalk'; +import { ToolingLog } from '@kbn/dev-utils'; import { isErrorLogged, markErrorLogged } from './errors'; +import { Build } from './build'; +import { Config } from './config'; -import { createBuild } from './build'; +interface Options { + config: Config; + log: ToolingLog; + buildOssDist: boolean; + buildDefaultDist: boolean; +} + +export interface GlobalTask { + global: true; + description: string; + run(config: Config, log: ToolingLog, builds: Build[]): Promise; +} + +export interface Task { + global?: false; + description: string; + run(config: Config, log: ToolingLog, build: Build): Promise; +} -export function createRunner({ config, log, buildOssDist, buildDefaultDist }) { - async function execTask(desc, task, ...args) { +export function createRunner({ config, log, buildOssDist, buildDefaultDist }: Options) { + async function execTask(desc: string, task: Task | GlobalTask, lastArg: any) { log.info(desc); log.indent(4); @@ -37,11 +57,11 @@ export function createRunner({ config, log, buildOssDist, buildDefaultDist }) { }; try { - await task.run(config, log, ...args); + await task.run(config, log, lastArg); log.success(chalk.green('✓'), time()); } catch (error) { if (!isErrorLogged(error)) { - log.error('failure', time()); + log.error(`failure ${time()}`); log.error(error); markErrorLogged(error); } @@ -53,22 +73,12 @@ export function createRunner({ config, log, buildOssDist, buildDefaultDist }) { } } - const builds = []; + const builds: Build[] = []; if (buildDefaultDist) { - builds.push( - createBuild({ - config, - oss: false, - }) - ); + builds.push(new Build(config, false)); } if (buildOssDist) { - builds.push( - createBuild({ - config, - oss: true, - }) - ); + builds.push(new Build(config, true)); } /** @@ -76,11 +86,8 @@ export function createRunner({ config, log, buildOssDist, buildDefaultDist }) { * `config`: an object with methods for determining top-level config values, see `./config.js` * `log`: an instance of the `ToolingLog`, see `../../tooling_log/tooling_log.js` * `builds?`: If task does is not defined as `global: true` then it is called for each build and passed each one here. - * - * @param {Task} task - * @return {Promise} */ - return async function run(task) { + return async function run(task: Task | GlobalTask) { if (task.global) { await execTask(chalk`{dim [ global ]} ${task.description}`, task, builds); } else { diff --git a/src/dev/build/lib/version_info.test.ts b/src/dev/build/lib/version_info.test.ts new file mode 100644 index 0000000000000..1b0c71bf9220e --- /dev/null +++ b/src/dev/build/lib/version_info.test.ts @@ -0,0 +1,62 @@ +/* + * 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 pkg from '../../../../package.json'; +import { getVersionInfo } from './version_info'; + +describe('isRelease = true', () => { + it('returns unchanged package.version, build sha, and build number', async () => { + const versionInfo = await getVersionInfo({ + isRelease: true, + pkg, + }); + + expect(versionInfo).toHaveProperty('buildVersion', pkg.version); + expect(versionInfo).toHaveProperty('buildSha', expect.stringMatching(/^[0-9a-f]{40}$/)); + expect(versionInfo).toHaveProperty('buildNumber'); + expect(versionInfo.buildNumber).toBeGreaterThan(1000); + }); +}); + +describe('isRelease = false', () => { + it('returns snapshot version, build sha, and build number', async () => { + const versionInfo = await getVersionInfo({ + isRelease: false, + pkg, + }); + + expect(versionInfo).toHaveProperty('buildVersion', expect.stringContaining(pkg.version)); + expect(versionInfo).toHaveProperty('buildVersion', expect.stringMatching(/-SNAPSHOT$/)); + expect(versionInfo).toHaveProperty('buildSha', expect.stringMatching(/^[0-9a-f]{40}$/)); + expect(versionInfo).toHaveProperty('buildNumber'); + expect(versionInfo.buildNumber).toBeGreaterThan(1000); + }); +}); + +describe('versionQualifier', () => { + it('appends a version qualifier', async () => { + const versionInfo = await getVersionInfo({ + isRelease: true, + versionQualifier: 'beta55', + pkg, + }); + + expect(versionInfo).toHaveProperty('buildVersion', pkg.version + '-beta55'); + }); +}); diff --git a/src/dev/build/lib/version_info.js b/src/dev/build/lib/version_info.ts similarity index 84% rename from src/dev/build/lib/version_info.js rename to src/dev/build/lib/version_info.ts index 3a053afdbff8b..958112c524bac 100644 --- a/src/dev/build/lib/version_info.js +++ b/src/dev/build/lib/version_info.ts @@ -34,7 +34,19 @@ async function getBuildNumber() { return parseFloat(wc.stdout.trim()); } -export async function getVersionInfo({ isRelease, versionQualifier, pkg }) { +interface Options { + isRelease: boolean; + versionQualifier?: string; + pkg: { + version: string; + }; +} + +type ResolvedType> = T extends Promise ? X : never; + +export type VersionInfo = ResolvedType>; + +export async function getVersionInfo({ isRelease, versionQualifier, pkg }: Options) { const buildVersion = pkg.version.concat( versionQualifier ? `-${versionQualifier}` : '', isRelease ? '' : '-SNAPSHOT' diff --git a/src/legacy/utils/watch_stdio_for_line.js b/src/dev/build/lib/watch_stdio_for_line.ts similarity index 83% rename from src/legacy/utils/watch_stdio_for_line.js rename to src/dev/build/lib/watch_stdio_for_line.ts index 01323b4d4e967..2322d017abc61 100644 --- a/src/legacy/utils/watch_stdio_for_line.js +++ b/src/dev/build/lib/watch_stdio_for_line.ts @@ -18,8 +18,13 @@ */ import { Transform } from 'stream'; +import { ExecaChildProcess } from 'execa'; -import { createPromiseFromStreams, createSplitStream, createMapStream } from './streams'; +import { + createPromiseFromStreams, + createSplitStream, + createMapStream, +} from '../../../legacy/utils/streams'; // creates a stream that skips empty lines unless they are followed by // another line, preventing the empty lines produced by splitStream @@ -27,7 +32,7 @@ function skipLastEmptyLineStream() { let skippedEmptyLine = false; return new Transform({ objectMode: true, - transform(line, enc, cb) { + transform(line, _, cb) { if (skippedEmptyLine) { this.push(''); skippedEmptyLine = false; @@ -37,14 +42,18 @@ function skipLastEmptyLineStream() { skippedEmptyLine = true; return cb(); } else { - return cb(null, line); + return cb(undefined, line); } }, }); } -export async function watchStdioForLine(proc, logFn, exitAfter) { - function onLogLine(line) { +export async function watchStdioForLine( + proc: ExecaChildProcess, + logFn: (line: string) => void, + exitAfter?: RegExp +) { + function onLogLine(line: string) { logFn(line); if (exitAfter && exitAfter.test(line)) { diff --git a/src/dev/build/tasks/bin/copy_bin_scripts_task.js b/src/dev/build/tasks/bin/copy_bin_scripts_task.ts similarity index 92% rename from src/dev/build/tasks/bin/copy_bin_scripts_task.js rename to src/dev/build/tasks/bin/copy_bin_scripts_task.ts index f620f12b17d88..d0ef0a58eebd5 100644 --- a/src/dev/build/tasks/bin/copy_bin_scripts_task.js +++ b/src/dev/build/tasks/bin/copy_bin_scripts_task.ts @@ -17,9 +17,9 @@ * under the License. */ -import { copyAll } from '../../lib'; +import { copyAll, Task } from '../../lib'; -export const CopyBinScriptsTask = { +export const CopyBinScripts: Task = { description: 'Copying bin scripts into platform-generic build directory', async run(config, log, build) { diff --git a/src/dev/build/tasks/bin/index.js b/src/dev/build/tasks/bin/index.js deleted file mode 100644 index e970ac5ec044b..0000000000000 --- a/src/dev/build/tasks/bin/index.js +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -export { CopyBinScriptsTask } from './copy_bin_scripts_task'; diff --git a/packages/kbn-plugin-helpers/src/tasks/test/karma/index.ts b/src/dev/build/tasks/bin/index.ts similarity index 95% rename from packages/kbn-plugin-helpers/src/tasks/test/karma/index.ts rename to src/dev/build/tasks/bin/index.ts index 3089357b49991..dc30f626decc4 100644 --- a/packages/kbn-plugin-helpers/src/tasks/test/karma/index.ts +++ b/src/dev/build/tasks/bin/index.ts @@ -17,4 +17,4 @@ * under the License. */ -export * from './test_karma_task'; +export * from './copy_bin_scripts_task'; diff --git a/src/dev/build/tasks/bin/scripts/kibana-keystore b/src/dev/build/tasks/bin/scripts/kibana-keystore index f83df118d24e8..d811e70095548 100755 --- a/src/dev/build/tasks/bin/scripts/kibana-keystore +++ b/src/dev/build/tasks/bin/scripts/kibana-keystore @@ -14,7 +14,7 @@ while [ -h "$SCRIPT" ] ; do done DIR="$(dirname "${SCRIPT}")/.." -CONFIG_DIR=${KIBANA_PATH_CONF:-"$DIR/config"} +CONFIG_DIR=${KBN_PATH_CONF:-"$DIR/config"} NODE="${DIR}/node/bin/node" test -x "$NODE" if [ ! -x "$NODE" ]; then diff --git a/src/dev/build/tasks/bin/scripts/kibana-keystore.bat b/src/dev/build/tasks/bin/scripts/kibana-keystore.bat index 389eb5bf488e4..7e227141c8ba3 100755 --- a/src/dev/build/tasks/bin/scripts/kibana-keystore.bat +++ b/src/dev/build/tasks/bin/scripts/kibana-keystore.bat @@ -12,8 +12,8 @@ If Not Exist "%NODE%" ( Exit /B 1 ) -set CONFIG_DIR=%KIBANA_PATH_CONF% -If [%KIBANA_PATH_CONF%] == [] ( +set CONFIG_DIR=%KBN_PATH_CONF% +If [%KBN_PATH_CONF%] == [] ( set CONFIG_DIR=%DIR%\config ) diff --git a/src/dev/build/tasks/bin/scripts/kibana-plugin b/src/dev/build/tasks/bin/scripts/kibana-plugin index f1102e1ef5a32..f4486e9cf85fb 100755 --- a/src/dev/build/tasks/bin/scripts/kibana-plugin +++ b/src/dev/build/tasks/bin/scripts/kibana-plugin @@ -14,7 +14,7 @@ while [ -h "$SCRIPT" ] ; do done DIR="$(dirname "${SCRIPT}")/.." -CONFIG_DIR=${KIBANA_PATH_CONF:-"$DIR/config"} +CONFIG_DIR=${KBN_PATH_CONF:-"$DIR/config"} NODE="${DIR}/node/bin/node" test -x "$NODE" if [ ! -x "$NODE" ]; then diff --git a/src/dev/build/tasks/bin/scripts/kibana-plugin.bat b/src/dev/build/tasks/bin/scripts/kibana-plugin.bat index 6815b1b9eab8c..4fb30977fda06 100755 --- a/src/dev/build/tasks/bin/scripts/kibana-plugin.bat +++ b/src/dev/build/tasks/bin/scripts/kibana-plugin.bat @@ -13,8 +13,8 @@ If Not Exist "%NODE%" ( Exit /B 1 ) -set CONFIG_DIR=%KIBANA_PATH_CONF% -If [%KIBANA_PATH_CONF%] == [] ( +set CONFIG_DIR=%KBN_PATH_CONF% +If [%KBN_PATH_CONF%] == [] ( set CONFIG_DIR=%DIR%\config ) diff --git a/src/dev/build/tasks/bin/scripts/kibana.bat b/src/dev/build/tasks/bin/scripts/kibana.bat index d3edc92f110a5..98dd9ec05a48c 100755 --- a/src/dev/build/tasks/bin/scripts/kibana.bat +++ b/src/dev/build/tasks/bin/scripts/kibana.bat @@ -14,8 +14,8 @@ If Not Exist "%NODE%" ( Exit /B 1 ) -set CONFIG_DIR=%KIBANA_PATH_CONF% -If [%KIBANA_PATH_CONF%] == [] ( +set CONFIG_DIR=%KBN_PATH_CONF% +If [%KBN_PATH_CONF%] == [] ( set CONFIG_DIR=%DIR%\config ) diff --git a/src/dev/build/tasks/build_kibana_platform_plugins.js b/src/dev/build/tasks/build_kibana_platform_plugins.ts similarity index 89% rename from src/dev/build/tasks/build_kibana_platform_plugins.js rename to src/dev/build/tasks/build_kibana_platform_plugins.ts index 153a3120f896f..beb5ad40229df 100644 --- a/src/dev/build/tasks/build_kibana_platform_plugins.js +++ b/src/dev/build/tasks/build_kibana_platform_plugins.ts @@ -25,9 +25,11 @@ import { reportOptimizerStats, } from '@kbn/optimizer'; -export const BuildKibanaPlatformPluginsTask = { +import { Task } from '../lib'; + +export const BuildKibanaPlatformPlugins: Task = { description: 'Building distributable versions of Kibana platform plugins', - async run(_, log, build) { + async run(config, log, build) { const optimizerConfig = OptimizerConfig.create({ repoRoot: build.resolvePath(), cache: false, @@ -42,7 +44,7 @@ export const BuildKibanaPlatformPluginsTask = { await runOptimizer(optimizerConfig) .pipe( - reportOptimizerStats(reporter, optimizerConfig), + reportOptimizerStats(reporter, optimizerConfig, log), logOptimizerState(log, optimizerConfig) ) .toPromise(); diff --git a/src/dev/build/tasks/build_packages_task.js b/src/dev/build/tasks/build_packages_task.ts similarity index 97% rename from src/dev/build/tasks/build_packages_task.js rename to src/dev/build/tasks/build_packages_task.ts index b31855aa42dac..dd4e88f9c2b74 100644 --- a/src/dev/build/tasks/build_packages_task.js +++ b/src/dev/build/tasks/build_packages_task.ts @@ -18,7 +18,8 @@ */ import { buildProductionProjects } from '@kbn/pm'; -import { mkdirp } from '../lib'; + +import { mkdirp, Task } from '../lib'; /** * High-level overview of how we enable shared packages in production: @@ -66,8 +67,7 @@ import { mkdirp } from '../lib'; * in some way by Kibana itself in production, as it won't otherwise be * included in the production build. */ - -export const BuildPackagesTask = { +export const BuildPackages: Task = { description: 'Building distributable versions of packages', async run(config, log, build) { await mkdirp(config.resolveFromRepo('target')); diff --git a/src/dev/build/tasks/clean_tasks.js b/src/dev/build/tasks/clean_tasks.ts similarity index 92% rename from src/dev/build/tasks/clean_tasks.js rename to src/dev/build/tasks/clean_tasks.ts index ff5c3b3a73dd3..b519b17e591a3 100644 --- a/src/dev/build/tasks/clean_tasks.js +++ b/src/dev/build/tasks/clean_tasks.ts @@ -19,9 +19,9 @@ import minimatch from 'minimatch'; -import { deleteAll, deleteEmptyFolders, scanDelete } from '../lib'; +import { deleteAll, deleteEmptyFolders, scanDelete, Task, GlobalTask } from '../lib'; -export const CleanTask = { +export const Clean: GlobalTask = { global: true, description: 'Cleaning artifacts from previous builds', @@ -37,7 +37,7 @@ export const CleanTask = { }, }; -export const CleanPackagesTask = { +export const CleanPackages: Task = { description: 'Cleaning source for packages that are now installed in node_modules', async run(config, log, build) { @@ -45,7 +45,7 @@ export const CleanPackagesTask = { }, }; -export const CleanTypescriptTask = { +export const CleanTypescript: Task = { description: 'Cleaning typescript source files that have been transpiled to JS', async run(config, log, build) { @@ -59,11 +59,11 @@ export const CleanTypescriptTask = { }, }; -export const CleanExtraFilesFromModulesTask = { +export const CleanExtraFilesFromModules: Task = { description: 'Cleaning tests, examples, docs, etc. from node_modules', async run(config, log, build) { - const makeRegexps = (patterns) => + const makeRegexps = (patterns: string[]) => patterns.map((pattern) => minimatch.makeRe(pattern, { nocase: true })); const regularExpressions = makeRegexps([ @@ -181,7 +181,7 @@ export const CleanExtraFilesFromModulesTask = { }, }; -export const CleanExtraBinScriptsTask = { +export const CleanExtraBinScripts: Task = { description: 'Cleaning extra bin/* scripts from platform-specific builds', async run(config, log, build) { @@ -201,7 +201,7 @@ export const CleanExtraBinScriptsTask = { }, }; -export const CleanEmptyFoldersTask = { +export const CleanEmptyFolders: Task = { description: 'Cleaning all empty folders recursively', async run(config, log, build) { diff --git a/src/dev/build/tasks/copy_source_task.js b/src/dev/build/tasks/copy_source_task.ts similarity index 91% rename from src/dev/build/tasks/copy_source_task.js rename to src/dev/build/tasks/copy_source_task.ts index e34f05bd6cfff..c8489673b83af 100644 --- a/src/dev/build/tasks/copy_source_task.js +++ b/src/dev/build/tasks/copy_source_task.ts @@ -17,9 +17,9 @@ * under the License. */ -import { copyAll } from '../lib'; +import { copyAll, Task } from '../lib'; -export const CopySourceTask = { +export const CopySource: Task = { description: 'Copying source into platform-generic build directory', async run(config, log, build) { @@ -33,11 +33,9 @@ export const CopySourceTask = { '!src/**/{__tests__,__snapshots__,__mocks__}/**', '!src/test_utils/**', '!src/fixtures/**', - '!src/legacy/core_plugins/tests_bundle/**', '!src/legacy/core_plugins/console/public/tests/**', '!src/cli/cluster/**', '!src/cli/repl/**', - '!src/es_archiver/**', '!src/functional_test_runner/**', '!src/dev/**', 'typings/**', diff --git a/src/dev/build/tasks/create_archives_sources_task.js b/src/dev/build/tasks/create_archives_sources_task.ts similarity index 95% rename from src/dev/build/tasks/create_archives_sources_task.js rename to src/dev/build/tasks/create_archives_sources_task.ts index 76f08bd3d2e4f..72f875b431933 100644 --- a/src/dev/build/tasks/create_archives_sources_task.js +++ b/src/dev/build/tasks/create_archives_sources_task.ts @@ -17,10 +17,10 @@ * under the License. */ -import { scanCopy } from '../lib'; +import { scanCopy, Task } from '../lib'; import { getNodeDownloadInfo } from './nodejs'; -export const CreateArchivesSourcesTask = { +export const CreateArchivesSources: Task = { description: 'Creating platform-specific archive source directories', async run(config, log, build) { await Promise.all( diff --git a/src/dev/build/tasks/create_archives_task.js b/src/dev/build/tasks/create_archives_task.ts similarity index 80% rename from src/dev/build/tasks/create_archives_task.js rename to src/dev/build/tasks/create_archives_task.ts index 541b9551dbc9b..3ffb1afef7469 100644 --- a/src/dev/build/tasks/create_archives_task.js +++ b/src/dev/build/tasks/create_archives_task.ts @@ -23,11 +23,11 @@ import { promisify } from 'util'; import { CiStatsReporter } from '@kbn/dev-utils'; -import { mkdirp, compress } from '../lib'; +import { mkdirp, compressTar, compressZip, Task } from '../lib'; const asyncStat = promisify(Fs.stat); -export const CreateArchivesTask = { +export const CreateArchives: Task = { description: 'Creating the archives for each platform', async run(config, log, build) { @@ -49,19 +49,16 @@ export const CreateArchivesTask = { path: destination, }); - await compress( - 'zip', - { - archiverOptions: { - zlib: { - level: 9, - }, + await compressZip({ + source, + destination, + archiverOptions: { + zlib: { + level: 9, }, - createRootDirectory: true, }, - source, - destination - ); + createRootDirectory: true, + }); break; case '.gz': @@ -70,20 +67,17 @@ export const CreateArchivesTask = { path: destination, }); - await compress( - 'tar', - { - archiverOptions: { - gzip: true, - gzipOptions: { - level: 9, - }, + await compressTar({ + source, + destination, + archiverOptions: { + gzip: true, + gzipOptions: { + level: 9, }, - createRootDirectory: true, }, - source, - destination - ); + createRootDirectory: true, + }); break; default: diff --git a/src/dev/build/tasks/create_empty_dirs_and_files_task.js b/src/dev/build/tasks/create_empty_dirs_and_files_task.ts similarity index 92% rename from src/dev/build/tasks/create_empty_dirs_and_files_task.js rename to src/dev/build/tasks/create_empty_dirs_and_files_task.ts index 6bf059ca9519b..a72c6a4598338 100644 --- a/src/dev/build/tasks/create_empty_dirs_and_files_task.js +++ b/src/dev/build/tasks/create_empty_dirs_and_files_task.ts @@ -17,9 +17,9 @@ * under the License. */ -import { mkdirp, write } from '../lib'; +import { mkdirp, write, Task } from '../lib'; -export const CreateEmptyDirsAndFilesTask = { +export const CreateEmptyDirsAndFiles: Task = { description: 'Creating some empty directories and files to prevent file-permission issues', async run(config, log, build) { diff --git a/src/dev/build/tasks/create_package_json_task.js b/src/dev/build/tasks/create_package_json_task.ts similarity index 92% rename from src/dev/build/tasks/create_package_json_task.js rename to src/dev/build/tasks/create_package_json_task.ts index e7a410b4c6350..5d7fdb9eae2f0 100644 --- a/src/dev/build/tasks/create_package_json_task.js +++ b/src/dev/build/tasks/create_package_json_task.ts @@ -19,9 +19,9 @@ import { copyWorkspacePackages } from '@kbn/pm'; -import { read, write } from '../lib'; +import { read, write, Task } from '../lib'; -export const CreatePackageJsonTask = { +export const CreatePackageJson: Task = { description: 'Creating build-ready version of package.json', async run(config, log, build) { @@ -38,7 +38,7 @@ export const CreatePackageJsonTask = { number: config.getBuildNumber(), sha: config.getBuildSha(), distributable: true, - release: config.isRelease(), + release: config.isRelease, }, repository: pkg.repository, engines: { @@ -59,7 +59,7 @@ export const CreatePackageJsonTask = { }, }; -export const RemovePackageJsonDepsTask = { +export const RemovePackageJsonDeps: Task = { description: 'Removing dependencies from package.json', async run(config, log, build) { @@ -74,7 +74,7 @@ export const RemovePackageJsonDepsTask = { }, }; -export const RemoveWorkspacesTask = { +export const RemoveWorkspaces: Task = { description: 'Remove workspace artifacts', async run(config, log, build) { diff --git a/src/dev/build/tasks/create_readme_task.js b/src/dev/build/tasks/create_readme_task.ts similarity index 93% rename from src/dev/build/tasks/create_readme_task.js rename to src/dev/build/tasks/create_readme_task.ts index 8d60dad9b5633..379ca45f43e26 100644 --- a/src/dev/build/tasks/create_readme_task.js +++ b/src/dev/build/tasks/create_readme_task.ts @@ -17,9 +17,9 @@ * under the License. */ -import { write, read } from '../lib'; +import { write, read, Task } from '../lib'; -export const CreateReadmeTask = { +export const CreateReadme: Task = { description: 'Creating README.md file', async run(config, log, build) { diff --git a/src/dev/build/tasks/index.js b/src/dev/build/tasks/index.ts similarity index 92% rename from src/dev/build/tasks/index.js rename to src/dev/build/tasks/index.ts index 0a3a67313d6a4..4c00e56faee6b 100644 --- a/src/dev/build/tasks/index.js +++ b/src/dev/build/tasks/index.ts @@ -27,7 +27,6 @@ export * from './create_archives_task'; export * from './create_empty_dirs_and_files_task'; export * from './create_package_json_task'; export * from './create_readme_task'; -export * from './install_chromium'; export * from './install_dependencies_task'; export * from './license_file_task'; export * from './nodejs'; @@ -41,3 +40,6 @@ export * from './transpile_scss_task'; export * from './uuid_verification_task'; export * from './verify_env_task'; export * from './write_sha_sums_task'; + +// @ts-expect-error this module can't be TS because it ends up pulling x-pack into Kibana +export { InstallChromium } from './install_chromium'; diff --git a/src/dev/build/tasks/install_chromium.js b/src/dev/build/tasks/install_chromium.js index c5878b23d43ae..3ae36d1615ccd 100644 --- a/src/dev/build/tasks/install_chromium.js +++ b/src/dev/build/tasks/install_chromium.js @@ -17,11 +17,12 @@ * under the License. */ +import { first } from 'rxjs/operators'; + // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { installBrowser } from '../../../../x-pack/plugins/reporting/server/browsers/install'; -import { first } from 'rxjs/operators'; -export const InstallChromiumTask = { +export const InstallChromium = { description: 'Installing Chromium', async run(config, log, build) { @@ -32,6 +33,7 @@ export const InstallChromiumTask = { log.info(`Installing Chromium for ${platform.getName()}-${platform.getArchitecture()}`); const { binaryPath$ } = installBrowser( + // TODO: https://github.com/elastic/kibana/issues/72496 log, build.resolvePathForPlatform(platform, 'x-pack/plugins/reporting/chromium'), platform.getName(), diff --git a/src/dev/build/tasks/install_dependencies_task.js b/src/dev/build/tasks/install_dependencies_task.ts similarity index 94% rename from src/dev/build/tasks/install_dependencies_task.js rename to src/dev/build/tasks/install_dependencies_task.ts index 5191899cd94d0..32fd23859456e 100644 --- a/src/dev/build/tasks/install_dependencies_task.js +++ b/src/dev/build/tasks/install_dependencies_task.ts @@ -19,7 +19,9 @@ import { Project } from '@kbn/pm'; -export const InstallDependenciesTask = { +import { Task } from '../lib'; + +export const InstallDependencies: Task = { description: 'Installing node_modules, including production builds of packages', async run(config, log, build) { diff --git a/src/dev/build/tasks/license_file_task.js b/src/dev/build/tasks/license_file_task.ts similarity index 94% rename from src/dev/build/tasks/license_file_task.js rename to src/dev/build/tasks/license_file_task.ts index 1a7c70738aa47..f1b65501d076f 100644 --- a/src/dev/build/tasks/license_file_task.js +++ b/src/dev/build/tasks/license_file_task.ts @@ -17,9 +17,9 @@ * under the License. */ -import { write, read } from '../lib'; +import { write, read, Task } from '../lib'; -export const UpdateLicenseFileTask = { +export const UpdateLicenseFile: Task = { description: 'Updating LICENSE.txt file', async run(config, log, build) { diff --git a/src/dev/build/tasks/nodejs/__tests__/download_node_builds_task.js b/src/dev/build/tasks/nodejs/__tests__/download_node_builds_task.js deleted file mode 100644 index c1764d06b43b3..0000000000000 --- a/src/dev/build/tasks/nodejs/__tests__/download_node_builds_task.js +++ /dev/null @@ -1,97 +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 sinon from 'sinon'; -import expect from '@kbn/expect'; - -import * as NodeShasumsNS from '../node_shasums'; -import * as NodeDownloadInfoNS from '../node_download_info'; -import * as DownloadNS from '../../../lib/download'; // sinon can't stub '../../../lib' properly -import { DownloadNodeBuildsTask } from '../download_node_builds_task'; - -describe('src/dev/build/tasks/nodejs/download_node_builds_task', () => { - const sandbox = sinon.createSandbox(); - afterEach(() => { - sandbox.restore(); - }); - - function setup({ failOnUrl } = {}) { - const platforms = [{ getName: () => 'foo' }, { getName: () => 'bar' }]; - - const log = {}; - const config = { - getNodePlatforms: () => platforms, - getNodeVersion: () => 'nodeVersion', - }; - - sandbox.stub(NodeDownloadInfoNS, 'getNodeDownloadInfo').callsFake((config, platform) => { - return { - url: `${platform.getName()}:url`, - downloadPath: `${platform.getName()}:downloadPath`, - downloadName: `${platform.getName()}:downloadName`, - }; - }); - - sandbox.stub(NodeShasumsNS, 'getNodeShasums').returns({ - 'foo:downloadName': 'foo:sha256', - 'bar:downloadName': 'bar:sha256', - }); - - sandbox.stub(DownloadNS, 'download').callsFake(({ url }) => { - if (url === failOnUrl) { - throw new Error('Download failed for reasons'); - } - }); - - return { log, config }; - } - - it('downloads node builds for each platform', async () => { - const { log, config } = setup(); - - await DownloadNodeBuildsTask.run(config, log); - - sinon.assert.calledTwice(DownloadNS.download); - sinon.assert.calledWithExactly(DownloadNS.download, { - log, - url: 'foo:url', - sha256: 'foo:sha256', - destination: 'foo:downloadPath', - retries: 3, - }); - sinon.assert.calledWithExactly(DownloadNS.download, { - log, - url: 'bar:url', - sha256: 'bar:sha256', - destination: 'bar:downloadPath', - retries: 3, - }); - }); - - it('rejects if any download fails', async () => { - const { config, log } = setup({ failOnUrl: 'foo:url' }); - - try { - await DownloadNodeBuildsTask.run(config, log); - throw new Error('Expected DownloadNodeBuildsTask to reject'); - } catch (error) { - expect(error).to.have.property('message').be('Download failed for reasons'); - } - }); -}); diff --git a/src/dev/build/tasks/nodejs/__tests__/extract_node_builds_task.js b/src/dev/build/tasks/nodejs/__tests__/extract_node_builds_task.js deleted file mode 100644 index efb7aaa3a2209..0000000000000 --- a/src/dev/build/tasks/nodejs/__tests__/extract_node_builds_task.js +++ /dev/null @@ -1,93 +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 sinon from 'sinon'; -import { resolve } from 'path'; -import * as NodeDownloadInfoNS from '../node_download_info'; -import * as FsNS from '../../../lib/fs'; -import { ExtractNodeBuildsTask } from '../extract_node_builds_task'; - -describe('src/dev/build/tasks/node_extract_node_builds_task', () => { - const sandbox = sinon.createSandbox(); - afterEach(() => { - sandbox.restore(); - }); - - it('copies downloadPath to extractDir/node.exe for windows platform', async () => { - sandbox.stub(NodeDownloadInfoNS, 'getNodeDownloadInfo').returns({ - downloadPath: 'downloadPath', - extractDir: 'extractDir', - }); - - sandbox.stub(ExtractNodeBuildsTask, 'copyWindows'); - sandbox.stub(FsNS, 'untar'); - - const platform = { - isWindows: () => true, - }; - - const config = { - getNodePlatforms: () => [platform], - }; - - await ExtractNodeBuildsTask.run(config); - - sinon.assert.calledOnce(NodeDownloadInfoNS.getNodeDownloadInfo); - sinon.assert.calledWithExactly(NodeDownloadInfoNS.getNodeDownloadInfo, config, platform); - - sinon.assert.calledOnce(ExtractNodeBuildsTask.copyWindows); - sinon.assert.calledWithExactly( - ExtractNodeBuildsTask.copyWindows, - 'downloadPath', - resolve('extractDir/node.exe') - ); - - sinon.assert.notCalled(FsNS.untar); - }); - - it('untars downloadPath to extractDir, stripping the top level of the archive, for non-windows platforms', async () => { - sandbox.stub(NodeDownloadInfoNS, 'getNodeDownloadInfo').returns({ - downloadPath: 'downloadPath', - extractDir: 'extractDir', - }); - - sandbox.stub(ExtractNodeBuildsTask, 'copyWindows'); - sandbox.stub(FsNS, 'untar'); - - const platform = { - isWindows: () => false, - }; - - const config = { - getNodePlatforms: () => [platform], - }; - - await ExtractNodeBuildsTask.run(config); - - sinon.assert.calledOnce(NodeDownloadInfoNS.getNodeDownloadInfo); - sinon.assert.calledWithExactly(NodeDownloadInfoNS.getNodeDownloadInfo, config, platform); - - sinon.assert.notCalled(ExtractNodeBuildsTask.copyWindows); - - sinon.assert.calledOnce(FsNS.untar); - sinon.assert.calledWithExactly(FsNS.untar, 'downloadPath', 'extractDir', { - strip: 1, - }); - }); -}); diff --git a/src/dev/build/tasks/nodejs/__tests__/verify_existing_node_builds_task.js b/src/dev/build/tasks/nodejs/__tests__/verify_existing_node_builds_task.js deleted file mode 100644 index a8f732a869d2d..0000000000000 --- a/src/dev/build/tasks/nodejs/__tests__/verify_existing_node_builds_task.js +++ /dev/null @@ -1,106 +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 sinon from 'sinon'; -import expect from '@kbn/expect'; - -import * as NodeShasumsNS from '../node_shasums'; -import * as NodeDownloadInfoNS from '../node_download_info'; -import * as FsNS from '../../../lib/fs'; -import { VerifyExistingNodeBuildsTask } from '../verify_existing_node_builds_task'; - -describe('src/dev/build/tasks/nodejs/verify_existing_node_builds_task', () => { - const sandbox = sinon.createSandbox(); - afterEach(() => { - sandbox.restore(); - }); - - function setup({ nodeShasums } = {}) { - const platforms = [ - { getName: () => 'foo', getNodeArch: () => 'foo:nodeArch' }, - { getName: () => 'bar', getNodeArch: () => 'bar:nodeArch' }, - ]; - - const log = { success: sinon.stub() }; - const config = { - getNodePlatforms: () => platforms, - getNodeVersion: () => 'nodeVersion', - }; - - sandbox.stub(NodeDownloadInfoNS, 'getNodeDownloadInfo').callsFake((config, platform) => { - return { - url: `${platform.getName()}:url`, - downloadPath: `${platform.getName()}:downloadPath`, - downloadName: `${platform.getName()}:downloadName`, - }; - }); - - sandbox.stub(NodeShasumsNS, 'getNodeShasums').returns( - nodeShasums || { - 'foo:downloadName': 'foo:sha256', - 'bar:downloadName': 'bar:sha256', - } - ); - - sandbox.stub(FsNS, 'getFileHash').callsFake((path) => { - switch (path) { - case 'foo:downloadPath': - return 'foo:sha256'; - case 'bar:downloadPath': - return 'bar:sha256'; - } - }); - - return { log, config, platforms }; - } - - it('downloads node builds for each platform', async () => { - const { log, config, platforms } = setup(); - - await VerifyExistingNodeBuildsTask.run(config, log); - - sinon.assert.calledOnce(NodeShasumsNS.getNodeShasums); - - sinon.assert.calledTwice(NodeDownloadInfoNS.getNodeDownloadInfo); - sinon.assert.calledWithExactly(NodeDownloadInfoNS.getNodeDownloadInfo, config, platforms[0]); - sinon.assert.calledWithExactly(NodeDownloadInfoNS.getNodeDownloadInfo, config, platforms[1]); - - sinon.assert.calledTwice(FsNS.getFileHash); - sinon.assert.calledWithExactly(FsNS.getFileHash, 'foo:downloadPath', 'sha256'); - sinon.assert.calledWithExactly(FsNS.getFileHash, 'bar:downloadPath', 'sha256'); - }); - - it('rejects if any download has an incorrect sha256', async () => { - const { config, log } = setup({ - nodeShasums: { - 'foo:downloadName': 'foo:sha256', - 'bar:downloadName': 'bar:invalid', - }, - }); - - try { - await VerifyExistingNodeBuildsTask.run(config, log); - throw new Error('Expected VerifyExistingNodeBuildsTask to reject'); - } catch (error) { - expect(error) - .to.have.property('message') - .be('Download at bar:downloadPath does not match expected checksum bar:sha256'); - } - }); -}); diff --git a/src/dev/build/tasks/nodejs/clean_node_builds_task.js b/src/dev/build/tasks/nodejs/clean_node_builds_task.ts similarity index 93% rename from src/dev/build/tasks/nodejs/clean_node_builds_task.js rename to src/dev/build/tasks/nodejs/clean_node_builds_task.ts index a34e65a394115..9deeb9f73de28 100644 --- a/src/dev/build/tasks/nodejs/clean_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/clean_node_builds_task.ts @@ -17,9 +17,9 @@ * under the License. */ -import { deleteAll } from '../../lib'; +import { deleteAll, Task } from '../../lib'; -export const CleanNodeBuildsTask = { +export const CleanNodeBuilds: Task = { description: 'Cleaning npm from node', async run(config, log, build) { diff --git a/src/dev/build/tasks/nodejs/download_node_builds_task.test.ts b/src/dev/build/tasks/nodejs/download_node_builds_task.test.ts new file mode 100644 index 0000000000000..6f08c8aa69750 --- /dev/null +++ b/src/dev/build/tasks/nodejs/download_node_builds_task.test.ts @@ -0,0 +1,136 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + ToolingLog, + ToolingLogCollectingWriter, + createAnyInstanceSerializer, +} from '@kbn/dev-utils'; + +import { Config, Platform } from '../../lib'; +import { DownloadNodeBuilds } from './download_node_builds_task'; + +// import * as NodeShasumsNS from '../node_shasums'; +// import * as NodeDownloadInfoNS from '../node_download_info'; +// import * as DownloadNS from '../../../lib/download'; +// import { DownloadNodeBuilds } from '../download_node_builds_task'; +jest.mock('./node_shasums'); +jest.mock('./node_download_info'); +jest.mock('../../lib/download'); + +expect.addSnapshotSerializer(createAnyInstanceSerializer(ToolingLog)); + +const { getNodeDownloadInfo } = jest.requireMock('./node_download_info'); +const { getNodeShasums } = jest.requireMock('./node_shasums'); +const { download } = jest.requireMock('../../lib/download'); + +const log = new ToolingLog(); +const testWriter = new ToolingLogCollectingWriter(); +log.setWriters([testWriter]); + +beforeEach(() => { + testWriter.messages.length = 0; + jest.clearAllMocks(); +}); + +async function setup({ failOnUrl }: { failOnUrl?: string } = {}) { + const config = await Config.create({ + isRelease: true, + targetAllPlatforms: true, + }); + + getNodeDownloadInfo.mockImplementation((_: Config, platform: Platform) => { + return { + url: `${platform.getName()}:url`, + downloadPath: `${platform.getName()}:downloadPath`, + downloadName: `${platform.getName()}:downloadName`, + }; + }); + + getNodeShasums.mockReturnValue({ + 'linux:downloadName': 'linux:sha256', + 'darwin:downloadName': 'darwin:sha256', + 'win32:downloadName': 'win32:sha256', + }); + + download.mockImplementation(({ url }: any) => { + if (url === failOnUrl) { + throw new Error('Download failed for reasons'); + } + }); + + return { config }; +} + +it('downloads node builds for each platform', async () => { + const { config } = await setup(); + + await DownloadNodeBuilds.run(config, log, []); + + expect(download.mock.calls).toMatchInlineSnapshot(` + Array [ + Array [ + Object { + "destination": "linux:downloadPath", + "log": , + "retries": 3, + "sha256": "linux:sha256", + "url": "linux:url", + }, + ], + Array [ + Object { + "destination": "linux:downloadPath", + "log": , + "retries": 3, + "sha256": "linux:sha256", + "url": "linux:url", + }, + ], + Array [ + Object { + "destination": "darwin:downloadPath", + "log": , + "retries": 3, + "sha256": "darwin:sha256", + "url": "darwin:url", + }, + ], + Array [ + Object { + "destination": "win32:downloadPath", + "log": , + "retries": 3, + "sha256": "win32:sha256", + "url": "win32:url", + }, + ], + ] + `); + expect(testWriter.messages).toMatchInlineSnapshot(`Array []`); +}); + +it('rejects if any download fails', async () => { + const { config } = await setup({ failOnUrl: 'linux:url' }); + + await expect(DownloadNodeBuilds.run(config, log, [])).rejects.toMatchInlineSnapshot( + `[Error: Download failed for reasons]` + ); + expect(testWriter.messages).toMatchInlineSnapshot(`Array []`); +}); diff --git a/src/dev/build/tasks/nodejs/download_node_builds_task.js b/src/dev/build/tasks/nodejs/download_node_builds_task.ts similarity index 93% rename from src/dev/build/tasks/nodejs/download_node_builds_task.js rename to src/dev/build/tasks/nodejs/download_node_builds_task.ts index c0907e6c42a97..ad42ea11436f5 100644 --- a/src/dev/build/tasks/nodejs/download_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/download_node_builds_task.ts @@ -17,11 +17,11 @@ * under the License. */ -import { download } from '../../lib'; +import { download, GlobalTask } from '../../lib'; import { getNodeShasums } from './node_shasums'; import { getNodeDownloadInfo } from './node_download_info'; -export const DownloadNodeBuildsTask = { +export const DownloadNodeBuilds: GlobalTask = { global: true, description: 'Downloading node.js builds for all platforms', async run(config, log) { diff --git a/src/dev/build/tasks/nodejs/extract_node_builds_task.test.ts b/src/dev/build/tasks/nodejs/extract_node_builds_task.test.ts new file mode 100644 index 0000000000000..94c421f7c9a62 --- /dev/null +++ b/src/dev/build/tasks/nodejs/extract_node_builds_task.test.ts @@ -0,0 +1,108 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + ToolingLog, + ToolingLogCollectingWriter, + createAbsolutePathSerializer, +} from '@kbn/dev-utils'; + +import { Config } from '../../lib'; +import { ExtractNodeBuilds } from './extract_node_builds_task'; + +jest.mock('../../lib/fs'); + +const Fs = jest.requireMock('../../lib/fs'); + +const log = new ToolingLog(); +const testWriter = new ToolingLogCollectingWriter(); +log.setWriters([testWriter]); + +expect.addSnapshotSerializer(createAbsolutePathSerializer()); + +async function setup() { + const config = await Config.create({ + isRelease: true, + targetAllPlatforms: true, + }); + + return { config }; +} + +beforeEach(() => { + testWriter.messages.length = 0; + jest.clearAllMocks(); +}); + +it('runs expected fs operations', async () => { + const { config } = await setup(); + + await ExtractNodeBuilds.run(config, log, []); + + const usedMethods = Object.fromEntries( + Object.entries(Fs) + .filter((entry): entry is [string, jest.Mock] => { + const [, mock] = entry; + + if (typeof mock !== 'function') { + return false; + } + + return (mock as jest.Mock).mock.calls.length > 0; + }) + .map(([name, mock]) => [name, mock.mock.calls]) + ); + + expect(usedMethods).toMatchInlineSnapshot(` + Object { + "copy": Array [ + Array [ + /.node_binaries/10.21.0/node.exe, + /.node_binaries/10.21.0/win32-x64/node.exe, + Object { + "clone": true, + }, + ], + ], + "untar": Array [ + Array [ + /.node_binaries/10.21.0/node-v10.21.0-linux-x64.tar.gz, + /.node_binaries/10.21.0/linux-x64, + Object { + "strip": 1, + }, + ], + Array [ + /.node_binaries/10.21.0/node-v10.21.0-linux-arm64.tar.gz, + /.node_binaries/10.21.0/linux-arm64, + Object { + "strip": 1, + }, + ], + Array [ + /.node_binaries/10.21.0/node-v10.21.0-darwin-x64.tar.gz, + /.node_binaries/10.21.0/darwin-x64, + Object { + "strip": 1, + }, + ], + ], + } + `); +}); diff --git a/src/dev/build/tasks/nodejs/extract_node_builds_task.js b/src/dev/build/tasks/nodejs/extract_node_builds_task.ts similarity index 56% rename from src/dev/build/tasks/nodejs/extract_node_builds_task.js rename to src/dev/build/tasks/nodejs/extract_node_builds_task.ts index caf0a389b4cc0..aaa3312c8ba3f 100644 --- a/src/dev/build/tasks/nodejs/extract_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/extract_node_builds_task.ts @@ -17,39 +17,27 @@ * under the License. */ -import { dirname, resolve } from 'path'; -import fs from 'fs'; -import { promisify } from 'util'; +import Path from 'path'; -import { untar, mkdirp } from '../../lib'; +import { untar, GlobalTask, copy } from '../../lib'; import { getNodeDownloadInfo } from './node_download_info'; -const statAsync = promisify(fs.stat); -const copyFileAsync = promisify(fs.copyFile); - -export const ExtractNodeBuildsTask = { +export const ExtractNodeBuilds: GlobalTask = { global: true, description: 'Extracting node.js builds for all platforms', async run(config) { await Promise.all( config.getNodePlatforms().map(async (platform) => { const { downloadPath, extractDir } = getNodeDownloadInfo(config, platform); - // windows executable is not extractable, it's just an .exe file if (platform.isWindows()) { - const destination = resolve(extractDir, 'node.exe'); - return this.copyWindows(downloadPath, destination); + // windows executable is not extractable, it's just an .exe file + await copy(downloadPath, Path.resolve(extractDir, 'node.exe'), { + clone: true, + }); + } else { + await untar(downloadPath, extractDir, { strip: 1 }); } - - // all other downloads are tarballs - return untar(downloadPath, extractDir, { strip: 1 }); }) ); }, - async copyWindows(source, destination) { - // ensure source exists before creating destination directory - await statAsync(source); - await mkdirp(dirname(destination)); - // for performance reasons, do a copy-on-write by using the fs.constants.COPYFILE_FICLONE flag - return await copyFileAsync(source, destination, fs.constants.COPYFILE_FICLONE); - }, }; diff --git a/src/dev/build/tasks/nodejs/index.js b/src/dev/build/tasks/nodejs/index.js deleted file mode 100644 index e52dba73e4a96..0000000000000 --- a/src/dev/build/tasks/nodejs/index.js +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -export { getNodeDownloadInfo } from './node_download_info'; - -export { DownloadNodeBuildsTask } from './download_node_builds_task'; -export { ExtractNodeBuildsTask } from './extract_node_builds_task'; -export { VerifyExistingNodeBuildsTask } from './verify_existing_node_builds_task'; -export { CleanNodeBuildsTask } from './clean_node_builds_task'; diff --git a/src/dev/build/tasks/nodejs/index.ts b/src/dev/build/tasks/nodejs/index.ts new file mode 100644 index 0000000000000..8dd65418fb445 --- /dev/null +++ b/src/dev/build/tasks/nodejs/index.ts @@ -0,0 +1,24 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export * from './node_download_info'; +export * from './download_node_builds_task'; +export * from './extract_node_builds_task'; +export * from './verify_existing_node_builds_task'; +export * from './clean_node_builds_task'; diff --git a/src/dev/build/tasks/nodejs/node_download_info.js b/src/dev/build/tasks/nodejs/node_download_info.ts similarity index 92% rename from src/dev/build/tasks/nodejs/node_download_info.js rename to src/dev/build/tasks/nodejs/node_download_info.ts index 33ffd042d85a3..b2c62d6667fd4 100644 --- a/src/dev/build/tasks/nodejs/node_download_info.js +++ b/src/dev/build/tasks/nodejs/node_download_info.ts @@ -19,7 +19,9 @@ import { basename } from 'path'; -export function getNodeDownloadInfo(config, platform) { +import { Config, Platform } from '../../lib'; + +export function getNodeDownloadInfo(config: Config, platform: Platform) { const version = config.getNodeVersion(); const arch = platform.getNodeArch(); diff --git a/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.test.ts b/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.test.ts new file mode 100644 index 0000000000000..f24b7ffc59c14 --- /dev/null +++ b/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.test.ts @@ -0,0 +1,225 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + ToolingLog, + ToolingLogCollectingWriter, + createAnyInstanceSerializer, +} from '@kbn/dev-utils'; + +import { Config, Platform } from '../../lib'; +import { VerifyExistingNodeBuilds } from './verify_existing_node_builds_task'; + +jest.mock('./node_shasums'); +jest.mock('./node_download_info'); +jest.mock('../../lib/fs'); + +const { getNodeShasums } = jest.requireMock('./node_shasums'); +const { getNodeDownloadInfo } = jest.requireMock('./node_download_info'); +const { getFileHash } = jest.requireMock('../../lib/fs'); + +const log = new ToolingLog(); +const testWriter = new ToolingLogCollectingWriter(); +log.setWriters([testWriter]); + +expect.addSnapshotSerializer(createAnyInstanceSerializer(Config)); + +async function setup(actualShaSums?: Record) { + const config = await Config.create({ + isRelease: true, + targetAllPlatforms: true, + }); + + getNodeShasums.mockReturnValue( + Object.fromEntries( + config.getTargetPlatforms().map((platform) => { + return [`${platform.getName()}:${platform.getNodeArch()}:downloadName`, 'valid shasum']; + }) + ) + ); + + getNodeDownloadInfo.mockImplementation((_: Config, platform: Platform) => { + return { + downloadPath: `${platform.getName()}:${platform.getNodeArch()}:downloadPath`, + downloadName: `${platform.getName()}:${platform.getNodeArch()}:downloadName`, + }; + }); + + getFileHash.mockImplementation((downloadPath: string) => { + if (actualShaSums?.[downloadPath]) { + return actualShaSums[downloadPath]; + } + + return 'valid shasum'; + }); + + return { config }; +} + +beforeEach(() => { + testWriter.messages.length = 0; + jest.clearAllMocks(); +}); + +it('checks shasums for each downloaded node build', async () => { + const { config } = await setup(); + + await VerifyExistingNodeBuilds.run(config, log, []); + + expect(getNodeShasums).toMatchInlineSnapshot(` + [MockFunction] { + "calls": Array [ + Array [ + "10.21.0", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": Object { + "darwin:darwin-x64:downloadName": "valid shasum", + "linux:linux-arm64:downloadName": "valid shasum", + "linux:linux-x64:downloadName": "valid shasum", + "win32:win32-x64:downloadName": "valid shasum", + }, + }, + ], + } + `); + expect(getNodeDownloadInfo).toMatchInlineSnapshot(` + [MockFunction] { + "calls": Array [ + Array [ + , + Platform { + "architecture": "x64", + "buildName": "linux-x86_64", + "name": "linux", + }, + ], + Array [ + , + Platform { + "architecture": "arm64", + "buildName": "linux-aarch64", + "name": "linux", + }, + ], + Array [ + , + Platform { + "architecture": "x64", + "buildName": "darwin-x86_64", + "name": "darwin", + }, + ], + Array [ + , + Platform { + "architecture": "x64", + "buildName": "windows-x86_64", + "name": "win32", + }, + ], + ], + "results": Array [ + Object { + "type": "return", + "value": Object { + "downloadName": "linux:linux-x64:downloadName", + "downloadPath": "linux:linux-x64:downloadPath", + }, + }, + Object { + "type": "return", + "value": Object { + "downloadName": "linux:linux-arm64:downloadName", + "downloadPath": "linux:linux-arm64:downloadPath", + }, + }, + Object { + "type": "return", + "value": Object { + "downloadName": "darwin:darwin-x64:downloadName", + "downloadPath": "darwin:darwin-x64:downloadPath", + }, + }, + Object { + "type": "return", + "value": Object { + "downloadName": "win32:win32-x64:downloadName", + "downloadPath": "win32:win32-x64:downloadPath", + }, + }, + ], + } + `); + expect(getFileHash).toMatchInlineSnapshot(` + [MockFunction] { + "calls": Array [ + Array [ + "linux:linux-x64:downloadPath", + "sha256", + ], + Array [ + "linux:linux-arm64:downloadPath", + "sha256", + ], + Array [ + "darwin:darwin-x64:downloadPath", + "sha256", + ], + Array [ + "win32:win32-x64:downloadPath", + "sha256", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": "valid shasum", + }, + Object { + "type": "return", + "value": "valid shasum", + }, + Object { + "type": "return", + "value": "valid shasum", + }, + Object { + "type": "return", + "value": "valid shasum", + }, + ], + } + `); +}); + +it('rejects if any download has an incorrect sha256', async () => { + const { config } = await setup({ + 'linux:linux-arm64:downloadPath': 'invalid shasum', + }); + + await expect( + VerifyExistingNodeBuilds.run(config, log, []) + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Download at linux:linux-arm64:downloadPath does not match expected checksum invalid shasum"` + ); +}); diff --git a/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.js b/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.ts similarity index 93% rename from src/dev/build/tasks/nodejs/verify_existing_node_builds_task.js rename to src/dev/build/tasks/nodejs/verify_existing_node_builds_task.ts index b320471fda33f..9ce0778d2d1f0 100644 --- a/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.ts @@ -17,11 +17,11 @@ * under the License. */ -import { getFileHash } from '../../lib'; +import { getFileHash, GlobalTask } from '../../lib'; import { getNodeDownloadInfo } from './node_download_info'; import { getNodeShasums } from './node_shasums'; -export const VerifyExistingNodeBuildsTask = { +export const VerifyExistingNodeBuilds: GlobalTask = { global: true, description: 'Verifying previously downloaded node.js build for all platforms', async run(config, log) { diff --git a/src/dev/build/tasks/notice_file_task.js b/src/dev/build/tasks/notice_file_task.ts similarity index 95% rename from src/dev/build/tasks/notice_file_task.js rename to src/dev/build/tasks/notice_file_task.ts index 59369c7cb5a3b..6edb76d506bc0 100644 --- a/src/dev/build/tasks/notice_file_task.js +++ b/src/dev/build/tasks/notice_file_task.ts @@ -20,11 +20,11 @@ import { getInstalledPackages } from '../../npm'; import { LICENSE_OVERRIDES } from '../../license_checker'; -import { write } from '../lib'; +import { write, Task } from '../lib'; import { getNodeDownloadInfo } from './nodejs'; import { generateNoticeFromSource, generateBuildNoticeText } from '../../notice'; -export const CreateNoticeFileTask = { +export const CreateNoticeFile: Task = { description: 'Generating NOTICE.txt file', async run(config, log, build) { @@ -40,7 +40,7 @@ export const CreateNoticeFileTask = { log.info('Discovering installed packages'); const packages = await getInstalledPackages({ directory: build.resolvePath(), - dev: false, + includeDev: false, licenseOverrides: LICENSE_OVERRIDES, }); diff --git a/src/dev/build/tasks/optimize_task.js b/src/dev/build/tasks/optimize_task.ts similarity index 95% rename from src/dev/build/tasks/optimize_task.js rename to src/dev/build/tasks/optimize_task.ts index 16a7537b8ac9e..98979f376eacd 100644 --- a/src/dev/build/tasks/optimize_task.js +++ b/src/dev/build/tasks/optimize_task.ts @@ -17,10 +17,10 @@ * under the License. */ -import { deleteAll, copyAll, exec } from '../lib'; +import { deleteAll, copyAll, exec, Task } from '../lib'; import { getNodeDownloadInfo } from './nodejs'; -export const OptimizeBuildTask = { +export const OptimizeBuild: Task = { description: 'Running optimizer', async run(config, log, build) { diff --git a/src/dev/build/tasks/os_packages/create_os_package_tasks.js b/src/dev/build/tasks/os_packages/create_os_package_tasks.ts similarity index 89% rename from src/dev/build/tasks/os_packages/create_os_package_tasks.js rename to src/dev/build/tasks/os_packages/create_os_package_tasks.ts index 6a00e681ab0ec..4580b95423d3d 100644 --- a/src/dev/build/tasks/os_packages/create_os_package_tasks.js +++ b/src/dev/build/tasks/os_packages/create_os_package_tasks.ts @@ -17,10 +17,11 @@ * under the License. */ +import { Task } from '../../lib'; import { runFpm } from './run_fpm'; import { runDockerGenerator, runDockerGeneratorForUBI } from './docker_generator'; -export const CreateDebPackageTask = { +export const CreateDebPackage: Task = { description: 'Creating deb package', async run(config, log, build) { @@ -33,7 +34,7 @@ export const CreateDebPackageTask = { }, }; -export const CreateRpmPackageTask = { +export const CreateRpmPackage: Task = { description: 'Creating rpm package', async run(config, log, build) { @@ -41,7 +42,7 @@ export const CreateRpmPackageTask = { }, }; -export const CreateDockerPackageTask = { +export const CreateDockerPackage: Task = { description: 'Creating docker package', async run(config, log, build) { @@ -50,7 +51,7 @@ export const CreateDockerPackageTask = { }, }; -export const CreateDockerUbiPackageTask = { +export const CreateDockerUbiPackage: Task = { description: 'Creating docker ubi package', async run(config, log, build) { diff --git a/src/dev/build/tasks/os_packages/docker_generator/bundle_dockerfiles.js b/src/dev/build/tasks/os_packages/docker_generator/bundle_dockerfiles.ts similarity index 80% rename from src/dev/build/tasks/os_packages/docker_generator/bundle_dockerfiles.js rename to src/dev/build/tasks/os_packages/docker_generator/bundle_dockerfiles.ts index bbcb6dfeeb109..7a8f7316913be 100644 --- a/src/dev/build/tasks/os_packages/docker_generator/bundle_dockerfiles.js +++ b/src/dev/build/tasks/os_packages/docker_generator/bundle_dockerfiles.ts @@ -18,10 +18,14 @@ */ import { resolve } from 'path'; -import { compress, copyAll, mkdirp, write } from '../../../lib'; + +import { ToolingLog } from '@kbn/dev-utils'; + +import { compressTar, copyAll, mkdirp, write, Config } from '../../../lib'; import { dockerfileTemplate } from './templates'; +import { TemplateContext } from './template_context'; -export async function bundleDockerFiles(config, log, build, scope) { +export async function bundleDockerFiles(config: Config, log: ToolingLog, scope: TemplateContext) { log.info( `Generating kibana${scope.imageFlavor}${scope.ubiImageFlavor} docker build context bundle` ); @@ -50,18 +54,15 @@ export async function bundleDockerFiles(config, log, build, scope) { // Compress dockerfiles dir created inside // docker build dir as output it as a target // on targets folder - await compress( - 'tar', - { - archiverOptions: { - gzip: true, - gzipOptions: { - level: 9, - }, + await compressTar({ + source: dockerFilesBuildDir, + destination: dockerFilesOutputDir, + archiverOptions: { + gzip: true, + gzipOptions: { + level: 9, }, - createRootDirectory: false, }, - dockerFilesBuildDir, - dockerFilesOutputDir - ); + createRootDirectory: false, + }); } diff --git a/src/dev/build/tasks/os_packages/docker_generator/index.ts b/src/dev/build/tasks/os_packages/docker_generator/index.ts new file mode 100644 index 0000000000000..dff56585fc704 --- /dev/null +++ b/src/dev/build/tasks/os_packages/docker_generator/index.ts @@ -0,0 +1,20 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export { runDockerGenerator, runDockerGeneratorForUBI } from './run'; diff --git a/src/dev/build/tasks/os_packages/docker_generator/run.js b/src/dev/build/tasks/os_packages/docker_generator/run.ts similarity index 90% rename from src/dev/build/tasks/os_packages/docker_generator/run.js rename to src/dev/build/tasks/os_packages/docker_generator/run.ts index b6dab43887f14..0a26729f3502d 100644 --- a/src/dev/build/tasks/os_packages/docker_generator/run.js +++ b/src/dev/build/tasks/os_packages/docker_generator/run.ts @@ -20,8 +20,12 @@ import { access, link, unlink, chmod } from 'fs'; import { resolve } from 'path'; import { promisify } from 'util'; -import { write, copyAll, mkdirp, exec } from '../../../lib'; + +import { ToolingLog } from '@kbn/dev-utils'; + +import { write, copyAll, mkdirp, exec, Config, Build } from '../../../lib'; import * as dockerTemplates from './templates'; +import { TemplateContext } from './template_context'; import { bundleDockerFiles } from './bundle_dockerfiles'; const accessAsync = promisify(access); @@ -29,7 +33,12 @@ const linkAsync = promisify(link); const unlinkAsync = promisify(unlink); const chmodAsync = promisify(chmod); -export async function runDockerGenerator(config, log, build, ubi = false) { +export async function runDockerGenerator( + config: Config, + log: ToolingLog, + build: Build, + ubi: boolean = false +) { // UBI var config const baseOSImage = ubi ? 'registry.access.redhat.com/ubi7/ubi-minimal:7.7' : 'centos:7'; const ubiVersionTag = 'ubi7'; @@ -52,7 +61,7 @@ export async function runDockerGenerator(config, log, build, ubi = false) { const dockerOutputDir = config.resolveFromTarget( `kibana${imageFlavor}${ubiImageFlavor}-${versionTag}-docker.tar.gz` ); - const scope = { + const scope: TemplateContext = { artifactTarball, imageFlavor, versionTag, @@ -112,10 +121,10 @@ export async function runDockerGenerator(config, log, build, ubi = false) { }); // Pack Dockerfiles and create a target for them - await bundleDockerFiles(config, log, build, scope); + await bundleDockerFiles(config, log, scope); } -export async function runDockerGeneratorForUBI(config, log, build) { +export async function runDockerGeneratorForUBI(config: Config, log: ToolingLog, build: Build) { // Only run ubi docker image build for default distribution if (build.isOss()) { return; diff --git a/src/dev/build/tasks/os_packages/docker_generator/template_context.ts b/src/dev/build/tasks/os_packages/docker_generator/template_context.ts new file mode 100644 index 0000000000000..115d4c6927c30 --- /dev/null +++ b/src/dev/build/tasks/os_packages/docker_generator/template_context.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. + */ + +export interface TemplateContext { + artifactTarball: string; + imageFlavor: string; + versionTag: string; + license: string; + artifactsDir: string; + imageTag: string; + dockerBuildDir: string; + dockerOutputDir: string; + baseOSImage: string; + ubiImageFlavor: string; + dockerBuildDate: string; + usePublicArtifact?: boolean; +} diff --git a/src/dev/build/tasks/os_packages/docker_generator/templates/build_docker_sh.template.js b/src/dev/build/tasks/os_packages/docker_generator/templates/build_docker_sh.template.ts similarity index 94% rename from src/dev/build/tasks/os_packages/docker_generator/templates/build_docker_sh.template.js rename to src/dev/build/tasks/os_packages/docker_generator/templates/build_docker_sh.template.ts index 4e8dfe188b867..ff6fcf7548d9d 100644 --- a/src/dev/build/tasks/os_packages/docker_generator/templates/build_docker_sh.template.js +++ b/src/dev/build/tasks/os_packages/docker_generator/templates/build_docker_sh.template.ts @@ -19,6 +19,8 @@ import dedent from 'dedent'; +import { TemplateContext } from '../template_context'; + function generator({ imageTag, imageFlavor, @@ -26,7 +28,7 @@ function generator({ dockerOutputDir, baseOSImage, ubiImageFlavor, -}) { +}: TemplateContext) { return dedent(` #!/usr/bin/env bash # diff --git a/src/dev/build/tasks/os_packages/docker_generator/templates/dockerfile.template.js b/src/dev/build/tasks/os_packages/docker_generator/templates/dockerfile.template.ts similarity index 98% rename from src/dev/build/tasks/os_packages/docker_generator/templates/dockerfile.template.js rename to src/dev/build/tasks/os_packages/docker_generator/templates/dockerfile.template.ts index 5832d00162b20..ea2f881768c8f 100755 --- a/src/dev/build/tasks/os_packages/docker_generator/templates/dockerfile.template.js +++ b/src/dev/build/tasks/os_packages/docker_generator/templates/dockerfile.template.ts @@ -19,6 +19,8 @@ import dedent from 'dedent'; +import { TemplateContext } from '../template_context'; + function generator({ artifactTarball, versionTag, @@ -27,7 +29,7 @@ function generator({ baseOSImage, ubiImageFlavor, dockerBuildDate, -}) { +}: TemplateContext) { const copyArtifactTarballInsideDockerOptFolder = () => { if (usePublicArtifact) { return `RUN cd /opt && curl --retry 8 -s -L -O https://artifacts.elastic.co/downloads/kibana/${artifactTarball} && cd -`; diff --git a/src/dev/build/tasks/os_packages/docker_generator/templates/index.js b/src/dev/build/tasks/os_packages/docker_generator/templates/index.ts similarity index 100% rename from src/dev/build/tasks/os_packages/docker_generator/templates/index.js rename to src/dev/build/tasks/os_packages/docker_generator/templates/index.ts diff --git a/src/dev/build/tasks/os_packages/docker_generator/templates/kibana_yml.template.js b/src/dev/build/tasks/os_packages/docker_generator/templates/kibana_yml.template.ts similarity index 91% rename from src/dev/build/tasks/os_packages/docker_generator/templates/kibana_yml.template.js rename to src/dev/build/tasks/os_packages/docker_generator/templates/kibana_yml.template.ts index c80f9334cfaeb..240ec6f4e9326 100644 --- a/src/dev/build/tasks/os_packages/docker_generator/templates/kibana_yml.template.js +++ b/src/dev/build/tasks/os_packages/docker_generator/templates/kibana_yml.template.ts @@ -19,7 +19,9 @@ import dedent from 'dedent'; -function generator({ imageFlavor }) { +import { TemplateContext } from '../template_context'; + +function generator({ imageFlavor }: TemplateContext) { return dedent(` # # ** THIS IS AN AUTO-GENERATED FILE ** diff --git a/src/dev/build/tasks/os_packages/index.js b/src/dev/build/tasks/os_packages/index.js deleted file mode 100644 index 82626c47b6087..0000000000000 --- a/src/dev/build/tasks/os_packages/index.js +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -export { - CreateRpmPackageTask, - CreateDebPackageTask, - CreateDockerPackageTask, - CreateDockerUbiPackageTask, -} from './create_os_package_tasks'; diff --git a/src/dev/build/tasks/os_packages/index.ts b/src/dev/build/tasks/os_packages/index.ts new file mode 100644 index 0000000000000..439fde71d255f --- /dev/null +++ b/src/dev/build/tasks/os_packages/index.ts @@ -0,0 +1,20 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export * from './create_os_package_tasks'; diff --git a/src/dev/build/tasks/os_packages/package_scripts/post_install.sh b/src/dev/build/tasks/os_packages/package_scripts/post_install.sh index 10f11ff51874e..1c679bdb40b59 100644 --- a/src/dev/build/tasks/os_packages/package_scripts/post_install.sh +++ b/src/dev/build/tasks/os_packages/package_scripts/post_install.sh @@ -3,6 +3,22 @@ set -e export KBN_PATH_CONF=${KBN_PATH_CONF:-<%= configDir %>} +set_chmod() { + chmod -f 660 ${KBN_PATH_CONF}/kibana.yml || true + chmod -f 2750 <%= dataDir %> || true + chmod -f 2750 ${KBN_PATH_CONF} || true +} + +set_chown() { + chown -R <%= user %>:<%= group %> <%= dataDir %> + chown -R root:<%= group %> ${KBN_PATH_CONF} +} + +set_access() { + set_chmod + set_chown +} + case $1 in # Debian configure) @@ -14,6 +30,12 @@ case $1 in adduser --quiet --system --no-create-home --disabled-password \ --ingroup "<%= group %>" --shell /bin/false "<%= user %>" fi + + if [ -n "$2" ]; then + IS_UPGRADE=true + fi + + set_access ;; abort-deconfigure|abort-upgrade|abort-remove) ;; @@ -28,6 +50,12 @@ case $1 in useradd -r -g "<%= group %>" -M -s /sbin/nologin \ -c "kibana service user" "<%= user %>" fi + + if [ "$1" = "2" ]; then + IS_UPGRADE=true + fi + + set_access ;; *) @@ -36,11 +64,8 @@ case $1 in ;; esac -chown -R <%= user %>:<%= group %> <%= dataDir %> -chmod 2750 <%= dataDir %> -chmod -R 2755 <%= dataDir %>/* - -chown :<%= group %> ${KBN_PATH_CONF} -chown :<%= group %> ${KBN_PATH_CONF}/kibana.yml -chmod 2750 ${KBN_PATH_CONF} -chmod 660 ${KBN_PATH_CONF}/kibana.yml +if [ "$IS_UPGRADE" = "true" ]; then + if command -v systemctl >/dev/null; then + systemctl daemon-reload + fi +fi diff --git a/src/dev/build/tasks/os_packages/run_fpm.js b/src/dev/build/tasks/os_packages/run_fpm.ts similarity index 91% rename from src/dev/build/tasks/os_packages/run_fpm.js rename to src/dev/build/tasks/os_packages/run_fpm.ts index eb77da0e70176..b5169ec3d43b6 100644 --- a/src/dev/build/tasks/os_packages/run_fpm.js +++ b/src/dev/build/tasks/os_packages/run_fpm.ts @@ -19,15 +19,23 @@ import { resolve } from 'path'; -import { exec } from '../../lib'; +import { ToolingLog } from '@kbn/dev-utils'; -export async function runFpm(config, log, build, type, pkgSpecificFlags) { +import { exec, Config, Build } from '../../lib'; + +export async function runFpm( + config: Config, + log: ToolingLog, + build: Build, + type: 'rpm' | 'deb', + pkgSpecificFlags: string[] +) { const linux = config.getPlatform('linux', 'x64'); const version = config.getBuildVersion(); - const resolveWithTrailingSlash = (...paths) => `${resolve(...paths)}/`; + const resolveWithTrailingSlash = (...paths: string[]) => `${resolve(...paths)}/`; - const fromBuild = (...paths) => build.resolvePathForPlatform(linux, ...paths); + const fromBuild = (...paths: string[]) => build.resolvePathForPlatform(linux, ...paths); const pickLicense = () => { if (build.isOss()) { diff --git a/src/dev/build/tasks/os_packages/service_templates/sysv/etc/default/kibana b/src/dev/build/tasks/os_packages/service_templates/sysv/etc/default/kibana index 092dc6482fa1d..ee019d348ed97 100644 --- a/src/dev/build/tasks/os_packages/service_templates/sysv/etc/default/kibana +++ b/src/dev/build/tasks/os_packages/service_templates/sysv/etc/default/kibana @@ -12,4 +12,4 @@ KILL_ON_STOP_TIMEOUT=0 BABEL_CACHE_PATH="/var/lib/kibana/optimize/.babel_register_cache.json" -KIBANA_PATH_CONF="/etc/kibana" +KBN_PATH_CONF="/etc/kibana" diff --git a/src/dev/build/tasks/patch_native_modules_task.js b/src/dev/build/tasks/patch_native_modules_task.ts similarity index 82% rename from src/dev/build/tasks/patch_native_modules_task.js rename to src/dev/build/tasks/patch_native_modules_task.ts index c30d1fd774b55..b56d01b616462 100644 --- a/src/dev/build/tasks/patch_native_modules_task.js +++ b/src/dev/build/tasks/patch_native_modules_task.ts @@ -16,14 +16,30 @@ * specific language governing permissions and limitations * under the License. */ -import fs from 'fs'; + import path from 'path'; -import util from 'util'; -import { deleteAll, download, gunzip, untar } from '../lib'; + +import { ToolingLog } from '@kbn/dev-utils'; + +import { deleteAll, download, gunzip, untar, Task, Config, Build, Platform, read } from '../lib'; const DOWNLOAD_DIRECTORY = '.native_modules'; -const packages = [ +interface Package { + name: string; + version: string; + destinationPath: string; + extractMethod: string; + archives: Record< + string, + { + url: string; + sha256: string; + } + >; +} + +const packages: Package[] = [ { name: 're2', version: '1.15.4', @@ -46,16 +62,22 @@ const packages = [ }, ]; -async function getInstalledVersion(config, packageName) { +async function getInstalledVersion(config: Config, packageName: string) { const packageJSONPath = config.resolveFromRepo( path.join('node_modules', packageName, 'package.json') ); - const buffer = await util.promisify(fs.readFile)(packageJSONPath); - const packageJSON = JSON.parse(buffer); + const json = await read(packageJSONPath); + const packageJSON = JSON.parse(json); return packageJSON.version; } -async function patchModule(config, log, build, platform, pkg) { +async function patchModule( + config: Config, + log: ToolingLog, + build: Build, + platform: Platform, + pkg: Package +) { const installedVersion = await getInstalledVersion(config, pkg.name); if (installedVersion !== pkg.version) { throw new Error( @@ -89,7 +111,7 @@ async function patchModule(config, log, build, platform, pkg) { } } -export const PatchNativeModulesTask = { +export const PatchNativeModules: Task = { description: 'Patching platform-specific native modules', async run(config, log, build) { for (const pkg of packages) { diff --git a/src/dev/build/tasks/path_length_task.js b/src/dev/build/tasks/path_length_task.ts similarity index 95% rename from src/dev/build/tasks/path_length_task.js rename to src/dev/build/tasks/path_length_task.ts index 29ab9ce5a2499..d639217adc53b 100644 --- a/src/dev/build/tasks/path_length_task.js +++ b/src/dev/build/tasks/path_length_task.ts @@ -21,9 +21,9 @@ import { relative } from 'path'; import { tap, filter, map, toArray } from 'rxjs/operators'; -import { scan$ } from '../lib/scan'; +import { scan$, Task } from '../lib'; -export const PathLengthTask = { +export const PathLength: Task = { description: 'Checking Windows for paths > 200 characters', async run(config, log, build) { diff --git a/src/dev/build/tasks/transpile_babel_task.js b/src/dev/build/tasks/transpile_babel_task.ts similarity index 80% rename from src/dev/build/tasks/transpile_babel_task.js rename to src/dev/build/tasks/transpile_babel_task.ts index f476ead9183fe..a1e994587ce92 100644 --- a/src/dev/build/tasks/transpile_babel_task.js +++ b/src/dev/build/tasks/transpile_babel_task.ts @@ -17,15 +17,21 @@ * under the License. */ +import { pipeline } from 'stream'; +import { promisify } from 'util'; + +// @ts-expect-error @types/gulp-babel is outdated and doesn't work for gulp-babel v8 import gulpBabel from 'gulp-babel'; import vfs from 'vinyl-fs'; -import { createPromiseFromStreams } from '../../../legacy/utils'; +import { Task, Build } from '../lib'; + +const asyncPipeline = promisify(pipeline); -const transpileWithBabel = async (srcGlobs, build, presets) => { +const transpileWithBabel = async (srcGlobs: string[], build: Build, presets: string[]) => { const buildRoot = build.resolvePath(); - await createPromiseFromStreams([ + await asyncPipeline( vfs.src( srcGlobs.concat([ '!**/*.d.ts', @@ -44,11 +50,11 @@ const transpileWithBabel = async (srcGlobs, build, presets) => { presets, }), - vfs.dest(buildRoot), - ]); + vfs.dest(buildRoot) + ); }; -export const TranspileBabelTask = { +export const TranspileBabel: Task = { description: 'Transpiling sources with babel', async run(config, log, build) { diff --git a/src/dev/build/tasks/transpile_scss_task.js b/src/dev/build/tasks/transpile_scss_task.ts similarity index 89% rename from src/dev/build/tasks/transpile_scss_task.js rename to src/dev/build/tasks/transpile_scss_task.ts index d1c76d97c8853..e1b0bd0171c92 100644 --- a/src/dev/build/tasks/transpile_scss_task.js +++ b/src/dev/build/tasks/transpile_scss_task.ts @@ -17,9 +17,12 @@ * under the License. */ +import { Task } from '../lib'; + +// @ts-expect-error buildSass isn't TS yet import { buildSass } from '../../sass'; -export const TranspileScssTask = { +export const TranspileScss: Task = { description: 'Transpiling SCSS to CSS', async run(config, log, build) { await buildSass({ diff --git a/src/dev/build/tasks/uuid_verification_task.js b/src/dev/build/tasks/uuid_verification_task.ts similarity index 94% rename from src/dev/build/tasks/uuid_verification_task.js rename to src/dev/build/tasks/uuid_verification_task.ts index 32c9e73dba988..b65096690b681 100644 --- a/src/dev/build/tasks/uuid_verification_task.js +++ b/src/dev/build/tasks/uuid_verification_task.ts @@ -17,9 +17,9 @@ * under the License. */ -import { read } from '../lib'; +import { read, Task } from '../lib'; -export const UuidVerificationTask = { +export const UuidVerification: Task = { description: 'Verify that no UUID file is baked into the build', async run(config, log, build) { diff --git a/src/dev/build/tasks/verify_env_task.js b/src/dev/build/tasks/verify_env_task.ts similarity index 93% rename from src/dev/build/tasks/verify_env_task.js rename to src/dev/build/tasks/verify_env_task.ts index eb679411d7e38..975a620c1c540 100644 --- a/src/dev/build/tasks/verify_env_task.js +++ b/src/dev/build/tasks/verify_env_task.ts @@ -17,7 +17,9 @@ * under the License. */ -export const VerifyEnvTask = { +import { GlobalTask } from '../lib'; + +export const VerifyEnv: GlobalTask = { global: true, description: 'Verifying environment meets requirements', diff --git a/src/dev/build/tasks/write_sha_sums_task.js b/src/dev/build/tasks/write_sha_sums_task.ts similarity index 92% rename from src/dev/build/tasks/write_sha_sums_task.js rename to src/dev/build/tasks/write_sha_sums_task.ts index c44924bb9ce09..abf938cd150ab 100644 --- a/src/dev/build/tasks/write_sha_sums_task.js +++ b/src/dev/build/tasks/write_sha_sums_task.ts @@ -19,9 +19,9 @@ import globby from 'globby'; -import { getFileHash, write } from '../lib'; +import { getFileHash, write, GlobalTask } from '../lib'; -export const WriteShaSumsTask = { +export const WriteShaSums: GlobalTask = { global: true, description: 'Writing sha1sums of archives and packages in target directory', diff --git a/src/dev/ci_setup/setup.sh b/src/dev/ci_setup/setup.sh index 25d2afb00cd87..aabc1e75b9025 100755 --- a/src/dev/ci_setup/setup.sh +++ b/src/dev/ci_setup/setup.sh @@ -50,22 +50,6 @@ if [ "$GIT_CHANGES" ]; then exit 1 fi -### -### rebuild kbn-pm distributable to ensure it's not out of date -### -echo " -- building renovate config" -node scripts/build_renovate_config - -### -### verify no git modifications -### -GIT_CHANGES="$(git ls-files --modified)" -if [ "$GIT_CHANGES" ]; then - echo -e "\n${RED}ERROR: 'node scripts/build_renovate_config' caused changes to the following files:${C_RESET}\n" - echo -e "$GIT_CHANGES\n" - exit 1 -fi - ### ### rebuild plugin list to ensure it's not out of date ### diff --git a/src/dev/code_coverage/ingest_coverage/ingest.js b/src/dev/code_coverage/ingest_coverage/ingest.js index 43f0663ad0359..31a94d161a3cc 100644 --- a/src/dev/code_coverage/ingest_coverage/ingest.js +++ b/src/dev/code_coverage/ingest_coverage/ingest.js @@ -77,6 +77,7 @@ async function send(logF, idx, redactedEsHostUrl, client, requestBody) { const sendMsg = (actuallySent, redactedEsHostUrl, payload) => { const { index, body } = payload; return `### ${actuallySent ? 'Sent' : 'Fake Sent'}: +${payload.pipeline ? `\t### Team Assignment Pipeline: ${green(payload.pipeline)}` : ''} ${redactedEsHostUrl ? `\t### ES Host: ${redactedEsHostUrl}` : ''} \t### Index: ${green(index)} \t### payload.body: ${body} diff --git a/src/dev/code_coverage/ingest_coverage/team_assignment/ingestion_pipeline_painless.json b/src/dev/code_coverage/ingest_coverage/team_assignment/ingestion_pipeline_painless.json index 18e88b47ec887..30e78635ec2e9 100644 --- a/src/dev/code_coverage/ingest_coverage/team_assignment/ingestion_pipeline_painless.json +++ b/src/dev/code_coverage/ingest_coverage/team_assignment/ingestion_pipeline_painless.json @@ -1 +1 @@ -{"description":"Kibana code coverage team assignments","processors":[{"script":{"lang":"painless","source":"\n String path = ctx.coveredFilePath; \n if (path.indexOf('src/legacy/core_plugins/kibana/') == 0) {\n\n if (path.indexOf('src/legacy/core_plugins/kibana/common/utils') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/migrations') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/dashboard/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/dev_tools/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/discover/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/home') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/home/np_ready/') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/local_application_service/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/management/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/core_plugins/kibana/server/lib') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/core_plugins/kibana/server/lib/management/saved_objects') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/core_plugins/kibana/server/routes/api/management/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/core_plugins/kibana/server/routes/api/import/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/core_plugins/kibana/server/routes/api/export/') == 0) ctx.team = 'kibana-platform';\n else ctx.team = 'unknown';\n\n } else if (path.indexOf('src/legacy/core_plugins/') == 0) {\n\n if (path.indexOf('src/legacy/core_plugins/apm_oss/') == 0) ctx.team = 'apm-ui';\n else if (path.indexOf('src/legacy/core_plugins/console_legacy') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/elasticsearch') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/core_plugins/embeddable_api/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/core_plugins/input_control_vis') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/interpreter/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/core_plugins/kibana_react/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/core_plugins/newsfeed') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/legacy/core_plugins/region_map') == 0) ctx.team = 'maps';\n else if (path.indexOf('src/legacy/core_plugins/status_page/public') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/core_plugins/testbed') == 0) ctx.team = 'kibana-platform';\n // else if (path.indexOf('src/legacy/core_plugins/tests_bundle/') == 0) ctx.team = 'kibana-platform';\n \n else if (path.indexOf('src/legacy/core_plugins/tile_map') == 0) ctx.team = 'maps';\n else if (path.indexOf('src/legacy/core_plugins/timelion') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/ui_metric/') == 0) ctx.team = 'pulse';\n else if (path.indexOf('src/legacy/core_plugins/vis_type_tagcloud') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/vis_type_vega') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/vis_type_vislib/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/visualizations/') == 0) ctx.team = 'kibana-app-arch';\n else ctx.team = 'unknown';\n\n } else if (path.indexOf('src/legacy/server/') == 0) {\n\n if (path.indexOf('src/legacy/server/config/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/server/http/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/server/i18n/') == 0) ctx.team = 'kibana-localization';\n else if (path.indexOf('src/legacy/server/index_patterns/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/server/keystore/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/legacy/server/logging/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/server/pid/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/legacy/server/sample_data/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/server/sass/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/legacy/server/saved_objects/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/server/status/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/server/url_shortening/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/server/utils/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/legacy/server/warnings/') == 0) ctx.team = 'kibana-operations';\n else ctx.team = 'unknown';\n\n } else if (path.indexOf('src/legacy/ui') == 0) {\n\n if (path.indexOf('src/legacy/ui/public/field_editor') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/ui/public/timefilter') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/ui/public/management') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/ui/public/state_management') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/ui/public/new_platform') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/ui/public/plugin_discovery') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/ui/public/chrome') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/ui/public/notify') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/ui/public/documentation_links') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/ui/public/autoload') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/ui/public/capabilities') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('src/legacy/ui/public/apm') == 0) ctx.team = 'apm-ui';\n\n } else if (path.indexOf('src/plugins/') == 0) {\n\n if (path.indexOf('src/plugins/advanced_settings/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/apm_oss/') == 0) ctx.team = 'apm-ui';\n else if (path.indexOf('src/plugins/bfetch/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/charts/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/charts/public/static/color_maps') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/console/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('src/plugins/dashboard/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/data/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/dev_tools/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('src/plugins/discover/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/embeddable/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/es_ui_shared/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('src/plugins/expressions/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/home/public') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/plugins/home/server/tutorials') == 0) ctx.team = 'observability';\n else if (path.indexOf('src/plugins/home/server/services/') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/plugins/home/') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/plugins/index_pattern_management/public/service') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/index_pattern_management/public') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/input_control_vis/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/inspector/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/kibana_legacy/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/kibana_react/public/code_editor') == 0) ctx.team = 'kibana-canvas';\n else if (path.indexOf('src/plugins/kibana_react/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/kibana_utils/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/management/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/kibana_usage_collection/') == 0) ctx.team = 'pulse';\n else if (path.indexOf('src/plugins/legacy_export/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/plugins/maps_legacy/') == 0) ctx.team = 'maps';\n else if (path.indexOf('src/plugins/region_map/') == 0) ctx.team = 'maps';\n else if (path.indexOf('src/plugins/tile_map/') == 0) ctx.team = 'maps';\n else if (path.indexOf('src/plugins/timelion') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/navigation/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/newsfeed') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/plugins/saved_objects_management/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/plugins/saved_objects/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/share/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/status_page/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/plugins/telemetry') == 0) ctx.team = 'pulse';\n else if (path.indexOf('src/plugins/testbed/server/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/plugins/ui_actions/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/usage_collection/') == 0) ctx.team = 'pulse';\n else if (path.indexOf('src/plugins/vis_default_editor') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/vis_type') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/visualizations/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/visualize/') == 0) ctx.team = 'kibana-app';\n else ctx.team = 'unknown';\n\n } else if (path.indexOf('x-pack/legacy/') == 0) {\n\n if (path.indexOf('x-pack/legacy/plugins/actions/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/legacy/plugins/alerting/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/legacy/plugins/apm/') == 0) ctx.team = 'apm-ui';\n else if (path.indexOf('x-pack/legacy/plugins/beats_management/') == 0) ctx.team = 'beats';\n else if (path.indexOf('x-pack/legacy/plugins/canvas/') == 0) ctx.team = 'kibana-canvas';\n else if (path.indexOf('x-pack/legacy/plugins/cross_cluster_replication/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/plugins/dashboard_mode/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('x-pack/legacy/plugins/encrypted_saved_objects/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('x-pack/legacy/plugins/index_management/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/plugins/infra/') == 0) ctx.team = 'logs-metrics-ui';\n else if (path.indexOf('x-pack/legacy/plugins/ingest_manager/') == 0) ctx.team = 'ingest-management';\n else if (path.indexOf('x-pack/legacy/plugins/license_management/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/plugins/maps/') == 0) ctx.team = 'kibana-gis';\n else if (path.indexOf('x-pack/legacy/plugins/ml/') == 0) ctx.team = 'ml-ui';\n else if (path.indexOf('x-pack/legacy/plugins/monitoring/') == 0) ctx.team = 'stack-monitoring-ui';\n else if (path.indexOf('x-pack/legacy/plugins/reporting') == 0) ctx.team = 'kibana-reporting';\n else if (path.indexOf('x-pack/legacy/plugins/rollup/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/plugins/security/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('x-pack/legacy/plugins/siem/') == 0) ctx.team = 'siem';\n else if (path.indexOf('x-pack/legacy/plugins/siem/server/lib/detection_engine/rules/prepackaged_rules') == 0) ctx.team = 'security-intelligence-analytics';\n else if (path.indexOf('x-pack/legacy/plugins/snapshot_restore/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/plugins/spaces/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('x-pack/legacy/plugins/task_manager') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/legacy/plugins/triggers_actions_ui/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/legacy/plugins/upgrade_assistant/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/plugins/uptime') == 0) ctx.team = 'uptime';\n else if (path.indexOf('x-pack/legacy/plugins/xpack_main/server/') == 0) ctx.team = 'kibana-platform';\n\n else if (path.indexOf('x-pack/legacy/server/lib/create_router/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/server/lib/check_license/') == 0) ctx.team = 'es-ui'; \n else if (path.indexOf('x-pack/legacy/server/lib/') == 0) ctx.team = 'kibana-platform'; \n else ctx.team = 'unknown';\n\n } else if (path.indexOf('x-pack/plugins/') == 0) {\n\n if (path.indexOf('x-pack/plugins/actions/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/plugins/advanced_ui_actions/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('x-pack/plugins/alerts') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/plugins/alerting_builtins') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/plugins/apm/') == 0) ctx.team = 'apm-ui';\n else if (path.indexOf('x-pack/plugins/beats_management/') == 0) ctx.team = 'beats';\n else if (path.indexOf('x-pack/plugins/canvas/') == 0) ctx.team = 'kibana-canvas';\n else if (path.indexOf('x-pack/plugins/case') == 0) ctx.team = 'siem';\n else if (path.indexOf('x-pack/plugins/cloud/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('x-pack/plugins/code/') == 0) ctx.team = 'code';\n else if (path.indexOf('x-pack/plugins/console_extensions/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/cross_cluster_replication/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/dashboard_enhanced') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('x-pack/plugins/dashboard_mode') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('x-pack/plugins/discover_enhanced') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('x-pack/plugins/embeddable_enhanced') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('x-pack/plugins/data_enhanced/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('x-pack/plugins/drilldowns/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('x-pack/plugins/encrypted_saved_objects/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('x-pack/plugins/endpoint/') == 0) ctx.team = 'endpoint-app-team';\n else if (path.indexOf('x-pack/plugins/es_ui_shared/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/event_log/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/plugins/features/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('x-pack/plugins/file_upload') == 0) ctx.team = 'kibana-gis';\n else if (path.indexOf('x-pack/plugins/global_search') == 0) ctx.team = 'kibana-platform';\n \n else if (path.indexOf('x-pack/plugins/graph/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('x-pack/plugins/grokdebugger/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/index_lifecycle_management/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/index_management/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/infra/') == 0) ctx.team = 'logs-metrics-ui';\n else if (path.indexOf('x-pack/plugins/ingest_manager/') == 0) ctx.team = 'ingest-management';\n else if (path.indexOf('x-pack/plugins/ingest_pipelines/') == 0) ctx.team = 'es-ui';\n \n else if (path.indexOf('x-pack/plugins/lens/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('x-pack/plugins/license_management/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/licensing/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('x-pack/plugins/lists/') == 0) ctx.team = 'siem';\n else if (path.indexOf('x-pack/plugins/logstash') == 0) ctx.team = 'logstash';\n else if (path.indexOf('x-pack/plugins/maps/') == 0) ctx.team = 'kibana-gis';\n else if (path.indexOf('x-pack/plugins/maps_legacy_licensing') == 0) ctx.team = 'maps';\n else if (path.indexOf('x-pack/plugins/ml/') == 0) ctx.team = 'ml-ui';\n else if (path.indexOf('x-pack/plugins/monitoring') == 0) ctx.team = 'stack-monitoring-ui';\n else if (path.indexOf('x-pack/plugins/observability/') == 0) ctx.team = 'apm-ui';\n else if (path.indexOf('x-pack/plugins/oss_telemetry/') == 0) ctx.team = 'pulse';\n else if (path.indexOf('x-pack/plugins/painless_lab/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/remote_clusters/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/reporting') == 0) ctx.team = 'kibana-reporting';\n else if (path.indexOf('x-pack/plugins/rollup/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/searchprofiler/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/security/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('x-pack/plugins/security_solution/') == 0) ctx.team = 'siem';\n \n else if (path.indexOf('x-pack/plugins/siem/server/lib/detection_engine/rules/prepackaged_rules') == 0) ctx.team = 'security-intelligence-analytics';\n else if (path.indexOf('x-pack/plugins/siem/') == 0) ctx.team = 'siem';\n else if (path.indexOf('x-pack/plugins/snapshot_restore/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/spaces/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('x-pack/plugins/task_manager/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/plugins/telemetry_collection_xpack/') == 0) ctx.team = 'pulse';\n else if (path.indexOf('x-pack/plugins/transform/') == 0) ctx.team = 'ml-ui';\n else if (path.indexOf('x-pack/plugins/translations/') == 0) ctx.team = 'kibana-localization';\n else if (path.indexOf('x-pack/plugins/triggers_actions_ui/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/plugins/upgrade_assistant/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/ui_actions_enhanced') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('x-pack/plugins/uptime') == 0) ctx.team = 'uptime';\n \n else if (path.indexOf('x-pack/plugins/watcher/') == 0) ctx.team = 'es-ui';\n else ctx.team = 'unknown';\n\n } else if (path.indexOf('packages') == 0) {\n\n if (path.indexOf('packages/kbn-analytics/') == 0) ctx.team = 'pulse';\n else if (path.indexOf('packages/kbn-babel') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-config-schema/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('packages/elastic-datemath') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('packages/kbn-dev-utils') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-es/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-eslint') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-expect') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-i18n/') == 0) ctx.team = 'kibana-localization';\n else if (path.indexOf('packages/kbn-interpreter/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('packages/kbn-optimizer/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-pm/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-test/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-test-subj-selector/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-ui-framework/') == 0) ctx.team = 'kibana-design';\n else if (path.indexOf('packages/kbn-ui-shared-deps/') == 0) ctx.team = 'kibana-operations';\n else ctx.team = 'unknown';\n\n } else {\n\n if (path.indexOf('config/kibana.yml') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/apm.js') == 0) ctx.team = 'apm-ui';\n else if (path.indexOf('src/core/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/core/public/i18n/') == 0) ctx.team = 'kibana-localization';\n else if (path.indexOf('src/core/server/csp/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('src/dev/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/dev/i18n/') == 0) ctx.team = 'kibana-localization';\n else if (path.indexOf('src/dev/run_check_published_api_changes.ts') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/es_archiver/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/optimize/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/setup_node_env/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/test_utils/') == 0) ctx.team = 'kibana-operations'; \n else ctx.team = 'unknown';\n }"}}]} +{"description":"Kibana code coverage team assignments","processors":[{"script":{"lang":"painless","source":"\n String path = ctx.coveredFilePath; \n if (path.indexOf('src/legacy/core_plugins/kibana/') == 0) {\n\n if (path.indexOf('src/legacy/core_plugins/kibana/common/utils') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/migrations') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/dashboard/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/dev_tools/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/discover/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/home') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/home/np_ready/') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/local_application_service/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/kibana/public/management/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/core_plugins/kibana/server/lib') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/core_plugins/kibana/server/lib/management/saved_objects') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/core_plugins/kibana/server/routes/api/management/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/core_plugins/kibana/server/routes/api/import/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/core_plugins/kibana/server/routes/api/export/') == 0) ctx.team = 'kibana-platform';\n else ctx.team = 'unknown';\n\n } else if (path.indexOf('src/legacy/core_plugins/') == 0) {\n\n if (path.indexOf('src/legacy/core_plugins/apm_oss/') == 0) ctx.team = 'apm-ui';\n else if (path.indexOf('src/legacy/core_plugins/console_legacy') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/elasticsearch') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/core_plugins/embeddable_api/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/core_plugins/input_control_vis') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/interpreter/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/core_plugins/kibana_react/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/core_plugins/newsfeed') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/legacy/core_plugins/region_map') == 0) ctx.team = 'maps';\n else if (path.indexOf('src/legacy/core_plugins/status_page/public') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/core_plugins/testbed') == 0) ctx.team = 'kibana-platform';\n // else if (path.indexOf('src/legacy/core_plugins/tests_bundle/') == 0) ctx.team = 'kibana-platform';\n \n else if (path.indexOf('src/legacy/core_plugins/tile_map') == 0) ctx.team = 'maps';\n else if (path.indexOf('src/legacy/core_plugins/timelion') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/ui_metric/') == 0) ctx.team = 'pulse';\n else if (path.indexOf('src/legacy/core_plugins/vis_type_tagcloud') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/vis_type_vega') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/vis_type_vislib/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/core_plugins/visualizations/') == 0) ctx.team = 'kibana-app-arch';\n else ctx.team = 'unknown';\n\n } else if (path.indexOf('src/legacy/server/') == 0) {\n\n if (path.indexOf('src/legacy/server/config/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/server/http/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/server/i18n/') == 0) ctx.team = 'kibana-localization';\n else if (path.indexOf('src/legacy/server/index_patterns/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/server/keystore/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/legacy/server/logging/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/server/pid/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/legacy/server/sample_data/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/server/sass/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/legacy/server/saved_objects/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/server/status/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/server/url_shortening/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/server/utils/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/legacy/server/warnings/') == 0) ctx.team = 'kibana-operations';\n else ctx.team = 'unknown';\n\n } else if (path.indexOf('src/legacy/ui') == 0) {\n\n if (path.indexOf('src/legacy/ui/public/field_editor') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/ui/public/timefilter') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/ui/public/management') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/legacy/ui/public/state_management') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/legacy/ui/public/new_platform') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/ui/public/plugin_discovery') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/ui/public/chrome') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/ui/public/notify') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/ui/public/documentation_links') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/ui/public/autoload') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/legacy/ui/public/capabilities') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('src/legacy/ui/public/apm') == 0) ctx.team = 'apm-ui';\n\n } else if (path.indexOf('src/plugins/') == 0) {\n\n if (path.indexOf('src/plugins/advanced_settings/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/apm_oss/') == 0) ctx.team = 'apm-ui';\n else if (path.indexOf('src/plugins/bfetch/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/charts/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/charts/public/static/color_maps') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/console/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('src/plugins/dashboard/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/data/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/dev_tools/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('src/plugins/discover/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/embeddable/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/es_ui_shared/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('src/plugins/expressions/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/home/public') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/plugins/home/server/tutorials') == 0) ctx.team = 'observability';\n else if (path.indexOf('src/plugins/home/server/services/') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/plugins/home/') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/plugins/index_pattern_management/public/service') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/index_pattern_management/public') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/input_control_vis/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/inspector/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/kibana_legacy/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/kibana_react/public/code_editor') == 0) ctx.team = 'kibana-canvas';\n else if (path.indexOf('src/plugins/kibana_react/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/kibana_utils/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/management/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/kibana_usage_collection/') == 0) ctx.team = 'pulse';\n else if (path.indexOf('src/plugins/legacy_export/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/plugins/maps_legacy/') == 0) ctx.team = 'maps';\n else if (path.indexOf('src/plugins/region_map/') == 0) ctx.team = 'maps';\n else if (path.indexOf('src/plugins/tile_map/') == 0) ctx.team = 'maps';\n else if (path.indexOf('src/plugins/timelion') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/navigation/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/newsfeed') == 0) ctx.team = 'kibana-core-ui';\n else if (path.indexOf('src/plugins/saved_objects_management/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/plugins/saved_objects/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/share/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/status_page/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/plugins/telemetry') == 0) ctx.team = 'pulse';\n else if (path.indexOf('src/plugins/testbed/server/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/plugins/ui_actions/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/usage_collection/') == 0) ctx.team = 'pulse';\n else if (path.indexOf('src/plugins/vis_default_editor') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/vis_type') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('src/plugins/visualizations/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('src/plugins/visualize/') == 0) ctx.team = 'kibana-app';\n else ctx.team = 'unknown';\n\n } else if (path.indexOf('x-pack/legacy/') == 0) {\n\n if (path.indexOf('x-pack/legacy/plugins/actions/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/legacy/plugins/alerting/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/legacy/plugins/apm/') == 0) ctx.team = 'apm-ui';\n else if (path.indexOf('x-pack/legacy/plugins/beats_management/') == 0) ctx.team = 'beats';\n else if (path.indexOf('x-pack/legacy/plugins/canvas/') == 0) ctx.team = 'kibana-canvas';\n else if (path.indexOf('x-pack/legacy/plugins/cross_cluster_replication/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/plugins/dashboard_mode/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('x-pack/legacy/plugins/encrypted_saved_objects/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('x-pack/legacy/plugins/index_management/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/plugins/infra/') == 0) ctx.team = 'logs-metrics-ui';\n else if (path.indexOf('x-pack/legacy/plugins/ingest_manager/') == 0) ctx.team = 'ingest-management';\n else if (path.indexOf('x-pack/legacy/plugins/license_management/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/plugins/maps/') == 0) ctx.team = 'kibana-gis';\n else if (path.indexOf('x-pack/legacy/plugins/ml/') == 0) ctx.team = 'ml-ui';\n else if (path.indexOf('x-pack/legacy/plugins/monitoring/') == 0) ctx.team = 'stack-monitoring-ui';\n else if (path.indexOf('x-pack/legacy/plugins/reporting') == 0) ctx.team = 'kibana-reporting';\n else if (path.indexOf('x-pack/legacy/plugins/rollup/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/plugins/security/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('x-pack/legacy/plugins/siem/') == 0) ctx.team = 'siem';\n else if (path.indexOf('x-pack/legacy/plugins/siem/server/lib/detection_engine/rules/prepackaged_rules') == 0) ctx.team = 'security-intelligence-analytics';\n else if (path.indexOf('x-pack/legacy/plugins/snapshot_restore/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/plugins/spaces/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('x-pack/legacy/plugins/task_manager') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/legacy/plugins/triggers_actions_ui/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/legacy/plugins/upgrade_assistant/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/plugins/uptime') == 0) ctx.team = 'uptime';\n else if (path.indexOf('x-pack/legacy/plugins/xpack_main/server/') == 0) ctx.team = 'kibana-platform';\n\n else if (path.indexOf('x-pack/legacy/server/lib/create_router/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/legacy/server/lib/check_license/') == 0) ctx.team = 'es-ui'; \n else if (path.indexOf('x-pack/legacy/server/lib/') == 0) ctx.team = 'kibana-platform'; \n else ctx.team = 'unknown';\n\n } else if (path.indexOf('x-pack/plugins/') == 0) {\n\n if (path.indexOf('x-pack/plugins/actions/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/plugins/advanced_ui_actions/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('x-pack/plugins/alerts') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/plugins/alerting_builtins') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/plugins/apm/') == 0) ctx.team = 'apm-ui';\n else if (path.indexOf('x-pack/plugins/beats_management/') == 0) ctx.team = 'beats';\n else if (path.indexOf('x-pack/plugins/canvas/') == 0) ctx.team = 'kibana-canvas';\n else if (path.indexOf('x-pack/plugins/case') == 0) ctx.team = 'siem';\n else if (path.indexOf('x-pack/plugins/cloud/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('x-pack/plugins/code/') == 0) ctx.team = 'code';\n else if (path.indexOf('x-pack/plugins/console_extensions/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/cross_cluster_replication/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/dashboard_enhanced') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('x-pack/plugins/dashboard_mode') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('x-pack/plugins/discover_enhanced') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('x-pack/plugins/embeddable_enhanced') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('x-pack/plugins/data_enhanced/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('x-pack/plugins/drilldowns/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('x-pack/plugins/encrypted_saved_objects/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('x-pack/plugins/endpoint/') == 0) ctx.team = 'endpoint-app-team';\n else if (path.indexOf('x-pack/plugins/es_ui_shared/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/event_log/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/plugins/features/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('x-pack/plugins/file_upload') == 0) ctx.team = 'kibana-gis';\n else if (path.indexOf('x-pack/plugins/global_search') == 0) ctx.team = 'kibana-platform';\n \n else if (path.indexOf('x-pack/plugins/graph/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('x-pack/plugins/grokdebugger/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/index_lifecycle_management/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/index_management/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/infra/') == 0) ctx.team = 'logs-metrics-ui';\n else if (path.indexOf('x-pack/plugins/ingest_manager/') == 0) ctx.team = 'ingest-management';\n else if (path.indexOf('x-pack/plugins/ingest_pipelines/') == 0) ctx.team = 'es-ui';\n \n else if (path.indexOf('x-pack/plugins/lens/') == 0) ctx.team = 'kibana-app';\n else if (path.indexOf('x-pack/plugins/license_management/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/licensing/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('x-pack/plugins/lists/') == 0) ctx.team = 'siem';\n else if (path.indexOf('x-pack/plugins/logstash') == 0) ctx.team = 'logstash';\n else if (path.indexOf('x-pack/plugins/maps/') == 0) ctx.team = 'kibana-gis';\n else if (path.indexOf('x-pack/plugins/maps_legacy_licensing') == 0) ctx.team = 'maps';\n else if (path.indexOf('x-pack/plugins/ml/') == 0) ctx.team = 'ml-ui';\n else if (path.indexOf('x-pack/plugins/monitoring') == 0) ctx.team = 'stack-monitoring-ui';\n else if (path.indexOf('x-pack/plugins/observability/') == 0) ctx.team = 'apm-ui';\n else if (path.indexOf('x-pack/plugins/oss_telemetry/') == 0) ctx.team = 'pulse';\n else if (path.indexOf('x-pack/plugins/painless_lab/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/remote_clusters/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/reporting') == 0) ctx.team = 'kibana-reporting';\n else if (path.indexOf('x-pack/plugins/rollup/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/searchprofiler/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/security/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('x-pack/plugins/security_solution/') == 0) ctx.team = 'siem';\n \n else if (path.indexOf('x-pack/plugins/siem/server/lib/detection_engine/rules/prepackaged_rules') == 0) ctx.team = 'security-intelligence-analytics';\n else if (path.indexOf('x-pack/plugins/siem/') == 0) ctx.team = 'siem';\n else if (path.indexOf('x-pack/plugins/snapshot_restore/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/spaces/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('x-pack/plugins/task_manager/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/plugins/telemetry_collection_xpack/') == 0) ctx.team = 'pulse';\n else if (path.indexOf('x-pack/plugins/transform/') == 0) ctx.team = 'ml-ui';\n else if (path.indexOf('x-pack/plugins/translations/') == 0) ctx.team = 'kibana-localization';\n else if (path.indexOf('x-pack/plugins/triggers_actions_ui/') == 0) ctx.team = 'kibana-alerting-services';\n else if (path.indexOf('x-pack/plugins/upgrade_assistant/') == 0) ctx.team = 'es-ui';\n else if (path.indexOf('x-pack/plugins/ui_actions_enhanced') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('x-pack/plugins/uptime') == 0) ctx.team = 'uptime';\n \n else if (path.indexOf('x-pack/plugins/watcher/') == 0) ctx.team = 'es-ui';\n else ctx.team = 'unknown';\n\n } else if (path.indexOf('packages') == 0) {\n\n if (path.indexOf('packages/kbn-analytics/') == 0) ctx.team = 'pulse';\n else if (path.indexOf('packages/kbn-babel') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-config-schema/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('packages/elastic-datemath') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('packages/kbn-dev-utils') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-es/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-eslint') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-expect') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-i18n/') == 0) ctx.team = 'kibana-localization';\n else if (path.indexOf('packages/kbn-interpreter/') == 0) ctx.team = 'kibana-app-arch';\n else if (path.indexOf('packages/kbn-optimizer/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-pm/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-test/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-test-subj-selector/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('packages/kbn-ui-framework/') == 0) ctx.team = 'kibana-design';\n else if (path.indexOf('packages/kbn-ui-shared-deps/') == 0) ctx.team = 'kibana-operations';\n else ctx.team = 'unknown';\n\n } else {\n\n if (path.indexOf('config/kibana.yml') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/apm.js') == 0) ctx.team = 'apm-ui';\n else if (path.indexOf('src/core/') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('src/core/public/i18n/') == 0) ctx.team = 'kibana-localization';\n else if (path.indexOf('src/core/server/csp/') == 0) ctx.team = 'kibana-security';\n else if (path.indexOf('src/dev/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/dev/i18n/') == 0) ctx.team = 'kibana-localization';\n else if (path.indexOf('src/dev/run_check_published_api_changes.ts') == 0) ctx.team = 'kibana-platform';\n else if (path.indexOf('packages/kbn-es-archiver/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/optimize/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/setup_node_env/') == 0) ctx.team = 'kibana-operations';\n else if (path.indexOf('src/test_utils/') == 0) ctx.team = 'kibana-operations'; \n else ctx.team = 'unknown';\n }"}}]} diff --git a/src/dev/jest/config.js b/src/dev/jest/config.js index e11668ab57f55..5249b7d652790 100644 --- a/src/dev/jest/config.js +++ b/src/dev/jest/config.js @@ -52,7 +52,6 @@ export default { '!packages/kbn-ui-framework/src/services/**/*/index.js', 'src/legacy/core_plugins/**/*.{js,mjs,jsx,ts,tsx}', '!src/legacy/core_plugins/**/{__test__,__snapshots__}/**/*', - '!src/legacy/core_plugins/tests_bundle/**', ], moduleNameMapper: { '@elastic/eui$': '/node_modules/@elastic/eui/test-env', diff --git a/src/dev/precommit_hook/casing_check_config.js b/src/dev/precommit_hook/casing_check_config.js index 1e4f048be8ea4..864bf7515053c 100644 --- a/src/dev/precommit_hook/casing_check_config.js +++ b/src/dev/precommit_hook/casing_check_config.js @@ -124,7 +124,6 @@ export const IGNORE_DIRECTORY_GLOBS = [ export const TEMPORARILY_IGNORED_PATHS = [ 'src/legacy/core_plugins/console/public/src/directives/helpExample.txt', 'src/legacy/core_plugins/console/public/src/sense_editor/theme-sense-dark.js', - 'src/legacy/core_plugins/tests_bundle/webpackShims/angular-mocks.js', 'src/legacy/core_plugins/tile_map/public/__tests__/scaledCircleMarkers.png', 'src/legacy/core_plugins/tile_map/public/__tests__/shadedCircleMarkers.png', 'src/legacy/core_plugins/tile_map/public/__tests__/shadedGeohashGrid.png', diff --git a/src/dev/renovate/config.ts b/src/dev/renovate/config.ts deleted file mode 100644 index c9688fc0ae0bd..0000000000000 --- a/src/dev/renovate/config.ts +++ /dev/null @@ -1,135 +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 { RENOVATE_PACKAGE_GROUPS } from './package_groups'; -import { PACKAGE_GLOBS } from './package_globs'; -import { wordRegExp, maybeFlatMap, maybeMap, getTypePackageName } from './utils'; - -const DEFAULT_LABELS = ['release_note:skip', 'Team:Operations', 'renovate', 'v8.0.0', 'v7.10.0']; - -export const RENOVATE_CONFIG = { - extends: ['config:base'], - - includePaths: PACKAGE_GLOBS, - - /** - * Only submit PRs to these branches, we will manually backport PRs for now - */ - baseBranches: ['master'], - - /** - * Labels added to PRs opened by renovate - */ - labels: DEFAULT_LABELS, - - /** - * Config customizations for major version upgrades - */ - major: { - labels: [...DEFAULT_LABELS, 'renovate:major'], - }, - - // TODO: remove this once we've caught up on upgrades - /** - * When there is a major and minor update available, only offer the major update, - * the list of all upgrades is too overwhelming for now. - */ - separateMajorMinor: false, - - /** - * Enable creation of a "Master Issue" within the repository. This - * Master Issue is akin to a mini dashboard and contains a list of all - * PRs pending, open, closed (unmerged) or in error. - */ - masterIssue: true, - - /** - * Whether updates should require manual approval from within the - * Master Issue before creation. - * - * We can turn this off once we've gotten through the backlog of - * outdated packages. - */ - masterIssueApproval: true, - - /** - * Policy for how to modify/update existing ranges - * bump = e.g. bump the range even if the new version satisifies the existing range, e.g. ^1.0.0 -> ^1.1.0 - */ - rangeStrategy: 'bump', - - npm: { - /** - * This deletes and re-creates the lock file, which we will only want - * to turn on once we've updated all our deps and enabled version pinning - */ - lockFileMaintenance: { enabled: false }, - - /** - * Define groups of packages that should be updated/configured together - */ - packageRules: [ - ...RENOVATE_PACKAGE_GROUPS.map((group) => ({ - groupSlug: group.name, - groupName: `${group.name} related packages`, - packagePatterns: maybeMap(group.packageWords, (word) => wordRegExp(word).source), - packageNames: maybeFlatMap(group.packageNames, (name) => [name, getTypePackageName(name)]), - labels: group.extraLabels && [...DEFAULT_LABELS, ...group.extraLabels], - enabled: group.enabled === false ? false : undefined, - allowedVersions: group.allowedVersions || undefined, - reviewers: group.reviewers || undefined, - masterIssueApproval: group.autoOpenPr ? false : undefined, - })).sort((a, b) => a.groupName.localeCompare(b.groupName)), - - // internal/local packages - { - packagePatterns: ['^@kbn/.*'], - enabled: false, - }, - ], - }, - - /** - * Limit the number of active PRs renovate will allow - * 0 (default) means no limit - */ - prConcurrentLimit: 0, - - /** - * Disable vulnerability alert handling, we handle that separately - */ - vulnerabilityAlerts: { - enabled: false, - }, - - /** - * Disable automatic rebase on each change to base branch - */ - rebaseStalePrs: false, - - /** - * Disable automatic rebase on conflicts with the base branch - */ - rebaseConflictedPrs: false, - - /** - * Disable semantic commit formating - */ - semanticCommits: false, -}; diff --git a/src/dev/renovate/package_globs.ts b/src/dev/renovate/package_globs.ts deleted file mode 100644 index 825e6ffed0ec6..0000000000000 --- a/src/dev/renovate/package_globs.ts +++ /dev/null @@ -1,59 +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 { readFileSync } from 'fs'; - -import globby from 'globby'; - -import { REPO_ROOT } from '../constants'; - -export const PACKAGE_GLOBS = [ - 'package.json', - 'x-pack/package.json', - 'x-pack/legacy/plugins/*/package.json', - 'packages/*/package.json', - 'examples/*/package.json', - 'test/plugin_functional/plugins/*/package.json', - 'test/interpreter_functional/plugins/*/package.json', -]; - -export function getAllDepNames() { - const depNames = new Set(); - - for (const glob of PACKAGE_GLOBS) { - const files = globby.sync(glob, { - cwd: REPO_ROOT, - absolute: true, - }); - - for (const path of files) { - const pkg = JSON.parse(readFileSync(path, 'utf8')); - const deps = [ - ...Object.keys(pkg.dependencies || {}), - ...Object.keys(pkg.devDependencies || {}), - ]; - - for (const dep of deps) { - depNames.add(dep); - } - } - } - - return depNames; -} diff --git a/src/dev/renovate/package_groups.ts b/src/dev/renovate/package_groups.ts deleted file mode 100644 index d051f956d14df..0000000000000 --- a/src/dev/renovate/package_groups.ts +++ /dev/null @@ -1,230 +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 { getAllDepNames } from './package_globs'; -import { wordRegExp, unwrapTypesPackage } from './utils'; - -interface PackageGroup { - /** - * The group name, will be used for the branch name and in pr titles - */ - readonly name: string; - - /** - * Specific words that, when found in the package name, identify it as part of this group - */ - readonly packageWords?: string[]; - - /** - * Exact package names that should be included in this group - */ - readonly packageNames?: string[]; - - /** - * Extra labels to apply to PRs created for packages in this group - */ - readonly extraLabels?: string[]; - - /** - * A flag that will prevent renovatebot from telling us when there - * are updates. This should only be used in very special cases, like - * when we intend to never update a package. To just prevent a version - * upgrade consider support for the `allowedVersions` config, or just - * closing PRs to communicate to renovate that the specific upgrade - * should be ignored. - */ - readonly enabled?: false; - - /** - * A semver range defining allowed versions for a package group - * https://renovatebot.com/docs/configuration-options/#allowedversions - */ - readonly allowedVersions?: string; - - /** - * An array of users to request reviews from - */ - readonly reviewers?: string[]; - - /** - * Unless this is set to true, then PRs will only be opened when - * the corresponding checkbox is ticked in the master issue. - */ - readonly autoOpenPr?: boolean; -} - -export const RENOVATE_PACKAGE_GROUPS: PackageGroup[] = [ - { - name: 'eslint', - packageWords: ['eslint'], - }, - - { - name: 'babel', - packageWords: ['babel'], - packageNames: ['core-js', '@babel/preset-react', '@babel/preset-typescript'], - }, - - { - name: 'jest', - packageWords: ['jest'], - }, - - { - name: '@elastic/charts', - packageNames: ['@elastic/charts'], - reviewers: ['markov00'], - autoOpenPr: true, - }, - - { - name: 'mocha', - packageWords: ['mocha'], - }, - - { - name: 'karma', - packageWords: ['karma'], - }, - - { - name: 'gulp', - packageWords: ['gulp'], - }, - - { - name: 'grunt', - packageWords: ['grunt'], - }, - - { - name: 'angular', - packageWords: ['angular'], - }, - - { - name: 'd3', - packageWords: ['d3'], - }, - - { - name: 'react', - packageWords: ['react', 'redux', 'enzyme'], - packageNames: ['ngreact', 'recompose', 'prop-types', 'typescript-fsa-reducers', 'reselect'], - }, - - { - name: 'moment', - packageWords: ['moment'], - }, - - { - name: 'graphql', - packageWords: ['graphql', 'apollo'], - }, - - { - name: 'webpack', - packageWords: ['webpack', 'loader', 'acorn', 'terser'], - packageNames: ['mini-css-extract-plugin', 'chokidar'], - }, - - { - name: 'vega', - packageWords: ['vega'], - enabled: false, - }, - - { - name: 'language server', - packageNames: ['vscode-jsonrpc', 'vscode-languageserver', 'vscode-languageserver-types'], - }, - - { - name: 'hapi', - packageWords: ['hapi'], - packageNames: [ - 'hapi', - 'joi', - 'boom', - 'hoek', - 'h2o2', - '@elastic/good', - 'good-squeeze', - 'inert', - 'accept', - ], - }, - - { - name: 'dragselect', - packageNames: ['dragselect'], - extraLabels: [':ml'], - }, - - { - name: 'api-documenter', - packageNames: ['@microsoft/api-documenter', '@microsoft/api-extractor'], - enabled: false, - }, - - { - name: 'jsts', - packageNames: ['jsts'], - allowedVersions: '^1.6.2', - }, - - { - name: 'storybook', - packageWords: ['storybook'], - }, - - { - name: 'typescript', - packageWords: ['ts', 'typescript'], - packageNames: ['tslib'], - }, -]; - -/** - * Auto-define package groups for any `@types/*` deps that are not already in a group - */ -for (const dep of getAllDepNames()) { - const typesFor = unwrapTypesPackage(dep); - if (!typesFor) { - continue; - } - - // determine if one of the existing groups has typesFor in its - // packageNames or if any of the packageWords is in typesFor - const existing = RENOVATE_PACKAGE_GROUPS.some( - (group) => - (group.packageNames || []).includes(typesFor) || - (group.packageWords || []).some((word) => wordRegExp(word).test(typesFor)) - ); - - if (existing) { - continue; - } - - RENOVATE_PACKAGE_GROUPS.push({ - name: typesFor, - packageNames: [typesFor], - }); -} diff --git a/src/dev/renovate/run_build_renovate_config_cli.ts b/src/dev/renovate/run_build_renovate_config_cli.ts deleted file mode 100644 index db08bbc8a8f23..0000000000000 --- a/src/dev/renovate/run_build_renovate_config_cli.ts +++ /dev/null @@ -1,49 +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 { writeFileSync } from 'fs'; -import { resolve } from 'path'; -import json5 from 'json5'; -import dedent from 'dedent'; - -import { run } from '@kbn/dev-utils'; -import { REPO_ROOT } from '../constants'; -import { RENOVATE_CONFIG } from './config'; - -run( - async () => { - const genInfo = dedent` - /** - * PLEASE DO NOT MODIFY - * - * This file is automatically generated by running \`node scripts/build_renovate_config\` - * - */ - `; - - writeFileSync( - resolve(REPO_ROOT, 'renovate.json5'), - `${genInfo}\n${json5.stringify(RENOVATE_CONFIG, null, 2)}\n` - ); - }, - { - description: - 'Regenerate the renovate.json5 file at the root of the repo based on the config in src/dev/renovate', - } -); diff --git a/src/dev/renovate/utils.ts b/src/dev/renovate/utils.ts deleted file mode 100644 index a3c7e1b56d7b7..0000000000000 --- a/src/dev/renovate/utils.ts +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -export const maybeMap = (input: T[] | undefined, fn: (i: T) => T2) => - input ? input.map(fn) : undefined; - -export const maybeFlatMap = (input: T[] | undefined, fn: (i: T) => T2[]) => - input ? input.reduce((acc, i) => [...acc, ...fn(i)], [] as T2[]) : undefined; - -export const wordRegExp = (word: string) => new RegExp(`(\\b|_)${word}(\\b|_)`); - -export const getTypePackageName = (pkgName: string) => { - const scopedPkgRe = /^@(.+?)\/(.+?)$/; - const match = pkgName.match(scopedPkgRe); - return `@types/${match ? `${match[1]}__${match[2]}` : pkgName}`; -}; - -export const unwrapTypesPackage = (pkgName: string) => { - if (!pkgName.startsWith('@types')) { - return; - } - - const typesFor = pkgName.slice('@types/'.length); - - if (!typesFor.includes('__')) { - return typesFor; - } - - // @types packages use a convention for scoped packages, @types/org__name - const [org, name] = typesFor.split('__'); - return `@${org}/${name}`; -}; diff --git a/src/dev/run_check_published_api_changes.ts b/src/dev/run_check_published_api_changes.ts index 0aa450c8b002a..28e8570812915 100644 --- a/src/dev/run_check_published_api_changes.ts +++ b/src/dev/run_check_published_api_changes.ts @@ -17,8 +17,6 @@ * under the License. */ -/* eslint-disable no-console */ - import { ToolingLog } from '@kbn/dev-utils'; import { Extractor, @@ -35,6 +33,11 @@ import fs from 'fs'; import path from 'path'; import getopts from 'getopts'; +const log = new ToolingLog({ + level: 'info', + writeTo: process.stdout, +}); + /* * Step 1: execute build:types * This users tsconfig.types.json to generate types in `target/types` @@ -92,13 +95,13 @@ const apiExtractorConfig = (folder: string): ExtractorConfig => { }, }, }; - const con = ExtractorConfig.prepare({ + const cfg = ExtractorConfig.prepare({ configObject: config, configObjectFullPath: undefined, packageJsonFullPath: path.resolve('package.json'), }); - return con; + return cfg; }; const runBuildTypes = async () => { @@ -108,7 +111,7 @@ const runBuildTypes = async () => { const runApiDocumenter = async (folder: string) => { const sourceFolder = `./build/${folder}`; const targetFolder = `./docs/development/${folder}`; - console.log(`Generating docs from ${sourceFolder} into ${targetFolder}...`); + log.info(`Generating docs from ${sourceFolder} into ${targetFolder}...`); await execa('api-documenter', ['generate', '-i', sourceFolder, '-o', targetFolder], { preferLocal: true, }); @@ -117,7 +120,7 @@ const runApiDocumenter = async (folder: string) => { const renameExtractedApiPackageName = async (folder: string) => { const fname = getReportFileName(folder); const jsonApiFile = `build/${folder}/${fname}.api.json`; - console.log(`Updating ${jsonApiFile}...`); + log.info(`Updating ${jsonApiFile}...`); const json = JSON.parse(fs.readFileSync(jsonApiFile).toString()); json.name = json.canonicalReference = `kibana-plugin-${folder.replace(/\//g, '-')}`; fs.writeFileSync(jsonApiFile, JSON.stringify(json, null, 2)); @@ -127,11 +130,7 @@ const renameExtractedApiPackageName = async (folder: string) => { * Runs api-extractor with a custom logger in order to extract results from the process * */ -const runApiExtractor = ( - log: ToolingLog, - folder: string, - acceptChanges: boolean = false -): ExtractorResult => { +const runApiExtractor = (folder: string, acceptChanges: boolean = false): ExtractorResult => { const config = apiExtractorConfig(folder); const options = { // Indicates that API Extractor is running as part of a local build, @@ -177,13 +176,10 @@ interface Options { filter: string; } -async function run( - folder: string, - { log, opts }: { log: ToolingLog; opts: Options } -): Promise { +async function run(folder: string, { opts }: { opts: Options }): Promise { log.info(`${folder} API: checking for changes in API signature...`); - const { apiReportChanged, succeeded } = runApiExtractor(log, folder, opts.accept); + const { apiReportChanged, succeeded } = runApiExtractor(folder, opts.accept); // If we're not accepting changes and there's a failure, exit. if (!opts.accept && !succeeded) { @@ -209,11 +205,6 @@ async function run( } (async () => { - const log = new ToolingLog({ - level: 'info', - writeTo: process.stdout, - }); - const extraFlags: string[] = []; const opts = (getopts(process.argv.slice(2), { boolean: ['accept', 'docs', 'help'], @@ -276,26 +267,22 @@ async function run( return !(extraFlags.length > 0); } - try { - log.info(`Building types for api extractor...`); - await runBuildTypes(); - } catch (e) { - log.error(e); - return false; - } + log.info('Building types for api extractor...'); + await runBuildTypes(); + log.info('Types for api extractor has been built'); const filteredFolders = folders.filter((folder) => opts.filter.length ? folder.match(opts.filter) : true ); const results = []; for (const folder of filteredFolders) { - results.push(await run(folder, { log, opts })); + results.push(await run(folder, { opts })); } if (results.includes(false)) { process.exitCode = 1; } })().catch((e) => { - console.log(e); + log.error(e); process.exitCode = 1; }); diff --git a/src/dev/run_i18n_integrate.ts b/src/dev/run_i18n_integrate.ts index 23d66fae9f26e..ac1e957adfc99 100644 --- a/src/dev/run_i18n_integrate.ts +++ b/src/dev/run_i18n_integrate.ts @@ -108,6 +108,7 @@ run( const reporter = new ErrorReporter(); const messages: Map = new Map(); await list.run({ messages, reporter }); + process.exitCode = 0; } catch (error) { process.exitCode = 1; if (error instanceof ErrorReporter) { @@ -117,6 +118,7 @@ run( log.error(error); } } + process.exit(); }, { flags: { diff --git a/src/es_archiver/cli.ts b/src/es_archiver/cli.ts deleted file mode 100644 index 85e10b31a87ee..0000000000000 --- a/src/es_archiver/cli.ts +++ /dev/null @@ -1,183 +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. - */ - -/** *********************************************************** - * - * Run `node scripts/es_archiver --help` for usage information - * - *************************************************************/ - -import { resolve } from 'path'; -import { readFileSync } from 'fs'; -import { format as formatUrl } from 'url'; -import readline from 'readline'; -import { Command } from 'commander'; -import * as legacyElasticsearch from 'elasticsearch'; - -import { ToolingLog } from '@kbn/dev-utils'; -import { readConfigFile } from '@kbn/test'; - -import { EsArchiver } from './es_archiver'; - -const cmd = new Command('node scripts/es_archiver'); - -const resolveConfigPath = (v: string) => resolve(process.cwd(), v); -const defaultConfigPath = resolveConfigPath('test/functional/config.js'); - -cmd - .description(`CLI to manage archiving/restoring data in elasticsearch`) - .option('--es-url [url]', 'url for elasticsearch') - .option( - '--kibana-url [url]', - 'url for kibana (only necessary if using "load" or "unload" methods)' - ) - .option(`--dir [path]`, 'where archives are stored') - .option('--verbose', 'turn on verbose logging') - .option( - '--config [path]', - 'path to a functional test config file to use for default values', - resolveConfigPath, - defaultConfigPath - ) - .on('--help', () => { - // eslint-disable-next-line no-console - console.log(readFileSync(resolve(__dirname, './cli_help.txt'), 'utf8')); - }); - -cmd - .option('--raw', `don't gzip the archive`) - .command('save ') - .description('archive the into the --dir with ') - .action((name, indices) => execute((archiver, { raw }) => archiver.save(name, indices, { raw }))); - -cmd - .option('--use-create', 'use create instead of index for loading documents') - .command('load ') - .description('load the archive in --dir with ') - .action((name) => execute((archiver, { useCreate }) => archiver.load(name, { useCreate }))); - -cmd - .command('unload ') - .description('remove indices created by the archive in --dir with ') - .action((name) => execute((archiver) => archiver.unload(name))); - -cmd - .command('empty-kibana-index') - .description( - '[internal] Delete any Kibana indices, and initialize the Kibana index as Kibana would do on startup.' - ) - .action(() => execute((archiver) => archiver.emptyKibanaIndex())); - -cmd - .command('edit [prefix]') - .description( - 'extract the archives under the prefix, wait for edits to be completed, and then recompress the archives' - ) - .action((prefix) => - execute((archiver) => - archiver.edit(prefix, async () => { - const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, - }); - - await new Promise((resolveInput) => { - rl.question(`Press enter when you're done`, () => { - rl.close(); - resolveInput(); - }); - }); - }) - ) - ); - -cmd - .command('rebuild-all') - .description('[internal] read and write all archives in --dir to remove any inconsistencies') - .action(() => execute((archiver) => archiver.rebuildAll())); - -cmd.parse(process.argv); - -const missingCommand = cmd.args.every((a) => !((a as any) instanceof Command)); -if (missingCommand) { - execute(); -} - -async function execute(fn?: (esArchiver: EsArchiver, command: Command) => void): Promise { - try { - const log = new ToolingLog({ - level: cmd.verbose ? 'debug' : 'info', - writeTo: process.stdout, - }); - - if (cmd.config) { - // load default values from the specified config file - const config = await readConfigFile(log, resolve(cmd.config)); - if (!cmd.esUrl) cmd.esUrl = formatUrl(config.get('servers.elasticsearch')); - if (!cmd.kibanaUrl) cmd.kibanaUrl = formatUrl(config.get('servers.kibana')); - if (!cmd.dir) cmd.dir = config.get('esArchiver.directory'); - } - - // log and count all validation errors - let errorCount = 0; - const error = (msg: string) => { - errorCount++; - log.error(msg); - }; - - if (!fn) { - error(`Unknown command "${cmd.args[0]}"`); - } - - if (!cmd.esUrl) { - error('You must specify either --es-url or --config flags'); - } - - if (!cmd.dir) { - error('You must specify either --dir or --config flags'); - } - - // if there was a validation error display the help - if (errorCount) { - cmd.help(); - return; - } - - // run! - const client = new legacyElasticsearch.Client({ - host: cmd.esUrl, - log: cmd.verbose ? 'trace' : [], - }); - - try { - const esArchiver = new EsArchiver({ - log, - client, - dataDir: resolve(cmd.dir), - kibanaUrl: cmd.kibanaUrl, - }); - await fn!(esArchiver, cmd); - } finally { - await client.close(); - } - } catch (err) { - // eslint-disable-next-line no-console - console.log('FATAL ERROR', err.stack); - } -} diff --git a/src/es_archiver/cli_help.txt b/src/es_archiver/cli_help.txt deleted file mode 100644 index 1e2f8e40824ba..0000000000000 --- a/src/es_archiver/cli_help.txt +++ /dev/null @@ -1,15 +0,0 @@ - Examples: - Dump an index to disk: - Save all `logstash-*` indices from http://localhost:9200 to `snapshots/my_test_data` directory - - WARNING: If the `my_test_data` snapshot exists it will be deleted! - - $ node scripts/es_archiver save my_test_data logstash-* --dir snapshots - - Load an index from disk - Load the `my_test_data` snapshot from the archive directory and elasticsearch instance defined - in the `test/functional/config.js` config file - - WARNING: If the indices exist already they will be deleted! - - $ node scripts/es_archiver load my_test_data --config test/functional/config.js diff --git a/src/legacy/core_plugins/apm_oss/index.js b/src/legacy/core_plugins/apm_oss/index.js deleted file mode 100644 index b7ab6797c0de9..0000000000000 --- a/src/legacy/core_plugins/apm_oss/index.js +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import _ from 'lodash'; - -export default function apmOss(kibana) { - return new kibana.Plugin({ - id: 'apm_oss', - - config(Joi) { - return Joi.object({ - // enable plugin - enabled: Joi.boolean().default(true), - - // Kibana Index pattern - indexPattern: Joi.string().default('apm-*'), - - // ES Indices - sourcemapIndices: Joi.string().default('apm-*'), - errorIndices: Joi.string().default('apm-*'), - transactionIndices: Joi.string().default('apm-*'), - spanIndices: Joi.string().default('apm-*'), - metricsIndices: Joi.string().default('apm-*'), - onboardingIndices: Joi.string().default('apm-*'), - }).default(); - }, - - init(server) { - server.expose( - 'indexPatterns', - _.uniq( - [ - 'sourcemapIndices', - 'errorIndices', - 'transactionIndices', - 'spanIndices', - 'metricsIndices', - 'onboardingIndices', - ].map((type) => server.config().get(`apm_oss.${type}`)) - ) - ); - }, - }); -} diff --git a/src/legacy/core_plugins/apm_oss/package.json b/src/legacy/core_plugins/apm_oss/package.json deleted file mode 100644 index 4ca161f293e79..0000000000000 --- a/src/legacy/core_plugins/apm_oss/package.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "apm_oss", - "version": "kibana" -} diff --git a/src/legacy/core_plugins/kibana/public/__tests__/discover/legacy.ts b/src/legacy/core_plugins/kibana/public/__tests__/discover/legacy.ts deleted file mode 100644 index ecda2a8c15395..0000000000000 --- a/src/legacy/core_plugins/kibana/public/__tests__/discover/legacy.ts +++ /dev/null @@ -1,27 +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 { npSetup, npStart } from 'ui/new_platform'; -import { plugin } from '../../../../../../plugins/discover/public'; -import { coreMock } from '../../../../../../core/public/mocks'; -const context = coreMock.createPluginInitializerContext(); - -export const pluginInstance = plugin(context); -export const setup = pluginInstance.setup(npSetup.core, npSetup.plugins); -export const start = pluginInstance.start(npStart.core, npStart.plugins); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js b/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js deleted file mode 100644 index 29c301bf065c4..0000000000000 --- a/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js +++ /dev/null @@ -1,428 +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 angular from 'angular'; -import _ from 'lodash'; -import sinon from 'sinon'; -import expect from '@kbn/expect'; -import ngMock from 'ng_mock'; -import { getFakeRow, getFakeRowVals } from 'fixtures/fake_row'; -import $ from 'jquery'; -import { pluginInstance } from './legacy'; -import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; -import { setScopedHistory } from '../../../../../../plugins/discover/public/kibana_services'; -import { createBrowserHistory } from 'history'; - -describe('Doc Table', function () { - let $parentScope; - let $scope; - - // Stub out a minimal mapping of 4 fields - let mapping; - - let fakeRowVals; - let stubFieldFormatConverter; - beforeEach(() => pluginInstance.initializeServices()); - beforeEach(() => pluginInstance.initializeInnerAngular()); - before(() => setScopedHistory(createBrowserHistory())); - beforeEach(ngMock.module('app/discover')); - beforeEach( - ngMock.inject(function ($rootScope, Private) { - $parentScope = $rootScope; - $parentScope.indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - mapping = $parentScope.indexPattern.fields; - - // Stub `getConverterFor` for a field in the indexPattern to return mock data. - // Returns `val` if provided, otherwise generates fake data for the field. - fakeRowVals = getFakeRowVals('formatted', 0, mapping); - stubFieldFormatConverter = function ($root, field, val) { - const convertFn = (value, type, options) => { - if (val) { - return val; - } - const fieldName = _.get(options, 'field.name', null); - - return fakeRowVals[fieldName] || ''; - }; - - $root.indexPattern.fields.getByName(field).format.convert = convertFn; - $root.indexPattern.fields.getByName(field).format.getConverterFor = () => convertFn; - }; - }) - ); - - // Sets up the directive, take an element, and a list of properties to attach to the parent scope. - const init = function ($elem, props) { - ngMock.inject(function ($compile) { - _.assign($parentScope, props); - $compile($elem)($parentScope); - $elem.scope().$digest(); - $scope = $elem.isolateScope(); - }); - }; - - const destroy = function () { - $scope.$destroy(); - $parentScope.$destroy(); - }; - - // For testing column removing/adding for the header and the rows - const columnTests = function (elemType, parentElem) { - it('should create a time column if the timefield is defined', function () { - const childElems = parentElem.find(elemType); - expect(childElems.length).to.be(1); - }); - - it('should be able to add and remove columns', function () { - let childElems; - - stubFieldFormatConverter($parentScope, 'bytes'); - stubFieldFormatConverter($parentScope, 'request_body'); - - // Should include a column for toggling and the time column by default - $parentScope.columns = ['bytes']; - parentElem.scope().$digest(); - childElems = parentElem.find(elemType); - expect(childElems.length).to.be(2); - expect($(childElems[1]).text()).to.contain('bytes'); - - $parentScope.columns = ['bytes', 'request_body']; - parentElem.scope().$digest(); - childElems = parentElem.find(elemType); - expect(childElems.length).to.be(3); - expect($(childElems[2]).text()).to.contain('request_body'); - - $parentScope.columns = ['request_body']; - parentElem.scope().$digest(); - childElems = parentElem.find(elemType); - expect(childElems.length).to.be(2); - expect($(childElems[1]).text()).to.contain('request_body'); - }); - - it('should create only the toggle column if there is no timeField', function () { - delete parentElem.scope().indexPattern.timeFieldName; - parentElem.scope().$digest(); - - const childElems = parentElem.find(elemType); - expect(childElems.length).to.be(0); - }); - }; - - describe('kbnTableRow', function () { - const $elem = angular.element( - '' - ); - let row; - - beforeEach(function () { - row = getFakeRow(0, mapping); - - init($elem, { - row, - columns: [], - sorting: [], - filter: sinon.spy(), - maxLength: 50, - }); - }); - afterEach(function () { - destroy(); - }); - - describe('adding and removing columns', function () { - columnTests('[data-test-subj~="docTableField"]', $elem); - }); - - describe('details row', function () { - it('should be an empty tr by default', function () { - expect($elem.next().is('tr')).to.be(true); - expect($elem.next().text()).to.be(''); - }); - - it('should expand the detail row when the toggle arrow is clicked', function () { - $elem.children(':first-child').click(); - $scope.$digest(); - expect($elem.next().text()).to.not.be(''); - }); - - describe('expanded', function () { - let $details; - beforeEach(function () { - // Open the row - $scope.toggleRow(); - $scope.$digest(); - $details = $elem.next(); - }); - afterEach(function () { - // Close the row - $scope.toggleRow(); - $scope.$digest(); - }); - - it('should be a tr with something in it', function () { - expect($details.is('tr')).to.be(true); - expect($details.text()).to.not.be.empty(); - }); - }); - }); - }); - - describe('kbnTableRow meta', function () { - const $elem = angular.element( - '' - ); - let row; - - beforeEach(function () { - row = getFakeRow(0, mapping); - - init($elem, { - row: row, - columns: [], - sorting: [], - filtering: sinon.spy(), - maxLength: 50, - }); - - // Open the row - $scope.toggleRow(); - $scope.$digest(); - $elem.next(); - }); - - afterEach(function () { - destroy(); - }); - - /** this no longer works with the new plugin approach - it('should render even when the row source contains a field with the same name as a meta field', function () { - setTimeout(() => { - //this should be overridden by later changes - }, 100); - expect($details.find('tr').length).to.be(_.keys($parentScope.indexPattern.flattenHit($scope.row)).length); - }); */ - }); - - describe('row diffing', function () { - let $row; - let $scope; - let $root; - let $before; - - beforeEach( - ngMock.inject(function ($rootScope, $compile, Private) { - $root = $rootScope; - $root.row = getFakeRow(0, mapping); - $root.columns = ['_source']; - $root.sorting = []; - $root.filtering = sinon.spy(); - $root.maxLength = 50; - $root.mapping = mapping; - $root.indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - - // Stub field format converters for every field in the indexPattern - $root.indexPattern.fields.forEach((f) => stubFieldFormatConverter($root, f.name)); - - $row = $('').attr({ - 'kbn-table-row': 'row', - columns: 'columns', - sorting: 'sorting', - filtering: 'filtering', - 'index-pattern': 'indexPattern', - }); - - $scope = $root.$new(); - $compile($row)($scope); - $root.$apply(); - - $before = $row.find('td'); - expect($before).to.have.length(3); - expect($before.eq(0).text().trim()).to.be(''); - expect($before.eq(1).text().trim()).to.match(/^time_formatted/); - }) - ); - - afterEach(function () { - $row.remove(); - }); - - it('handles a new column', function () { - $root.columns.push('bytes'); - $root.$apply(); - - const $after = $row.find('td'); - expect($after).to.have.length(4); - expect($after[0]).to.be($before[0]); - expect($after[1]).to.be($before[1]); - expect($after[2]).to.be($before[2]); - expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); - }); - - it('handles two new columns at once', function () { - $root.columns.push('bytes'); - $root.columns.push('request_body'); - $root.$apply(); - - const $after = $row.find('td'); - expect($after).to.have.length(5); - expect($after[0]).to.be($before[0]); - expect($after[1]).to.be($before[1]); - expect($after[2]).to.be($before[2]); - expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); - expect($after.eq(4).text().trim()).to.match(/^request_body_formatted/); - }); - - it('handles three new columns in odd places', function () { - $root.columns = ['@timestamp', 'bytes', '_source', 'request_body']; - $root.$apply(); - - const $after = $row.find('td'); - expect($after).to.have.length(6); - expect($after[0]).to.be($before[0]); - expect($after[1]).to.be($before[1]); - expect($after.eq(2).text().trim()).to.match(/^@timestamp_formatted/); - expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); - expect($after[4]).to.be($before[2]); - expect($after.eq(5).text().trim()).to.match(/^request_body_formatted/); - }); - - it('handles a removed column', function () { - _.pull($root.columns, '_source'); - $root.$apply(); - - const $after = $row.find('td'); - expect($after).to.have.length(2); - expect($after[0]).to.be($before[0]); - expect($after[1]).to.be($before[1]); - }); - - it('handles two removed columns', function () { - // first add a column - $root.columns.push('@timestamp'); - $root.$apply(); - - const $mid = $row.find('td'); - expect($mid).to.have.length(4); - - $root.columns.pop(); - $root.columns.pop(); - $root.$apply(); - - const $after = $row.find('td'); - expect($after).to.have.length(2); - expect($after[0]).to.be($before[0]); - expect($after[1]).to.be($before[1]); - }); - - it('handles three removed random columns', function () { - // first add two column - $root.columns.push('@timestamp', 'bytes'); - $root.$apply(); - - const $mid = $row.find('td'); - expect($mid).to.have.length(5); - - $root.columns[0] = false; // _source - $root.columns[2] = false; // bytes - $root.columns = $root.columns.filter(Boolean); - $root.$apply(); - - const $after = $row.find('td'); - expect($after).to.have.length(3); - expect($after[0]).to.be($before[0]); - expect($after[1]).to.be($before[1]); - expect($after.eq(2).text().trim()).to.match(/^@timestamp_formatted/); - }); - - it('handles two columns with the same content', function () { - stubFieldFormatConverter($root, 'request_body', fakeRowVals.bytes); - - $root.columns.length = 0; - $root.columns.push('bytes'); - $root.columns.push('request_body'); - $root.$apply(); - - const $after = $row.find('td'); - expect($after).to.have.length(4); - expect($after.eq(2).text().trim()).to.match(/^bytes_formatted/); - expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); - }); - - it('handles two columns swapping position', function () { - $root.columns.push('bytes'); - $root.$apply(); - - const $mid = $row.find('td'); - expect($mid).to.have.length(4); - - $root.columns.reverse(); - $root.$apply(); - - const $after = $row.find('td'); - expect($after).to.have.length(4); - expect($after[0]).to.be($before[0]); - expect($after[1]).to.be($before[1]); - expect($after[2]).to.be($mid[3]); - expect($after[3]).to.be($mid[2]); - }); - - it('handles four columns all reversing position', function () { - $root.columns.push('bytes', 'response', '@timestamp'); - $root.$apply(); - - const $mid = $row.find('td'); - expect($mid).to.have.length(6); - - $root.columns.reverse(); - $root.$apply(); - - const $after = $row.find('td'); - expect($after).to.have.length(6); - expect($after[0]).to.be($before[0]); - expect($after[1]).to.be($before[1]); - expect($after[2]).to.be($mid[5]); - expect($after[3]).to.be($mid[4]); - expect($after[4]).to.be($mid[3]); - expect($after[5]).to.be($mid[2]); - }); - - it('handles multiple columns with the same name', function () { - $root.columns.push('bytes', 'bytes', 'bytes'); - $root.$apply(); - - const $after = $row.find('td'); - expect($after).to.have.length(6); - expect($after[0]).to.be($before[0]); - expect($after[1]).to.be($before[1]); - expect($after[2]).to.be($before[2]); - expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); - expect($after.eq(4).text().trim()).to.match(/^bytes_formatted/); - expect($after.eq(5).text().trim()).to.match(/^bytes_formatted/); - }); - }); -}); diff --git a/src/legacy/core_plugins/status_page/index.js b/src/legacy/core_plugins/status_page/index.js index 01991d8439a04..5a94eb9c77160 100644 --- a/src/legacy/core_plugins/status_page/index.js +++ b/src/legacy/core_plugins/status_page/index.js @@ -21,15 +21,10 @@ export default function (kibana) { return new kibana.Plugin({ uiExports: { app: { - title: 'Server Status', + title: 'Legacy Server Status', main: 'plugins/status_page/status_page', hidden: true, - url: '/status', - }, - injectDefaultVars(server) { - return { - isStatusPageAnonymous: server.config().get('status.allowAnonymous'), - }; + url: '/__legacy__/status', }, }, }); diff --git a/src/legacy/core_plugins/status_page/public/components/__snapshots__/metric_tiles.test.js.snap b/src/legacy/core_plugins/status_page/public/components/__snapshots__/metric_tiles.test.js.snap deleted file mode 100644 index 7d4b245021c4c..0000000000000 --- a/src/legacy/core_plugins/status_page/public/components/__snapshots__/metric_tiles.test.js.snap +++ /dev/null @@ -1,33 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`byte metric 1`] = ` - -`; - -exports[`float metric 1`] = ` - -`; - -exports[`general metric 1`] = ` - -`; - -exports[`millisecond metric 1`] = ` - -`; diff --git a/src/legacy/core_plugins/status_page/public/components/__snapshots__/server_status.test.js.snap b/src/legacy/core_plugins/status_page/public/components/__snapshots__/server_status.test.js.snap deleted file mode 100644 index 6ff046557afa3..0000000000000 --- a/src/legacy/core_plugins/status_page/public/components/__snapshots__/server_status.test.js.snap +++ /dev/null @@ -1,44 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`render 1`] = ` - - - -

- - Green - , - } - } - /> -

-
-
- - -

- My Computer -

-
-
-
-`; diff --git a/src/legacy/core_plugins/status_page/public/components/render.js b/src/legacy/core_plugins/status_page/public/components/render.js index b9462bf21797c..dca79d783a29a 100644 --- a/src/legacy/core_plugins/status_page/public/components/render.js +++ b/src/legacy/core_plugins/status_page/public/components/render.js @@ -20,24 +20,19 @@ import React from 'react'; import { render, unmountComponentAtNode } from 'react-dom'; import { I18nContext } from 'ui/i18n'; - -import StatusApp from './status_app'; +// just to import eui into legacy +import '@elastic/eui'; const STATUS_PAGE_DOM_NODE_ID = 'createStatusPageReact'; -export function renderStatusPage(buildNum, buildSha) { +export function renderStatusPage() { const node = document.getElementById(STATUS_PAGE_DOM_NODE_ID); if (!node) { return; } - render( - - - , - node - ); + render(Foo, node); } export function destroyStatusPage() { diff --git a/src/legacy/core_plugins/status_page/public/components/status_table.js b/src/legacy/core_plugins/status_page/public/components/status_table.js deleted file mode 100644 index 68b93153951cb..0000000000000 --- a/src/legacy/core_plugins/status_page/public/components/status_table.js +++ /dev/null @@ -1,82 +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 React, { Component } from 'react'; -import PropTypes from 'prop-types'; -import { State as StatePropType } from '../lib/prop_types'; -import { EuiBasicTable, EuiIcon } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; - -class StatusTable extends Component { - static propTypes = { - statuses: PropTypes.arrayOf( - PropTypes.shape({ - id: PropTypes.string.isRequired, // plugin id - state: StatePropType.isRequired, // state of the plugin - }) - ), // can be null - }; - - static columns = [ - { - field: 'state', - name: '', - render: (state) => , - width: '32px', - }, - { - field: 'id', - name: i18n.translate('statusPage.statusTable.columns.idHeader', { - defaultMessage: 'ID', - }), - }, - { - field: 'state', - name: i18n.translate('statusPage.statusTable.columns.statusHeader', { - defaultMessage: 'Status', - }), - render: (state) => {state.message}, - }, - ]; - - static getRowProps = ({ state }) => { - return { - className: `status-table-row-${state.uiColor}`, - }; - }; - - render() { - const { statuses } = this.props; - - if (!statuses) { - return null; - } - - return ( - - ); - } -} - -export default StatusTable; diff --git a/src/legacy/core_plugins/status_page/public/lib/load_status.js b/src/legacy/core_plugins/status_page/public/lib/load_status.js deleted file mode 100644 index d033e5f147d9d..0000000000000 --- a/src/legacy/core_plugins/status_page/public/lib/load_status.js +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import _ from 'lodash'; - -import chrome from 'ui/chrome'; -import { toastNotifications } from 'ui/notify'; -import { i18n } from '@kbn/i18n'; - -// Module-level error returned by notify.error -let errorNotif; - -/* -Returns an object of any keys that should be included for metrics. -*/ -function formatMetrics(data) { - if (!data.metrics) { - return null; - } - - return [ - { - name: i18n.translate('statusPage.metricsTiles.columns.heapTotalHeader', { - defaultMessage: 'Heap total', - }), - value: _.get(data.metrics, 'process.memory.heap.size_limit'), - type: 'byte', - }, - { - name: i18n.translate('statusPage.metricsTiles.columns.heapUsedHeader', { - defaultMessage: 'Heap used', - }), - value: _.get(data.metrics, 'process.memory.heap.used_in_bytes'), - type: 'byte', - }, - { - name: i18n.translate('statusPage.metricsTiles.columns.loadHeader', { - defaultMessage: 'Load', - }), - value: [ - _.get(data.metrics, 'os.load.1m'), - _.get(data.metrics, 'os.load.5m'), - _.get(data.metrics, 'os.load.15m'), - ], - type: 'float', - }, - { - name: i18n.translate('statusPage.metricsTiles.columns.resTimeAvgHeader', { - defaultMessage: 'Response time avg', - }), - value: _.get(data.metrics, 'response_times.avg_in_millis'), - type: 'ms', - }, - { - name: i18n.translate('statusPage.metricsTiles.columns.resTimeMaxHeader', { - defaultMessage: 'Response time max', - }), - value: _.get(data.metrics, 'response_times.max_in_millis'), - type: 'ms', - }, - { - name: i18n.translate('statusPage.metricsTiles.columns.requestsPerSecHeader', { - defaultMessage: 'Requests per second', - }), - value: - (_.get(data.metrics, 'requests.total') * 1000) / - _.get(data.metrics, 'collection_interval_in_millis'), - }, - ]; -} - -/** - * Reformat the backend data to make the frontend views simpler. - */ -function formatStatus(status) { - return { - id: status.id, - state: { - id: status.state, - title: status.title, - message: status.message, - uiColor: status.uiColor, - }, - }; -} - -async function fetchData() { - return fetch(chrome.addBasePath('/api/status'), { - method: 'get', - credentials: 'same-origin', - }); -} - -/* -Get the status from the server API and format it for display. - -`fetchFn` can be injected for testing, defaults to the implementation above. -*/ -async function loadStatus(fetchFn = fetchData) { - // Clear any existing error banner. - if (errorNotif) { - errorNotif.clear(); - errorNotif = null; - } - - let response; - - try { - response = await fetchFn(); - } catch (e) { - // If the fetch failed to connect, display an error and bail. - const serverIsDownErrorMessage = i18n.translate( - 'statusPage.loadStatus.serverIsDownErrorMessage', - { - defaultMessage: 'Failed to request server status. Perhaps your server is down?', - } - ); - - errorNotif = toastNotifications.addDanger(serverIsDownErrorMessage); - return e; - } - - if (response.status >= 400) { - // If the server does not respond with a successful status, display an error and bail. - const serverStatusCodeErrorMessage = i18n.translate( - 'statusPage.loadStatus.serverStatusCodeErrorMessage', - { - defaultMessage: 'Failed to request server status with status code {responseStatus}', - values: { responseStatus: response.status }, - } - ); - - errorNotif = toastNotifications.addDanger(serverStatusCodeErrorMessage); - return; - } - - const data = await response.json(); - - return { - name: data.name, - statuses: data.status.statuses.map(formatStatus), - serverState: formatStatus(data.status.overall).state, - metrics: formatMetrics(data), - }; -} - -export default loadStatus; diff --git a/src/legacy/core_plugins/status_page/public/lib/load_status.test.js b/src/legacy/core_plugins/status_page/public/lib/load_status.test.js deleted file mode 100644 index a0f1930ca7667..0000000000000 --- a/src/legacy/core_plugins/status_page/public/lib/load_status.test.js +++ /dev/null @@ -1,115 +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 './load_status.test.mocks'; -import loadStatus from './load_status'; - -// A faked response to the `fetch` call -const mockFetch = async () => ({ - status: 200, - json: async () => ({ - name: 'My computer', - status: { - overall: { - state: 'yellow', - title: 'Yellow', - }, - statuses: [ - { id: 'plugin:1', state: 'green', title: 'Green', message: 'Ready', uiColor: 'secondary' }, - { - id: 'plugin:2', - state: 'yellow', - title: 'Yellow', - message: 'Something is weird', - uiColor: 'warning', - }, - ], - }, - metrics: { - collection_interval_in_millis: 1000, - os: { - load: { - '1m': 4.1, - '5m': 2.1, - '15m': 0.1, - }, - }, - - process: { - memory: { - heap: { - size_limit: 1000000, - used_in_bytes: 100, - }, - }, - }, - - response_times: { - avg_in_millis: 4000, - max_in_millis: 8000, - }, - - requests: { - total: 400, - }, - }, - }), -}); - -describe('response processing', () => { - test('includes the name', async () => { - const data = await loadStatus(mockFetch); - expect(data.name).toEqual('My computer'); - }); - - test('includes the plugin statuses', async () => { - const data = await loadStatus(mockFetch); - expect(data.statuses).toEqual([ - { - id: 'plugin:1', - state: { id: 'green', title: 'Green', message: 'Ready', uiColor: 'secondary' }, - }, - { - id: 'plugin:2', - state: { id: 'yellow', title: 'Yellow', message: 'Something is weird', uiColor: 'warning' }, - }, - ]); - }); - - test('includes the serverState', async () => { - const data = await loadStatus(mockFetch); - expect(data.serverState).toEqual({ id: 'yellow', title: 'Yellow' }); - }); - - test('builds the metrics', async () => { - const data = await loadStatus(mockFetch); - const names = data.metrics.map((m) => m.name); - expect(names).toEqual([ - 'Heap total', - 'Heap used', - 'Load', - 'Response time avg', - 'Response time max', - 'Requests per second', - ]); - - const values = data.metrics.map((m) => m.value); - expect(values).toEqual([1000000, 100, [4.1, 2.1, 0.1], 4000, 8000, 400]); - }); -}); diff --git a/src/legacy/core_plugins/status_page/public/lib/load_status.test.mocks.js b/src/legacy/core_plugins/status_page/public/lib/load_status.test.mocks.js deleted file mode 100644 index ec633a429b2e0..0000000000000 --- a/src/legacy/core_plugins/status_page/public/lib/load_status.test.mocks.js +++ /dev/null @@ -1,38 +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 { - fatalErrorsServiceMock, - notificationServiceMock, - overlayServiceMock, -} from '../../../../../core/public/mocks'; - -jest.doMock('ui/new_platform', () => ({ - npSetup: { - core: { - fatalErrors: fatalErrorsServiceMock.createSetupContract(), - notifications: notificationServiceMock.createSetupContract(), - }, - }, - npStart: { - core: { - overlays: overlayServiceMock.createStartContract(), - }, - }, -})); diff --git a/src/legacy/core_plugins/status_page/public/lib/prop_types.js b/src/legacy/core_plugins/status_page/public/lib/prop_types.js deleted file mode 100644 index d1f665f97475b..0000000000000 --- a/src/legacy/core_plugins/status_page/public/lib/prop_types.js +++ /dev/null @@ -1,33 +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 PropTypes from 'prop-types'; - -export const State = PropTypes.shape({ - id: PropTypes.string.isRequired, - message: PropTypes.string, // optional - title: PropTypes.string, // optional - uiColor: PropTypes.string.isRequired, -}); - -export const Metric = PropTypes.shape({ - name: PropTypes.string.isRequired, - value: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number), PropTypes.number]).isRequired, - type: PropTypes.string, // optional -}); diff --git a/src/legacy/core_plugins/tests_bundle/find_source_files.js b/src/legacy/core_plugins/tests_bundle/find_source_files.js deleted file mode 100644 index eed88a5ecb8b0..0000000000000 --- a/src/legacy/core_plugins/tests_bundle/find_source_files.js +++ /dev/null @@ -1,64 +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. - */ - -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { fromRoot } from '../../../core/server/utils'; -import { chain } from 'lodash'; -import { resolve } from 'path'; -import { fromNode } from 'bluebird'; -import glob from 'glob-all'; - -const findSourceFiles = async (patterns, cwd = fromRoot('.')) => { - patterns = [].concat(patterns || []); - - const matches = await fromNode((cb) => { - glob( - patterns, - { - cwd: cwd, - ignore: [ - 'node_modules/**/*', - 'bower_components/**/*', - '**/_*.js', - '**/*.test.js', - '**/*.test.mocks.js', - '**/__mocks__/**/*', - ], - symlinks: findSourceFiles.symlinks, - statCache: findSourceFiles.statCache, - realpathCache: findSourceFiles.realpathCache, - cache: findSourceFiles.cache, - }, - cb - ); - }); - - return chain(matches) - .flatten() - .uniq() - .map((match) => resolve(cwd, match)) - .value(); -}; - -findSourceFiles.symlinks = {}; -findSourceFiles.statCache = {}; -findSourceFiles.realpathCache = {}; -findSourceFiles.cache = {}; - -export default findSourceFiles; diff --git a/src/legacy/core_plugins/tests_bundle/index.js b/src/legacy/core_plugins/tests_bundle/index.js deleted file mode 100644 index da7c1c4f4527e..0000000000000 --- a/src/legacy/core_plugins/tests_bundle/index.js +++ /dev/null @@ -1,180 +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 { createReadStream } from 'fs'; -import { resolve } from 'path'; - -import globby from 'globby'; -import MultiStream from 'multistream'; -import webpackMerge from 'webpack-merge'; - -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { fromRoot } from '../../../core/server/utils'; -import { replacePlaceholder } from '../../../optimize/public_path_placeholder'; -import findSourceFiles from './find_source_files'; -import { createTestEntryTemplate } from './tests_entry_template'; - -export default (kibana) => { - return new kibana.Plugin({ - config: (Joi) => { - return Joi.object({ - enabled: Joi.boolean().default(true), - instrument: Joi.boolean().default(false), - pluginId: Joi.string(), - }).default(); - }, - - uiExports: { - styleSheetPaths: resolve(__dirname, 'public/index.scss'), - async __bundleProvider__(kbnServer) { - const modules = new Set(); - - const { - config, - uiApps, - uiBundles, - plugins, - uiExports: { uiSettingDefaults = {} }, - } = kbnServer; - - const testGlobs = []; - - const testingPluginIds = config.get('tests_bundle.pluginId'); - - if (testingPluginIds) { - testingPluginIds.split(',').forEach((pluginId) => { - const plugin = plugins.find((plugin) => plugin.id === pluginId); - - if (!plugin) { - throw new Error('Invalid testingPluginId :: unknown plugin ' + pluginId); - } - - // add the modules from all of this plugins apps - for (const app of uiApps) { - if (app.getPluginId() === pluginId) { - modules.add(app.getMainModuleId()); - } - } - - testGlobs.push(`${plugin.publicDir}/**/__tests__/**/*.js`); - }); - } else { - // add all since we are not just focused on specific plugins - testGlobs.push('src/legacy/ui/public/**/*.js', '!src/legacy/ui/public/flot-charts/**/*'); - // add the modules from all of the apps - for (const app of uiApps) { - modules.add(app.getMainModuleId()); - } - - for (const plugin of plugins) { - testGlobs.push(`${plugin.publicDir}/**/__tests__/**/*.js`); - } - } - - const testFiles = await findSourceFiles(testGlobs); - for (const f of testFiles) modules.add(f); - - if (config.get('tests_bundle.instrument')) { - uiBundles.addPostLoader({ - test: /\.js$/, - exclude: /[\/\\](__tests__|node_modules|bower_components|webpackShims)[\/\\]/, - loader: 'istanbul-instrumenter-loader', - }); - } - - uiBundles.add({ - id: 'tests', - modules: [...modules], - template: createTestEntryTemplate(uiSettingDefaults), - extendConfig(webpackConfig) { - const mergedConfig = webpackMerge( - { - resolve: { - extensions: ['.karma_mock.js', '.karma_mock.tsx', '.karma_mock.ts'], - }, - node: { - fs: 'empty', - child_process: 'empty', - dns: 'empty', - net: 'empty', - tls: 'empty', - }, - }, - webpackConfig - ); - - /** - * [..] it removes the commons bundle creation from the webpack - * config when we're building the bundle for the browser tests. It - * shouldn't be created, and by default isn't, but something is - * triggering it in webpack which breaks the tests so if we just - * remove the optimization config it will never happen and the tests - * will keep working [..] - * - * TLDR: If you have any questions about this line, ask Spencer. - */ - delete mergedConfig.optimization.splitChunks.cacheGroups.commons; - - return mergedConfig; - }, - }); - - kbnServer.server.route({ - method: 'GET', - path: '/test_bundle/built_css.css', - async handler(_, h) { - const cssFiles = await globby( - testingPluginIds - ? testingPluginIds.split(',').map((id) => `built_assets/css/plugins/${id}/**/*.css`) - : `built_assets/css/**/*.css`, - { cwd: fromRoot('.'), absolute: true } - ); - - const stream = replacePlaceholder( - new MultiStream(cssFiles.map((path) => createReadStream(path))), - '/built_assets/css/' - ); - - return h.response(stream).code(200).type('text/css'); - }, - }); - - // Sets global variables normally set by the bootstrap.js script - kbnServer.server.route({ - path: '/test_bundle/karma/globals.js', - method: 'GET', - async handler(req, h) { - const basePath = config.get('server.basePath'); - - const file = `window.__kbnPublicPath__ = { 'kbn-ui-shared-deps': "${basePath}/bundles/kbn-ui-shared-deps/" };`; - - return h.response(file).header('content-type', 'application/json'); - }, - }); - }, - - __globalImportAliases__: { - ng_mock$: fromRoot('src/test_utils/public/ng_mock'), - 'angular-mocks$': require.resolve('./webpackShims/angular-mocks'), - fixtures: fromRoot('src/fixtures'), - test_utils: fromRoot('src/test_utils/public'), - }, - }, - }); -}; diff --git a/src/legacy/core_plugins/tests_bundle/package.json b/src/legacy/core_plugins/tests_bundle/package.json deleted file mode 100644 index 4d2df048d4164..0000000000000 --- a/src/legacy/core_plugins/tests_bundle/package.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "tests_bundle", - "version": "kibana" -} diff --git a/src/legacy/core_plugins/tests_bundle/public/index.scss b/src/legacy/core_plugins/tests_bundle/public/index.scss deleted file mode 100644 index d8dbf8d6dc885..0000000000000 --- a/src/legacy/core_plugins/tests_bundle/public/index.scss +++ /dev/null @@ -1,4 +0,0 @@ -// This file pulls some styles of NP plugins into the legacy test stylesheet -// so they are available for karma browser tests. -@import '../../../../plugins/vis_type_vislib/public/index'; -@import '../../../../plugins/visualizations/public/index'; diff --git a/src/legacy/core_plugins/tests_bundle/tests_entry_template.js b/src/legacy/core_plugins/tests_bundle/tests_entry_template.js deleted file mode 100644 index 28c26f08621eb..0000000000000 --- a/src/legacy/core_plugins/tests_bundle/tests_entry_template.js +++ /dev/null @@ -1,158 +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 { Type } from '@kbn/config-schema'; -import pkg from '../../../../package.json'; - -export const createTestEntryTemplate = (defaultUiSettings) => (bundle) => ` -/** - * Test entry file - * - * This is programmatically created and updated, do not modify - * - * context: ${bundle.getContext()} - * - */ - -import fetchMock from 'fetch-mock/es5/client'; -import { CoreSystem } from '__kibanaCore__'; - -// Fake uiCapabilities returned to Core in browser tests -const uiCapabilities = { - navLinks: { - myLink: true, - notMyLink: true, - }, - discover: { - showWriteControls: true - }, - visualize: { - save: true - }, - dashboard: { - showWriteControls: true - }, - timelion: { - save: true - }, - management: { - kibana: { - settings: true, - index_patterns: true, - objects: true - } - } -}; - -// Mock fetch for CoreSystem calls. -fetchMock.config.fallbackToNetwork = true; -fetchMock.post(/\\/api\\/core\\/capabilities/, { - status: 200, - body: JSON.stringify(uiCapabilities), - headers: { 'Content-Type': 'application/json' }, -}); - -// render the core system in a element not attached to the document as the -// default children of the body in the browser tests are needed for mocha and -// other test components to work -const rootDomElement = document.createElement('div'); - -const coreSystem = new CoreSystem({ - injectedMetadata: { - version: '1.2.3', - buildNumber: 1234, - legacyMode: true, - legacyMetadata: { - app: { - id: 'karma', - title: 'Karma', - }, - nav: [], - version: '1.2.3', - buildNum: 1234, - devMode: true, - uiSettings: { - defaults: ${JSON.stringify( - defaultUiSettings, - (key, value) => { - if (value instanceof Type) return null; - return value; - }, - 2 - ) - .split('\n') - .join('\n ')}, - user: {} - }, - nav: [] - }, - csp: { - warnLegacyBrowsers: false, - }, - capabilities: uiCapabilities, - uiPlugins: [], - vars: { - kbnIndex: '.kibana', - esShardTimeout: 1500, - esApiVersion: ${JSON.stringify(pkg.branch)}, - esRequestTimeout: '300000', - tilemapsConfig: { - deprecated: { - isOverridden: false, - config: { - options: { - } - } - } - }, - regionmapsConfig: { - layers: [] - }, - mapConfig: { - includeElasticMapsService: true, - emsFileApiUrl: 'https://vector-staging.maps.elastic.co', - emsTileApiUrl: 'https://tiles.maps.elastic.co', - }, - vegaConfig: { - enabled: true, - enableExternalUrls: true - }, - }, - }, - rootDomElement, - requireLegacyBootstrapModule: () => { - // wrapped in NODE_ENV check so the 'ui/test_harness' module - // is not included in the distributable - if (process.env.IS_KIBANA_DISTRIBUTABLE !== 'true') { - return require('ui/test_harness'); - } - - throw new Error('tests bundle is not available in the distributable'); - }, - requireNewPlatformShimModule: () => require('ui/new_platform'), - requireLegacyFiles: () => { - ${bundle.getRequires().join('\n ')} - } -}) - -coreSystem - .setup() - .then(() => { - return coreSystem.start(); - }); -`; diff --git a/src/legacy/core_plugins/tests_bundle/webpackShims/angular-mocks.js b/src/legacy/core_plugins/tests_bundle/webpackShims/angular-mocks.js deleted file mode 100644 index 24f794cb32990..0000000000000 --- a/src/legacy/core_plugins/tests_bundle/webpackShims/angular-mocks.js +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -require('angular'); -require('../../../../../node_modules/angular-mocks/angular-mocks.js'); diff --git a/src/legacy/server/kbn_server.d.ts b/src/legacy/server/kbn_server.d.ts index 40996500bfbe0..9bb091383ab13 100644 --- a/src/legacy/server/kbn_server.d.ts +++ b/src/legacy/server/kbn_server.d.ts @@ -43,7 +43,6 @@ import { import { LegacyConfig, ILegacyService, ILegacyInternals } from '../../core/server/legacy'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { UiPlugins } from '../../core/server/plugins'; -import { ApmOssPlugin } from '../core_plugins/apm_oss'; import { CallClusterWithRequest, ElasticsearchPlugin } from '../core_plugins/elasticsearch'; import { UsageCollectionSetup } from '../../plugins/usage_collection/server'; import { UiSettingsServiceFactoryOptions } from '../../legacy/ui/ui_settings/ui_settings_service_factory'; @@ -62,7 +61,6 @@ declare module 'hapi' { elasticsearch: ElasticsearchPlugin; kibana: any; spaces: any; - apm_oss: ApmOssPlugin; // add new plugin types here } diff --git a/src/legacy/server/status/index.js b/src/legacy/server/status/index.js index 377a5d74610a9..ab7ec471a67ff 100644 --- a/src/legacy/server/status/index.js +++ b/src/legacy/server/status/index.js @@ -19,7 +19,7 @@ import ServerStatus from './server_status'; import { Metrics } from './lib/metrics'; -import { registerStatusPage, registerStatusApi, registerStatsApi } from './routes'; +import { registerStatusApi, registerStatsApi } from './routes'; import Oppsy from 'oppsy'; import { cloneDeep } from 'lodash'; import { getOSInfo } from './lib/get_os_info'; @@ -53,7 +53,6 @@ export function statusMixin(kbnServer, server, config) { }); // init routes - registerStatusPage(kbnServer, server, config); registerStatusApi(kbnServer, server, config); registerStatsApi(usageCollection, server, config, kbnServer); diff --git a/src/legacy/server/status/routes/index.js b/src/legacy/server/status/routes/index.js index 720309c3fd749..12736a76d4915 100644 --- a/src/legacy/server/status/routes/index.js +++ b/src/legacy/server/status/routes/index.js @@ -17,6 +17,5 @@ * under the License. */ -export { registerStatusPage } from './page/register_status'; export { registerStatusApi } from './api/register_status'; export { registerStatsApi } from './api/register_stats'; diff --git a/src/legacy/server/status/routes/page/register_status.js b/src/legacy/server/status/routes/page/register_status.js deleted file mode 100644 index 47bd3c34eba59..0000000000000 --- a/src/legacy/server/status/routes/page/register_status.js +++ /dev/null @@ -1,53 +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 { wrapAuthConfig } from '../../wrap_auth_config'; - -export function registerStatusPage(kbnServer, server, config) { - const allowAnonymous = config.get('status.allowAnonymous'); - const wrapAuth = wrapAuthConfig(allowAnonymous); - - server.decorate('toolkit', 'renderStatusPage', async function () { - const app = server.getHiddenUiAppById('status_page'); - const h = this; - - let response; - // An unauthenticated (anonymous) user may not have access to the customized configuration. - // For this scenario, render with the default config. - if (app) { - response = allowAnonymous ? await h.renderAppWithDefaultConfig(app) : await h.renderApp(app); - } else { - h.response(kbnServer.status.toString()); - } - - if (response) { - return response.code(kbnServer.status.isGreen() ? 200 : 503); - } - }); - - server.route( - wrapAuth({ - method: 'GET', - path: '/status', - handler(request, h) { - return h.renderStatusPage(); - }, - }) - ); -} diff --git a/src/legacy/ui/public/test_harness/.eslintrc b/src/legacy/ui/public/test_harness/.eslintrc deleted file mode 100644 index b1b85968796dd..0000000000000 --- a/src/legacy/ui/public/test_harness/.eslintrc +++ /dev/null @@ -1,2 +0,0 @@ -rules: - no-console: 0 diff --git a/src/legacy/ui/public/test_harness/index.js b/src/legacy/ui/public/test_harness/index.js deleted file mode 100644 index d66a4b1d67214..0000000000000 --- a/src/legacy/ui/public/test_harness/index.js +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -export { bootstrap } from './test_harness'; diff --git a/src/legacy/ui/public/test_harness/test_harness.css b/src/legacy/ui/public/test_harness/test_harness.css deleted file mode 100644 index d0a0f50c55b9b..0000000000000 --- a/src/legacy/ui/public/test_harness/test_harness.css +++ /dev/null @@ -1,22 +0,0 @@ -/** - * This file is only for tests so it is it's own CSS - * to be imported directly by and only by this module. - */ - -body#test-harness-body { - /** - now that tests include the kibana styles, we have - to override the body { display: flex; } rule as it - prevents the visualizations from properly testing - their sizing - */ - display: block; -} - -body#test-harness-body #mocha-stats .progress { - /* bootstrap thinks it is the only one who will use ".progress" */ - height: auto; - background-color: transparent; - overflow: auto; - border-radius: 0; -} diff --git a/src/legacy/ui/public/test_harness/test_harness.js b/src/legacy/ui/public/test_harness/test_harness.js deleted file mode 100644 index 22c981fe0cf54..0000000000000 --- a/src/legacy/ui/public/test_harness/test_harness.js +++ /dev/null @@ -1,89 +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. - */ - -// chrome expects to be loaded first, let it get its way -import chrome from '../chrome'; - -import { parse as parseUrl } from 'url'; -import { Subject } from 'rxjs'; -import sinon from 'sinon'; -import { metadata } from '../metadata'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { UiSettingsClient } from '../../../../core/public/ui_settings'; - -import './test_harness.css'; -import 'ng_mock'; -import { setupTestSharding } from './test_sharding'; - -const { query } = parseUrl(window.location.href, true); -if (query && query.mocha) { - try { - window.mocha.setup(JSON.parse(query.mocha)); - } catch (error) { - throw new Error( - `'?mocha=${query.mocha}' query string param provided but it could not be parsed as json` - ); - } -} - -setupTestSharding(); - -before(() => { - // prevent accidental ajax requests - sinon.useFakeXMLHttpRequest(); -}); - -let stubUiSettings; -let done$; -function createStubUiSettings() { - if (stubUiSettings) { - done$.complete(); - } - done$ = new Subject(); - - stubUiSettings = new UiSettingsClient({ - api: { - async batchSet() { - return { settings: stubUiSettings.getAll() }; - }, - }, - onUpdateError: () => {}, - defaults: metadata.uiSettings.defaults, - initialSettings: {}, - done$, - }); -} - -createStubUiSettings(); -sinon.stub(chrome, 'getUiSettingsClient').callsFake(() => stubUiSettings); - -afterEach(function () { - createStubUiSettings(); -}); - -// Kick off mocha, called at the end of test entry files -export function bootstrap(targetDomElement) { - // allows test_harness.less to have higher priority selectors - targetDomElement.setAttribute('id', 'test-harness-body'); - - // load the hacks since we aren't actually bootstrapping the - // chrome, which is where the hacks would normally be loaded - require('uiExports/hacks'); - chrome.setupAngular(); -} diff --git a/src/legacy/ui/public/test_harness/test_sharding/find_test_bundle_url.js b/src/legacy/ui/public/test_harness/test_sharding/find_test_bundle_url.js deleted file mode 100644 index 53800d08ca05b..0000000000000 --- a/src/legacy/ui/public/test_harness/test_sharding/find_test_bundle_url.js +++ /dev/null @@ -1,39 +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. - */ - -/** - * We don't have a lot of options for passing arguments to the page that karma - * creates, so we tack some query string params onto the test bundle script url. - * - * This function finds that url by looking for a script tag that has - * the "/tests.bundle.js" segment - * - * @return {string} url - */ -export function findTestBundleUrl() { - const scriptTags = document.querySelectorAll('script[src]'); - const scriptUrls = [].map.call(scriptTags, (el) => el.getAttribute('src')); - const testBundleUrl = scriptUrls.find((url) => url.includes('/tests.bundle.js')); - - if (!testBundleUrl) { - throw new Error("test bundle url couldn't be found"); - } - - return testBundleUrl; -} diff --git a/src/legacy/ui/public/test_harness/test_sharding/get_shard_num.js b/src/legacy/ui/public/test_harness/test_sharding/get_shard_num.js deleted file mode 100644 index 55a33fc295191..0000000000000 --- a/src/legacy/ui/public/test_harness/test_sharding/get_shard_num.js +++ /dev/null @@ -1,47 +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 murmurHash3 from 'murmurhash3js'; - -// murmur hashes are 32bit unsigned integers -const MAX_HASH = Math.pow(2, 32); - -/** - * Determine the shard number for a suite by hashing - * its name and placing it based on the hash - * - * @param {number} shardTotal - the total number of shards - * @param {string} suiteName - the suite name to hash - * @return {number} shardNum - 1-based shard number - */ -export function getShardNum(shardTotal, suiteName) { - const hashIntsPerShard = MAX_HASH / shardTotal; - - const hashInt = murmurHash3.x86.hash32(suiteName); - - // murmur3 produces 32bit integers, so we devide it by the number of chunks - // to determine which chunk the suite should fall in. +1 because the current - // chunk is 1-based - const shardNum = Math.floor(hashInt / hashIntsPerShard) + 1; - - // It's not clear if hash32 can produce the MAX_HASH or not, - // but this just ensures that shard numbers don't go out of bounds - // and cause tests to be ignored unnecessarily - return Math.max(1, Math.min(shardNum, shardTotal)); -} diff --git a/src/legacy/ui/public/test_harness/test_sharding/get_sharding_params_from_url.js b/src/legacy/ui/public/test_harness/test_sharding/get_sharding_params_from_url.js deleted file mode 100644 index 65e41dbc84b63..0000000000000 --- a/src/legacy/ui/public/test_harness/test_sharding/get_sharding_params_from_url.js +++ /dev/null @@ -1,45 +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 { parse as parseUrl } from 'url'; - -/** - * This function extracts the relevant "shards" and "shard_num" - * params from the url. - * - * @param {string} testBundleUrl - * @return {object} params - * @property {number} params.shards - the total number of shards - * @property {number} params.shard_num - the current shard number, 1 based - */ -export function getShardingParamsFromUrl(url) { - const parsedUrl = parseUrl(url, true); - const parsedQuery = parsedUrl.query || {}; - - const params = {}; - if (parsedQuery.shards) { - params.shards = parseInt(parsedQuery.shards, 10); - } - - if (parsedQuery.shard_num) { - params.shard_num = parseInt(parsedQuery.shard_num, 10); - } - - return params; -} diff --git a/src/legacy/ui/public/test_harness/test_sharding/index.js b/src/legacy/ui/public/test_harness/test_sharding/index.js deleted file mode 100644 index cdca50725a058..0000000000000 --- a/src/legacy/ui/public/test_harness/test_sharding/index.js +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -export { setupTestSharding } from './setup_test_sharding'; diff --git a/src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js b/src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js deleted file mode 100644 index fce1876162387..0000000000000 --- a/src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js +++ /dev/null @@ -1,69 +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 { uniq, defaults } from 'lodash'; - -import { findTestBundleUrl } from './find_test_bundle_url'; -import { getShardingParamsFromUrl } from './get_sharding_params_from_url'; -import { setupTopLevelDescribeFilter } from './setup_top_level_describe_filter'; -import { getShardNum } from './get_shard_num'; - -const DEFAULT_PARAMS = { - shards: 1, - shard_num: 1, -}; - -export function setupTestSharding() { - const pageUrl = window.location.href; - const bundleUrl = findTestBundleUrl(); - - // supports overriding params via the debug page - // url in dev mode - const params = defaults( - {}, - getShardingParamsFromUrl(pageUrl), - getShardingParamsFromUrl(bundleUrl), - DEFAULT_PARAMS - ); - - const { shards: shardTotal, shard_num: shardNum } = params; - if (shardNum < 1 || shardNum > shardTotal) { - throw new TypeError( - `shard_num param of ${shardNum} must be greater 0 and less than the total, ${shardTotal}` - ); - } - - // track and log the number of ignored describe calls - const ignoredDescribeShards = []; - before(() => { - const ignoredCount = ignoredDescribeShards.length; - const ignoredFrom = uniq(ignoredDescribeShards).join(', '); - console.log(`Ignored ${ignoredCount} top-level suites from ${ignoredFrom}`); - }); - - // Filter top-level describe statements as they come - setupTopLevelDescribeFilter((describeName) => { - const describeShardNum = getShardNum(shardTotal, describeName); - if (describeShardNum === shardNum) return true; - // track shard numbers that we ignore - ignoredDescribeShards.push(describeShardNum); - }); - - console.log(`ready to load tests for shard ${shardNum} of ${shardTotal}`); -} diff --git a/src/legacy/ui/public/test_harness/test_sharding/setup_top_level_describe_filter.js b/src/legacy/ui/public/test_harness/test_sharding/setup_top_level_describe_filter.js deleted file mode 100644 index 726f890077b94..0000000000000 --- a/src/legacy/ui/public/test_harness/test_sharding/setup_top_level_describe_filter.js +++ /dev/null @@ -1,125 +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. - */ - -/** - * Intercept all calls to mocha.describe() and determine - * which calls make it through using a filter function. - * - * The filter function is also only called for top-level - * describe() calls; all describe calls nested within another - * are allowed based on the filter value for the parent - * describe - * - * ## example - * - * assume tests that look like this: - * - * ```js - * describe('section 1', () => { - * describe('item 1', () => { - * - * }) - * }) - * ``` - * - * If the filter function returned true for "section 1" then "item 1" - * would automatically be defined. If it returned false for "section 1" - * then "section 1" would be ignored and "item 1" would never be defined - * - * @param {function} test - a function that takes the first argument - * passed to describe, the sections name, and - * returns true if the describe call should - * be delegated to mocha, any other value causes - * the describe call to be ignored - * @return {undefined} - */ -export function setupTopLevelDescribeFilter(test) { - const originalDescribe = window.describe; - - if (!originalDescribe) { - throw new TypeError( - 'window.describe must be defined by mocha before test sharding can be setup' - ); - } - - /** - * When describe is called it is likely to make additional, nested, - * calls to describe. We track how deeply nested we are at any time - * with a depth counter, `describeCallDepth`. - * - * Before delegating a describe call to mocha we increment - * that counter, and once mocha is done we decrement it. - * - * This way, we can check if `describeCallDepth > 0` at any time - * to know if we are already within a describe call. - * - * ```js - * // +1 - * describe('section 1', () => { - * // describeCallDepth = 1 - * // +1 - * describe('item 1', () => { - * // describeCallDepth = 2 - * }) - * // -1 - * }) - * // -1 - * // describeCallDepth = 0 - * ``` - * - * @type {Number} - */ - let describeCallDepth = 0; - - const describeInterceptor = function (describeName, describeBody) { - const context = this; - - const isTopLevelCall = describeCallDepth === 0; - const shouldIgnore = isTopLevelCall && Boolean(test(describeName)) === false; - if (shouldIgnore) return; - - /** - * we wrap the delegation to mocha in a try/finally block - * to ensure that our describeCallDepth counter stays up - * to date even if the call throws an error. - * - * note that try/finally won't actually catch the error, it - * will continue to propagate up the call stack - */ - let result; - try { - describeCallDepth += 1; - result = originalDescribe.call(context, describeName, describeBody); - } finally { - describeCallDepth -= 1; - } - return result; - }; - - // to allow describe.only calls. we dont need interceptor as it will call describe internally - describeInterceptor.only = originalDescribe.only; - describeInterceptor.skip = originalDescribe.skip; - - // ensure that window.describe isn't messed with by other code - Object.defineProperty(window, 'describe', { - configurable: false, - enumerable: true, - value: describeInterceptor, - }); -} diff --git a/src/legacy/ui/ui_exports/ui_export_defaults.js b/src/legacy/ui/ui_exports/ui_export_defaults.js index f7ee9aa056762..348f4ee77fab4 100644 --- a/src/legacy/ui/ui_exports/ui_export_defaults.js +++ b/src/legacy/ui/ui_exports/ui_export_defaults.js @@ -30,7 +30,6 @@ export const UI_EXPORT_DEFAULTS = { webpackAliases: { ui: resolve(ROOT, 'src/legacy/ui/public'), __kibanaCore__$: resolve(ROOT, 'src/core/public'), - test_harness: resolve(ROOT, 'src/test_harness/public'), }, styleSheetPaths: ['light', 'dark'].map((theme) => ({ diff --git a/src/legacy/ui/ui_render/ui_render_mixin.js b/src/legacy/ui/ui_render/ui_render_mixin.js index 7788aeaee72e5..12ae6390fdc22 100644 --- a/src/legacy/ui/ui_render/ui_render_mixin.js +++ b/src/legacy/ui/ui_render/ui_render_mixin.js @@ -204,13 +204,8 @@ export function uiRenderMixin(kbnServer, server, config) { async handler(req, h) { const id = req.params.id; const app = server.getUiAppById(id); - try { - if (kbnServer.status.isGreen()) { - return await h.renderApp(app); - } else { - return await h.renderStatusPage(); - } + return await h.renderApp(app); } catch (err) { throw Boom.boomify(err); } diff --git a/src/legacy/utils/__tests__/watch_stdio_for_line.js b/src/legacy/utils/__tests__/watch_stdio_for_line.js deleted file mode 100644 index 32d61658c1114..0000000000000 --- a/src/legacy/utils/__tests__/watch_stdio_for_line.js +++ /dev/null @@ -1,55 +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 execa from 'execa'; -import stripAnsi from 'strip-ansi'; -import sinon from 'sinon'; - -import { watchStdioForLine } from '../watch_stdio_for_line'; - -describe('src/legacy/utils/watch_stdio_for_line', function () { - const sandbox = sinon.sandbox.create(); - afterEach(() => sandbox.reset()); - - const onLogLine = sandbox.stub(); - const logFn = (line) => onLogLine(stripAnsi(line)); - - it('calls logFn with log lines', async () => { - const proc = execa(process.execPath, ['-e', 'console.log("hi")']); - - await watchStdioForLine(proc, logFn); - - // log output of the process - sinon.assert.calledWithExactly(onLogLine, sinon.match(/hi/)); - }); - - it('send the proc SIGKILL if it logs a line matching exitAfter regexp', async function () { - // fixture proc will exit after 10 seconds if sigint not received, but the test won't fail - // unless we see the log line `SIGINT not received`, so we let the test take up to 30 seconds - // for potentially huge delays here and there - this.timeout(30000); - - const proc = execa(process.execPath, [require.resolve('./fixtures/log_on_sigint')]); - - await watchStdioForLine(proc, logFn, /listening for SIGINT/); - - sinon.assert.calledWithExactly(onLogLine, sinon.match(/listening for SIGINT/)); - sinon.assert.neverCalledWith(onLogLine, sinon.match(/SIGINT not received/)); - }); -}); diff --git a/src/legacy/utils/index.js b/src/legacy/utils/index.js index a4c0cdf958fc2..4274fb2e4901a 100644 --- a/src/legacy/utils/index.js +++ b/src/legacy/utils/index.js @@ -21,7 +21,6 @@ export { BinderBase } from './binder'; export { BinderFor } from './binder_for'; export { deepCloneWithBuffers } from './deep_clone_with_buffers'; export { unset } from './unset'; -export { watchStdioForLine } from './watch_stdio_for_line'; export { IS_KIBANA_DISTRIBUTABLE } from './artifact_type'; export { IS_KIBANA_RELEASE } from './artifact_type'; diff --git a/src/legacy/utils/streams/index.d.ts b/src/legacy/utils/streams/index.d.ts index 5ef39b292c685..470b5d9fa3505 100644 --- a/src/legacy/utils/streams/index.d.ts +++ b/src/legacy/utils/streams/index.d.ts @@ -17,7 +17,7 @@ * under the License. */ -import { Readable, Transform, Writable, TransformOptions } from 'stream'; +import { Readable, Writable, Transform, TransformOptions } from 'stream'; export function concatStreamProviders( sourceProviders: Array<() => Readable>, diff --git a/src/plugins/dashboard/public/application/dashboard_app.tsx b/src/plugins/dashboard/public/application/dashboard_app.tsx index f101935b9288d..6690ae318fc8f 100644 --- a/src/plugins/dashboard/public/application/dashboard_app.tsx +++ b/src/plugins/dashboard/public/application/dashboard_app.tsx @@ -52,7 +52,10 @@ export interface DashboardAppScope extends ng.IScope { expandedPanel?: string; getShouldShowEditHelp: () => boolean; getShouldShowViewHelp: () => boolean; - updateQueryAndFetch: ({ query, dateRange }: { query: Query; dateRange?: TimeRange }) => void; + handleRefresh: ( + { query, dateRange }: { query?: Query; dateRange: TimeRange }, + isUpdate?: boolean + ) => void; topNavMenu: any; showAddPanel: any; showSaveQuery: boolean; diff --git a/src/plugins/dashboard/public/application/dashboard_app_controller.tsx b/src/plugins/dashboard/public/application/dashboard_app_controller.tsx index 8138e1c7f4dfd..3a4e49968626f 100644 --- a/src/plugins/dashboard/public/application/dashboard_app_controller.tsx +++ b/src/plugins/dashboard/public/application/dashboard_app_controller.tsx @@ -25,12 +25,11 @@ import React, { useState, ReactElement } from 'react'; import ReactDOM from 'react-dom'; import angular from 'angular'; -import { Subscription } from 'rxjs'; -import { map } from 'rxjs/operators'; +import { Observable, pipe, Subscription, merge } from 'rxjs'; +import { filter, map, debounceTime, mapTo, startWith, switchMap } from 'rxjs/operators'; import { History } from 'history'; import { SavedObjectSaveOpts } from 'src/plugins/saved_objects/public'; import { NavigationPublicPluginStart as NavigationStart } from 'src/plugins/navigation/public'; -import { TimeRange } from 'src/plugins/data/public'; import { DashboardEmptyScreen, DashboardEmptyScreenProps } from './dashboard_empty_screen'; import { @@ -38,11 +37,9 @@ import { esFilters, IndexPattern, IndexPatternsContract, - Query, QueryState, SavedQuery, syncQueryStateWithUrl, - UI_SETTINGS, } from '../../../data/public'; import { getSavedObjectFinder, SaveResult, showSaveModal } from '../../../saved_objects/public'; @@ -81,8 +78,8 @@ import { addFatalError, AngularHttpError, KibanaLegacyStart, - migrateLegacyQuery, subscribeWithScope, + migrateLegacyQuery, } from '../../../kibana_legacy/public'; export interface DashboardAppControllerDependencies extends RenderDeps { @@ -127,7 +124,6 @@ export class DashboardAppController { $route, $routeParams, dashboardConfig, - localStorage, indexPatterns, savedQueryService, embeddable, @@ -153,8 +149,8 @@ export class DashboardAppController { navigation, }: DashboardAppControllerDependencies) { const filterManager = queryService.filterManager; - const queryFilter = filterManager; const timefilter = queryService.timefilter.timefilter; + const queryStringManager = queryService.queryString; const isEmbeddedExternally = Boolean($routeParams.embed); // url param rules should only apply when embedded (e.g. url?embed=true) @@ -172,6 +168,10 @@ export class DashboardAppController { chrome.docTitle.change(dash.title); } + const incomingEmbeddable = embeddable + .getStateTransfer(scopedHistory()) + .getIncomingEmbeddablePackage(); + const dashboardStateManager = new DashboardStateManager({ savedDashboard: dash, hideWriteControls: dashboardConfig.getHideWriteControls(), @@ -184,20 +184,30 @@ export class DashboardAppController { // sync initial app filters from state to filterManager // if there is an existing similar global filter, then leave it as global filterManager.setAppFilters(_.cloneDeep(dashboardStateManager.appState.filters)); + queryStringManager.setQuery(migrateLegacyQuery(dashboardStateManager.appState.query)); + // setup syncing of app filters between appState and filterManager const stopSyncingAppFilters = connectToQueryState( queryService, { - set: ({ filters }) => dashboardStateManager.setFilters(filters || []), - get: () => ({ filters: dashboardStateManager.appState.filters }), + set: ({ filters, query }) => { + dashboardStateManager.setFilters(filters || []); + dashboardStateManager.setQuery(query || queryStringManager.getDefaultQuery()); + }, + get: () => ({ + filters: dashboardStateManager.appState.filters, + query: dashboardStateManager.getQuery(), + }), state$: dashboardStateManager.appState$.pipe( map((state) => ({ filters: state.filters, + query: queryStringManager.formatQuery(state.query), })) ), }, { filters: esFilters.FilterStateStore.APP_STATE, + query: true, } ); @@ -253,11 +263,7 @@ export class DashboardAppController { navActions[TopNavIds.VISUALIZE](); }; - const updateIndexPatterns = (container?: DashboardContainer) => { - if (!container || isErrorEmbeddable(container)) { - return; - } - + function getDashboardIndexPatterns(container: DashboardContainer): IndexPattern[] { let panelIndexPatterns: IndexPattern[] = []; Object.values(container.getChildIds()).forEach((id) => { const embeddableInstance = container.getChild(id); @@ -267,19 +273,34 @@ export class DashboardAppController { panelIndexPatterns.push(...embeddableIndexPatterns); }); panelIndexPatterns = uniqBy(panelIndexPatterns, 'id'); + return panelIndexPatterns; + } - if (panelIndexPatterns && panelIndexPatterns.length > 0) { - $scope.$evalAsync(() => { - $scope.indexPatterns = panelIndexPatterns; - }); - } else { - indexPatterns.getDefault().then((defaultIndexPattern) => { - $scope.$evalAsync(() => { - $scope.indexPatterns = [defaultIndexPattern as IndexPattern]; - }); + const updateIndexPatternsOperator = pipe( + filter((container: DashboardContainer) => !!container && !isErrorEmbeddable(container)), + map(getDashboardIndexPatterns), + // using switchMap for previous task cancellation + switchMap((panelIndexPatterns: IndexPattern[]) => { + return new Observable((observer) => { + if (panelIndexPatterns && panelIndexPatterns.length > 0) { + $scope.$evalAsync(() => { + if (observer.closed) return; + $scope.indexPatterns = panelIndexPatterns; + observer.complete(); + }); + } else { + indexPatterns.getDefault().then((defaultIndexPattern) => { + if (observer.closed) return; + $scope.$evalAsync(() => { + if (observer.closed) return; + $scope.indexPatterns = [defaultIndexPattern as IndexPattern]; + observer.complete(); + }); + }); + } }); - } - }; + }) + ); const getEmptyScreenProps = ( shouldShowEditHelp: boolean, @@ -316,7 +337,7 @@ export class DashboardAppController { const isEmptyInReadonlyMode = shouldShowUnauthorizedEmptyState(); return { id: dashboardStateManager.savedDashboard.id || '', - filters: queryFilter.getFilters(), + filters: filterManager.getFilters(), hidePanelTitles: dashboardStateManager.getHidePanelTitles(), query: $scope.model.query, timeRange: { @@ -341,7 +362,7 @@ export class DashboardAppController { // https://github.com/angular/angular.js/wiki/Understanding-Scopes $scope.model = { query: dashboardStateManager.getQuery(), - filters: queryFilter.getFilters(), + filters: filterManager.getFilters(), timeRestore: dashboardStateManager.getTimeRestore(), title: dashboardStateManager.getTitle(), description: dashboardStateManager.getDescription(), @@ -384,11 +405,17 @@ export class DashboardAppController { ) : null; }; - updateIndexPatterns(dashboardContainer); - - outputSubscription = dashboardContainer.getOutput$().subscribe(() => { - updateIndexPatterns(dashboardContainer); - }); + outputSubscription = new Subscription(); + outputSubscription.add( + dashboardContainer + .getOutput$() + .pipe( + mapTo(dashboardContainer), + startWith(dashboardContainer), // to trigger initial index pattern update + updateIndexPatternsOperator + ) + .subscribe() + ); inputSubscription = dashboardContainer.getInput$().subscribe(() => { let dirty = false; @@ -399,12 +426,12 @@ export class DashboardAppController { if ( !esFilters.compareFilters( container.getInput().filters, - queryFilter.getFilters(), + filterManager.getFilters(), esFilters.COMPARE_ALL_OPTIONS ) ) { // Add filters modifies the object passed to it, hence the clone deep. - queryFilter.addFilters(_.cloneDeep(container.getInput().filters)); + filterManager.addFilters(_.cloneDeep(container.getInput().filters)); dashboardStateManager.applyFilters( $scope.model.query, @@ -427,21 +454,24 @@ export class DashboardAppController { refreshDashboardContainer(); }); - const incomingState = embeddable - .getStateTransfer(scopedHistory()) - .getIncomingEmbeddablePackage(); - if (incomingState) { - if ('id' in incomingState) { - container.addOrUpdateEmbeddable(incomingState.type, { - savedObjectId: incomingState.id, - }); - } else if ('input' in incomingState) { - const input = incomingState.input; + if (incomingEmbeddable) { + if ('id' in incomingEmbeddable) { + container.addOrUpdateEmbeddable( + incomingEmbeddable.type, + { + savedObjectId: incomingEmbeddable.id, + } + ); + } else if ('input' in incomingEmbeddable) { + const input = incomingEmbeddable.input; delete input.id; const explicitInput = { savedVis: input, }; - container.addOrUpdateEmbeddable(incomingState.type, explicitInput); + container.addOrUpdateEmbeddable( + incomingEmbeddable.type, + explicitInput + ); } } } @@ -463,13 +493,8 @@ export class DashboardAppController { }); dashboardStateManager.applyFilters( - dashboardStateManager.getQuery() || { - query: '', - language: - localStorage.get('kibana.userQueryLanguage') || - uiSettings.get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE), - }, - queryFilter.getFilters() + dashboardStateManager.getQuery() || queryStringManager.getDefaultQuery(), + filterManager.getFilters() ); timefilter.disableTimeRangeSelector(); @@ -543,21 +568,13 @@ export class DashboardAppController { } }; - $scope.updateQueryAndFetch = function ({ query, dateRange }) { - if (dateRange) { - timefilter.setTime(dateRange); - } - - const oldQuery = $scope.model.query; - if (_.isEqual(oldQuery, query)) { + $scope.handleRefresh = function (_payload, isUpdate) { + if (isUpdate === false) { // The user can still request a reload in the query bar, even if the // query is the same, and in that case, we have to explicitly ask for // a reload, since no state changes will cause it. lastReloadRequestTime = new Date().getTime(); refreshDashboardContainer(); - } else { - $scope.model.query = query; - dashboardStateManager.applyFilters($scope.model.query, $scope.model.filters); } }; @@ -576,7 +593,7 @@ export class DashboardAppController { // Making this method sync broke the updates. // Temporary fix, until we fix the complex state in this file. setTimeout(() => { - queryFilter.setFilters(allFilters); + filterManager.setFilters(allFilters); }, 0); }; @@ -609,11 +626,6 @@ export class DashboardAppController { $scope.indexPatterns = []; - $scope.$watch('model.query', (newQuery: Query) => { - const query = migrateLegacyQuery(newQuery) as Query; - $scope.updateQueryAndFetch({ query }); - }); - $scope.$watch( () => dashboardCapabilities.saveQuery, (newCapability) => { @@ -654,18 +666,11 @@ export class DashboardAppController { showFilterBar, indexPatterns: $scope.indexPatterns, showSaveQuery: $scope.showSaveQuery, - query: $scope.model.query, savedQuery: $scope.savedQuery, onSavedQueryIdChange, savedQueryId: dashboardStateManager.getSavedQueryId(), useDefaultBehaviors: true, - onQuerySubmit: (payload: { dateRange: TimeRange; query?: Query }): void => { - if (!payload.query) { - $scope.updateQueryAndFetch({ query: $scope.model.query, dateRange: payload.dateRange }); - } else { - $scope.updateQueryAndFetch({ query: payload.query, dateRange: payload.dateRange }); - } - }, + onQuerySubmit: $scope.handleRefresh, }; }; const dashboardNavBar = document.getElementById('dashboardChrome'); @@ -680,25 +685,11 @@ export class DashboardAppController { }; $scope.timefilterSubscriptions$ = new Subscription(); - - $scope.timefilterSubscriptions$.add( - subscribeWithScope( - $scope, - timefilter.getRefreshIntervalUpdate$(), - { - next: () => { - updateState(); - refreshDashboardContainer(); - }, - }, - (error: AngularHttpError | Error | string) => addFatalError(fatalErrors, error) - ) - ); - + const timeChanges$ = merge(timefilter.getRefreshIntervalUpdate$(), timefilter.getTimeUpdate$()); $scope.timefilterSubscriptions$.add( subscribeWithScope( $scope, - timefilter.getTimeUpdate$(), + timeChanges$, { next: () => { updateState(); @@ -1071,13 +1062,21 @@ export class DashboardAppController { updateViewMode(dashboardStateManager.getViewMode()); + const filterChanges = merge(filterManager.getUpdates$(), queryStringManager.getUpdates$()).pipe( + debounceTime(100) + ); + // update root source when filters update - const updateSubscription = queryFilter.getUpdates$().subscribe({ + const updateSubscription = filterChanges.subscribe({ next: () => { - $scope.model.filters = queryFilter.getFilters(); + $scope.model.filters = filterManager.getFilters(); + $scope.model.query = queryStringManager.getQuery(); dashboardStateManager.applyFilters($scope.model.query, $scope.model.filters); if (dashboardContainer) { - dashboardContainer.updateInput({ filters: $scope.model.filters }); + dashboardContainer.updateInput({ + filters: $scope.model.filters, + query: $scope.model.query, + }); } }, }); diff --git a/src/plugins/dashboard/public/index.ts b/src/plugins/dashboard/public/index.ts index 17968dd0281e6..dcfde67cd9f13 100644 --- a/src/plugins/dashboard/public/index.ts +++ b/src/plugins/dashboard/public/index.ts @@ -32,7 +32,11 @@ export { export { DashboardConstants, createDashboardEditUrl } from './dashboard_constants'; export { DashboardStart, DashboardUrlGenerator } from './plugin'; -export { DASHBOARD_APP_URL_GENERATOR, createDashboardUrlGenerator } from './url_generator'; +export { + DASHBOARD_APP_URL_GENERATOR, + createDashboardUrlGenerator, + DashboardUrlGeneratorState, +} from './url_generator'; export { addEmbeddableToDashboardUrl } from './url_utils/url_helper'; export { SavedObjectDashboard } from './saved_dashboards'; export { SavedDashboardPanel } from './types'; diff --git a/src/plugins/dashboard/public/plugin.tsx b/src/plugins/dashboard/public/plugin.tsx index 041a02a251e8a..f0b57fec169fd 100644 --- a/src/plugins/dashboard/public/plugin.tsx +++ b/src/plugins/dashboard/public/plugin.tsx @@ -65,6 +65,7 @@ import { ACTION_REPLACE_PANEL, ClonePanelAction, ClonePanelActionContext, + createDashboardContainerByValueRenderer, DASHBOARD_CONTAINER_TYPE, DashboardContainerFactory, DashboardContainerFactoryDefinition, @@ -77,17 +78,17 @@ import { import { createDashboardUrlGenerator, DASHBOARD_APP_URL_GENERATOR, - DashboardAppLinkGeneratorState, + DashboardUrlGeneratorState, } from './url_generator'; import { createSavedDashboardLoader } from './saved_dashboards'; import { DashboardConstants } from './dashboard_constants'; import { addEmbeddableToDashboardUrl } from './url_utils/url_helper'; import { PlaceholderEmbeddableFactory } from './application/embeddable/placeholder'; -import { createDashboardContainerByValueRenderer } from './application'; +import { UrlGeneratorState } from '../../share/public'; declare module '../../share/public' { export interface UrlGeneratorStateMapping { - [DASHBOARD_APP_URL_GENERATOR]: DashboardAppLinkGeneratorState; + [DASHBOARD_APP_URL_GENERATOR]: UrlGeneratorState; } } diff --git a/src/plugins/dashboard/public/url_generator.ts b/src/plugins/dashboard/public/url_generator.ts index 188de7fd857be..68a50396e00d6 100644 --- a/src/plugins/dashboard/public/url_generator.ts +++ b/src/plugins/dashboard/public/url_generator.ts @@ -26,7 +26,7 @@ import { RefreshInterval, } from '../../data/public'; import { setStateToKbnUrl } from '../../kibana_utils/public'; -import { UrlGeneratorsDefinition, UrlGeneratorState } from '../../share/public'; +import { UrlGeneratorsDefinition } from '../../share/public'; import { SavedObjectLoader } from '../../saved_objects/public'; import { ViewMode } from '../../embeddable/public'; @@ -35,7 +35,7 @@ export const GLOBAL_STATE_STORAGE_KEY = '_g'; export const DASHBOARD_APP_URL_GENERATOR = 'DASHBOARD_APP_URL_GENERATOR'; -export type DashboardAppLinkGeneratorState = UrlGeneratorState<{ +export interface DashboardUrlGeneratorState { /** * If given, the dashboard saved object with this id will be loaded. If not given, * a new, unsaved dashboard will be loaded up. @@ -79,7 +79,7 @@ export type DashboardAppLinkGeneratorState = UrlGeneratorState<{ * View mode of the dashboard. */ viewMode?: ViewMode; -}>; +} export const createDashboardUrlGenerator = ( getStartServices: () => Promise<{ diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index 846471420327f..e95150e8f6f73 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -58,6 +58,7 @@ import { changeTimeFilter, mapAndFlattenFilters, extractTimeFilter, + extractTimeRange, convertRangeFilterToTimeRangeString, } from './query'; @@ -99,6 +100,7 @@ export const esFilters = { convertRangeFilterToTimeRangeString, mapAndFlattenFilters, extractTimeFilter, + extractTimeRange, }; export { diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index a8868c07061c3..97e7a96c71e69 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -7,44 +7,15 @@ import { $Values } from '@kbn/utility-types'; import _ from 'lodash'; import { Action } from 'history'; +import { ApiResponse } from '@elastic/elasticsearch/lib/Transport'; import { ApplicationStart } from 'kibana/public'; import { Assign } from '@kbn/utility-types'; import { BehaviorSubject } from 'rxjs'; import Boom from 'boom'; -import { BulkIndexDocumentsParams } from 'elasticsearch'; -import { CatAliasesParams } from 'elasticsearch'; -import { CatAllocationParams } from 'elasticsearch'; -import { CatCommonParams } from 'elasticsearch'; -import { CatFielddataParams } from 'elasticsearch'; -import { CatHealthParams } from 'elasticsearch'; -import { CatHelpParams } from 'elasticsearch'; -import { CatIndicesParams } from 'elasticsearch'; -import { CatRecoveryParams } from 'elasticsearch'; -import { CatSegmentsParams } from 'elasticsearch'; -import { CatShardsParams } from 'elasticsearch'; -import { CatSnapshotsParams } from 'elasticsearch'; -import { CatTasksParams } from 'elasticsearch'; -import { CatThreadPoolParams } from 'elasticsearch'; -import { ClearScrollParams } from 'elasticsearch'; -import { Client } from 'elasticsearch'; -import { ClusterAllocationExplainParams } from 'elasticsearch'; -import { ClusterGetSettingsParams } from 'elasticsearch'; -import { ClusterHealthParams } from 'elasticsearch'; -import { ClusterPendingTasksParams } from 'elasticsearch'; -import { ClusterPutSettingsParams } from 'elasticsearch'; -import { ClusterRerouteParams } from 'elasticsearch'; -import { ClusterStateParams } from 'elasticsearch'; -import { ClusterStatsParams } from 'elasticsearch'; import { Component } from 'react'; import { CoreSetup } from 'src/core/public'; import { CoreStart } from 'kibana/public'; import { CoreStart as CoreStart_2 } from 'src/core/public'; -import { CountParams } from 'elasticsearch'; -import { CreateDocumentParams } from 'elasticsearch'; -import { DeleteDocumentByQueryParams } from 'elasticsearch'; -import { DeleteDocumentParams } from 'elasticsearch'; -import { DeleteScriptParams } from 'elasticsearch'; -import { DeleteTemplateParams } from 'elasticsearch'; import { Ensure } from '@kbn/utility-types'; import { ErrorToastOptions } from 'src/core/public/notifications'; import { EuiBreadcrumb } from '@elastic/eui'; @@ -53,98 +24,33 @@ import { EuiComboBoxProps } from '@elastic/eui'; import { EuiConfirmModalProps } from '@elastic/eui'; import { EuiGlobalToastListToast } from '@elastic/eui'; import { ExclusiveUnion } from '@elastic/eui'; -import { ExistsParams } from 'elasticsearch'; -import { ExplainParams } from 'elasticsearch'; import { ExpressionAstFunction } from 'src/plugins/expressions/common'; import { ExpressionsSetup } from 'src/plugins/expressions/public'; -import { FieldStatsParams } from 'elasticsearch'; -import { GenericParams } from 'elasticsearch'; -import { GetParams } from 'elasticsearch'; -import { GetResponse } from 'elasticsearch'; -import { GetScriptParams } from 'elasticsearch'; -import { GetSourceParams } from 'elasticsearch'; -import { GetTemplateParams } from 'elasticsearch'; import { History } from 'history'; import { Href } from 'history'; import { IconType } from '@elastic/eui'; -import { IndexDocumentParams } from 'elasticsearch'; -import { IndicesAnalyzeParams } from 'elasticsearch'; -import { IndicesClearCacheParams } from 'elasticsearch'; -import { IndicesCloseParams } from 'elasticsearch'; -import { IndicesCreateParams } from 'elasticsearch'; -import { IndicesDeleteAliasParams } from 'elasticsearch'; -import { IndicesDeleteParams } from 'elasticsearch'; -import { IndicesDeleteTemplateParams } from 'elasticsearch'; -import { IndicesExistsAliasParams } from 'elasticsearch'; -import { IndicesExistsParams } from 'elasticsearch'; -import { IndicesExistsTemplateParams } from 'elasticsearch'; -import { IndicesExistsTypeParams } from 'elasticsearch'; -import { IndicesFlushParams } from 'elasticsearch'; -import { IndicesFlushSyncedParams } from 'elasticsearch'; -import { IndicesForcemergeParams } from 'elasticsearch'; -import { IndicesGetAliasParams } from 'elasticsearch'; -import { IndicesGetFieldMappingParams } from 'elasticsearch'; -import { IndicesGetMappingParams } from 'elasticsearch'; -import { IndicesGetParams } from 'elasticsearch'; -import { IndicesGetSettingsParams } from 'elasticsearch'; -import { IndicesGetTemplateParams } from 'elasticsearch'; -import { IndicesGetUpgradeParams } from 'elasticsearch'; -import { IndicesOpenParams } from 'elasticsearch'; -import { IndicesPutAliasParams } from 'elasticsearch'; -import { IndicesPutMappingParams } from 'elasticsearch'; -import { IndicesPutSettingsParams } from 'elasticsearch'; -import { IndicesPutTemplateParams } from 'elasticsearch'; -import { IndicesRecoveryParams } from 'elasticsearch'; -import { IndicesRefreshParams } from 'elasticsearch'; -import { IndicesRolloverParams } from 'elasticsearch'; -import { IndicesSegmentsParams } from 'elasticsearch'; -import { IndicesShardStoresParams } from 'elasticsearch'; -import { IndicesShrinkParams } from 'elasticsearch'; -import { IndicesStatsParams } from 'elasticsearch'; -import { IndicesUpdateAliasesParams } from 'elasticsearch'; -import { IndicesUpgradeParams } from 'elasticsearch'; -import { IndicesValidateQueryParams } from 'elasticsearch'; -import { InfoParams } from 'elasticsearch'; -import { IngestDeletePipelineParams } from 'elasticsearch'; -import { IngestGetPipelineParams } from 'elasticsearch'; -import { IngestPutPipelineParams } from 'elasticsearch'; -import { IngestSimulateParams } from 'elasticsearch'; import { InjectedIntl } from '@kbn/i18n/react'; import { IStorageWrapper } from 'src/plugins/kibana_utils/public'; import { IUiSettingsClient } from 'src/core/public'; import { IUiSettingsClient as IUiSettingsClient_3 } from 'kibana/public'; +import { KibanaClient } from '@elastic/elasticsearch/api/kibana'; import { KibanaConfigType } from 'src/core/server/kibana_config'; import { Location } from 'history'; import { LocationDescriptorObject } from 'history'; import { MaybePromise } from '@kbn/utility-types'; import { METRIC_TYPE } from '@kbn/analytics'; -import { MGetParams } from 'elasticsearch'; -import { MGetResponse } from 'elasticsearch'; import { Moment } from 'moment'; import moment from 'moment'; -import { MSearchParams } from 'elasticsearch'; -import { MSearchResponse } from 'elasticsearch'; -import { MSearchTemplateParams } from 'elasticsearch'; -import { MTermVectorsParams } from 'elasticsearch'; import { NameList } from 'elasticsearch'; -import { NodesHotThreadsParams } from 'elasticsearch'; -import { NodesInfoParams } from 'elasticsearch'; -import { NodesStatsParams } from 'elasticsearch'; import { Observable } from 'rxjs'; import { Path } from 'history'; -import { PingParams } from 'elasticsearch'; import { Plugin as Plugin_2 } from 'src/core/public'; import { PluginInitializerContext as PluginInitializerContext_2 } from 'src/core/public'; import { PopoverAnchorPosition } from '@elastic/eui'; import { PublicUiSettingsParams } from 'src/core/server/types'; -import { PutScriptParams } from 'elasticsearch'; -import { PutTemplateParams } from 'elasticsearch'; import React from 'react'; import * as React_2 from 'react'; import { RecursiveReadonly } from '@kbn/utility-types'; -import { ReindexParams } from 'elasticsearch'; -import { ReindexRethrottleParams } from 'elasticsearch'; -import { RenderSearchTemplateParams } from 'elasticsearch'; import { Reporter } from '@kbn/analytics'; import { RequestAdapter } from 'src/plugins/inspector/common'; import { RequestStatistics } from 'src/plugins/inspector/common'; @@ -153,38 +59,22 @@ import * as Rx from 'rxjs'; import { SavedObject } from 'src/core/server'; import { SavedObject as SavedObject_3 } from 'src/core/public'; import { SavedObjectsClientContract } from 'src/core/public'; -import { ScrollParams } from 'elasticsearch'; import { SearchParams } from 'elasticsearch'; import { SearchResponse as SearchResponse_2 } from 'elasticsearch'; -import { SearchShardsParams } from 'elasticsearch'; -import { SearchTemplateParams } from 'elasticsearch'; import { SerializedFieldFormat as SerializedFieldFormat_2 } from 'src/plugins/expressions/common'; -import { SnapshotCreateParams } from 'elasticsearch'; -import { SnapshotCreateRepositoryParams } from 'elasticsearch'; -import { SnapshotDeleteParams } from 'elasticsearch'; -import { SnapshotDeleteRepositoryParams } from 'elasticsearch'; -import { SnapshotGetParams } from 'elasticsearch'; -import { SnapshotGetRepositoryParams } from 'elasticsearch'; -import { SnapshotRestoreParams } from 'elasticsearch'; -import { SnapshotStatusParams } from 'elasticsearch'; -import { SnapshotVerifyRepositoryParams } from 'elasticsearch'; import { Subscription } from 'rxjs'; -import { SuggestParams } from 'elasticsearch'; -import { TasksCancelParams } from 'elasticsearch'; -import { TasksGetParams } from 'elasticsearch'; -import { TasksListParams } from 'elasticsearch'; -import { TermvectorsParams } from 'elasticsearch'; import { Toast } from 'kibana/public'; import { ToastInputFields } from 'src/core/public/notifications'; import { ToastsStart } from 'kibana/public'; +import { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport'; +import { TransportRequestParams } from '@elastic/elasticsearch/lib/Transport'; +import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; import { TypeOf } from '@kbn/config-schema'; import { UiActionsSetup } from 'src/plugins/ui_actions/public'; import { UiActionsStart } from 'src/plugins/ui_actions/public'; import { Unit } from '@elastic/datemath'; import { UnregisterCallback } from 'history'; import { UnwrapPromiseOrReturn } from '@kbn/utility-types'; -import { UpdateDocumentByQueryParams } from 'elasticsearch'; -import { UpdateDocumentParams } from 'elasticsearch'; import { UserProvidedValues } from 'src/core/server/types'; // Warning: (ae-forgotten-export) The symbol "AggConfigSerialized" needs to be exported by the entry point index.d.ts @@ -309,10 +199,11 @@ export const castEsToKbnFieldTypeName: (esType: ES_FIELD_TYPES | string) => KBN_ // Warning: (ae-missing-release-tag) "connectToQueryState" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public -export const connectToQueryState: ({ timefilter: { timefilter }, filterManager, state$, }: Pick, stateContainer: BaseStateContainer, syncConfig: { +export const connectToQueryState: ({ timefilter: { timefilter }, filterManager, queryString, state$, }: Pick, stateContainer: BaseStateContainer, syncConfig: { time?: boolean; refreshInterval?: boolean; filters?: FilterStateStore | boolean; + query?: boolean; }) => () => void; // Warning: (ae-missing-release-tag) "createSavedQueryService" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -499,6 +390,7 @@ export const esFilters: { convertRangeFilterToTimeRangeString: typeof convertRangeFilterToTimeRangeString; mapAndFlattenFilters: (filters: import("../common").Filter[]) => import("../common").Filter[]; extractTimeFilter: typeof extractTimeFilter; + extractTimeRange: typeof extractTimeRange; }; // Warning: (ae-missing-release-tag) "esKuery" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -1497,6 +1389,8 @@ export interface QueryState { // (undocumented) filters?: Filter[]; // (undocumented) + query?: Query; + // (undocumented) refreshInterval?: RefreshInterval; // (undocumented) time?: TimeRange; @@ -1871,7 +1765,7 @@ export type StatefulSearchBarProps = SearchBarOwnProps & { // Warning: (ae-missing-release-tag) "syncQueryStateWithUrl" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public -export const syncQueryStateWithUrl: (query: Pick, kbnUrlStateStorage: IKbnUrlStateStorage) => { +export const syncQueryStateWithUrl: (query: Pick, kbnUrlStateStorage: IKbnUrlStateStorage) => { stop: () => void; hasInheritedQueryFromUrl: boolean; }; @@ -2019,7 +1913,7 @@ export const UI_SETTINGS: { // src/plugins/data/public/index.ts:392:1 - (ae-forgotten-export) The symbol "parseInterval" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:393:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:396:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/query/state_sync/connect_to_query_state.ts:41:60 - (ae-forgotten-export) The symbol "FilterStateStore" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/query/state_sync/connect_to_query_state.ts:45:5 - (ae-forgotten-export) The symbol "FilterStateStore" needs to be exported by the entry point index.d.ts // src/plugins/data/public/types.ts:54:5 - (ae-forgotten-export) The symbol "createFiltersFromValueClickAction" needs to be exported by the entry point index.d.ts // src/plugins/data/public/types.ts:55:5 - (ae-forgotten-export) The symbol "createFiltersFromRangeSelectAction" needs to be exported by the entry point index.d.ts // src/plugins/data/public/types.ts:63:5 - (ae-forgotten-export) The symbol "IndexPatternSelectProps" needs to be exported by the entry point index.d.ts diff --git a/src/plugins/data/public/query/mocks.ts b/src/plugins/data/public/query/mocks.ts index 41896107bb868..8c15d9d6d0152 100644 --- a/src/plugins/data/public/query/mocks.ts +++ b/src/plugins/data/public/query/mocks.ts @@ -21,6 +21,7 @@ import { Observable } from 'rxjs'; import { QueryService, QuerySetup, QueryStart } from '.'; import { timefilterServiceMock } from './timefilter/timefilter_service.mock'; import { createFilterManagerMock } from './filter_manager/filter_manager.mock'; +import { queryStringManagerMock } from './query_string/query_string_manager.mock'; type QueryServiceClientContract = PublicMethodsOf; @@ -28,6 +29,7 @@ const createSetupContractMock = () => { const setupContract: jest.Mocked = { filterManager: createFilterManagerMock(), timefilter: timefilterServiceMock.createSetupContract(), + queryString: queryStringManagerMock.createSetupContract(), state$: new Observable(), }; @@ -38,6 +40,7 @@ const createStartContractMock = () => { const startContract: jest.Mocked = { addToQueryLog: jest.fn(), filterManager: createFilterManagerMock(), + queryString: queryStringManagerMock.createStartContract(), savedQueries: jest.fn() as any, state$: new Observable(), timefilter: timefilterServiceMock.createStartContract(), diff --git a/src/plugins/data/public/query/query_service.ts b/src/plugins/data/public/query/query_service.ts index eb1f985fa51db..da514c0e24ea4 100644 --- a/src/plugins/data/public/query/query_service.ts +++ b/src/plugins/data/public/query/query_service.ts @@ -25,6 +25,7 @@ import { createAddToQueryLog } from './lib'; import { TimefilterService, TimefilterSetup } from './timefilter'; import { createSavedQueryService } from './saved_query/saved_query_service'; import { createQueryStateObservable } from './state_sync/create_global_query_observable'; +import { QueryStringManager, QueryStringContract } from './query_string'; /** * Query Service @@ -45,6 +46,7 @@ interface QueryServiceStartDependencies { export class QueryService { filterManager!: FilterManager; timefilter!: TimefilterSetup; + queryStringManager!: QueryStringContract; state$!: ReturnType; @@ -57,14 +59,18 @@ export class QueryService { storage, }); + this.queryStringManager = new QueryStringManager(storage, uiSettings); + this.state$ = createQueryStateObservable({ filterManager: this.filterManager, timefilter: this.timefilter, + queryString: this.queryStringManager, }).pipe(share()); return { filterManager: this.filterManager, timefilter: this.timefilter, + queryString: this.queryStringManager, state$: this.state$, }; } @@ -76,6 +82,7 @@ export class QueryService { uiSettings, }), filterManager: this.filterManager, + queryString: this.queryStringManager, savedQueries: createSavedQueryService(savedObjectsClient), state$: this.state$, timefilter: this.timefilter, diff --git a/src/plugins/data/public/query/query_string/index.ts b/src/plugins/data/public/query/query_string/index.ts new file mode 100644 index 0000000000000..6ea87fde69ac8 --- /dev/null +++ b/src/plugins/data/public/query/query_string/index.ts @@ -0,0 +1,20 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export { QueryStringContract, QueryStringManager } from './query_string_manager'; diff --git a/src/plugins/data/public/query/query_string/query_string_manager.mock.ts b/src/plugins/data/public/query/query_string/query_string_manager.mock.ts new file mode 100644 index 0000000000000..427662cb01ebb --- /dev/null +++ b/src/plugins/data/public/query/query_string/query_string_manager.mock.ts @@ -0,0 +1,37 @@ +/* + * 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 { QueryStringContract } from '.'; + +const createSetupContractMock = () => { + const queryStringManagerMock: jest.Mocked = { + getQuery: jest.fn(), + setQuery: jest.fn(), + getUpdates$: jest.fn(), + getDefaultQuery: jest.fn(), + formatQuery: jest.fn(), + clearQuery: jest.fn(), + }; + return queryStringManagerMock; +}; + +export const queryStringManagerMock = { + createSetupContract: createSetupContractMock, + createStartContract: createSetupContractMock, +}; diff --git a/src/plugins/data/public/query/query_string/query_string_manager.ts b/src/plugins/data/public/query/query_string/query_string_manager.ts new file mode 100644 index 0000000000000..bd02830f4aed8 --- /dev/null +++ b/src/plugins/data/public/query/query_string/query_string_manager.ts @@ -0,0 +1,90 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import _ from 'lodash'; +import { BehaviorSubject } from 'rxjs'; +import { CoreStart } from 'kibana/public'; +import { IStorageWrapper } from 'src/plugins/kibana_utils/public'; +import { Query, UI_SETTINGS } from '../../../common'; + +export class QueryStringManager { + private query$: BehaviorSubject; + + constructor( + private readonly storage: IStorageWrapper, + private readonly uiSettings: CoreStart['uiSettings'] + ) { + this.query$ = new BehaviorSubject(this.getDefaultQuery()); + } + + private getDefaultLanguage() { + return ( + this.storage.get('kibana.userQueryLanguage') || + this.uiSettings.get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE) + ); + } + + public getDefaultQuery() { + return { + query: '', + language: this.getDefaultLanguage(), + }; + } + + public formatQuery(query: Query | string | undefined): Query { + if (!query) { + return this.getDefaultQuery(); + } else if (typeof query === 'string') { + return { + query, + language: this.getDefaultLanguage(), + }; + } else { + return query; + } + } + + public getUpdates$ = () => { + return this.query$.asObservable(); + }; + + public getQuery = (): Query => { + return this.query$.getValue(); + }; + + /** + * Updates the query. + * @param {Query} query + */ + public setQuery = (query: Query) => { + const curQuery = this.query$.getValue(); + if (query?.language !== curQuery.language || query?.query !== curQuery.query) { + this.query$.next(query); + } + }; + + /** + * Resets the query to the default one. + */ + public clearQuery = () => { + this.setQuery(this.getDefaultQuery()); + }; +} + +export type QueryStringContract = PublicMethodsOf; diff --git a/src/plugins/data/public/query/state_sync/connect_to_query_state.test.ts b/src/plugins/data/public/query/state_sync/connect_to_query_state.test.ts index cf98c87b18267..307d1fe1b2b0b 100644 --- a/src/plugins/data/public/query/state_sync/connect_to_query_state.test.ts +++ b/src/plugins/data/public/query/state_sync/connect_to_query_state.test.ts @@ -48,6 +48,8 @@ setupMock.uiSettings.get.mockImplementation((key: string) => { switch (key) { case UI_SETTINGS.FILTERS_PINNED_BY_DEFAULT: return true; + case UI_SETTINGS.SEARCH_QUERY_LANGUAGE: + return 'kuery'; case 'timepicker:timeDefaults': return { from: 'now-15m', to: 'now' }; case UI_SETTINGS.TIMEPICKER_REFRESH_INTERVAL_DEFAULTS: diff --git a/src/plugins/data/public/query/state_sync/connect_to_query_state.ts b/src/plugins/data/public/query/state_sync/connect_to_query_state.ts index 2e62dac87f6ef..55edd04b5dab0 100644 --- a/src/plugins/data/public/query/state_sync/connect_to_query_state.ts +++ b/src/plugins/data/public/query/state_sync/connect_to_query_state.ts @@ -35,15 +35,24 @@ export const connectToQueryState = ( { timefilter: { timefilter }, filterManager, + queryString, state$, - }: Pick, + }: Pick, stateContainer: BaseStateContainer, - syncConfig: { time?: boolean; refreshInterval?: boolean; filters?: FilterStateStore | boolean } + syncConfig: { + time?: boolean; + refreshInterval?: boolean; + filters?: FilterStateStore | boolean; + query?: boolean; + } ) => { const syncKeys: Array = []; if (syncConfig.time) { syncKeys.push('time'); } + if (syncConfig.query) { + syncKeys.push('query'); + } if (syncConfig.refreshInterval) { syncKeys.push('refreshInterval'); } @@ -133,6 +142,9 @@ export const connectToQueryState = ( if (syncConfig.time && changes.time) { newState.time = timefilter.getTime(); } + if (syncConfig.query && changes.query) { + newState.query = queryString.getQuery(); + } if (syncConfig.refreshInterval && changes.refreshInterval) { newState.refreshInterval = timefilter.getRefreshInterval(); } @@ -173,6 +185,13 @@ export const connectToQueryState = ( } } + if (syncConfig.query) { + const curQuery = state.query || queryString.getQuery(); + if (!_.isEqual(curQuery, queryString.getQuery())) { + queryString.setQuery(_.cloneDeep(curQuery)); + } + } + if (syncConfig.filters) { const filters = state.filters || []; if (syncConfig.filters === true) { diff --git a/src/plugins/data/public/query/state_sync/create_global_query_observable.ts b/src/plugins/data/public/query/state_sync/create_global_query_observable.ts index 87032925294c6..5e2c575c74af7 100644 --- a/src/plugins/data/public/query/state_sync/create_global_query_observable.ts +++ b/src/plugins/data/public/query/state_sync/create_global_query_observable.ts @@ -24,23 +24,31 @@ import { FilterManager } from '../filter_manager'; import { QueryState, QueryStateChange } from './index'; import { createStateContainer } from '../../../../kibana_utils/public'; import { isFilterPinned, compareFilters, COMPARE_ALL_OPTIONS } from '../../../common'; +import { QueryStringContract } from '../query_string'; export function createQueryStateObservable({ timefilter: { timefilter }, filterManager, + queryString, }: { timefilter: TimefilterSetup; filterManager: FilterManager; + queryString: QueryStringContract; }): Observable<{ changes: QueryStateChange; state: QueryState }> { return new Observable((subscriber) => { const state = createStateContainer({ time: timefilter.getTime(), refreshInterval: timefilter.getRefreshInterval(), filters: filterManager.getFilters(), + query: queryString.getQuery(), }); let currentChange: QueryStateChange = {}; const subs: Subscription[] = [ + queryString.getUpdates$().subscribe(() => { + currentChange.query = true; + state.set({ ...state.get(), query: queryString.getQuery() }); + }), timefilter.getTimeUpdate$().subscribe(() => { currentChange.time = true; state.set({ ...state.get(), time: timefilter.getTime() }); diff --git a/src/plugins/data/public/query/state_sync/sync_state_with_url.test.ts b/src/plugins/data/public/query/state_sync/sync_state_with_url.test.ts index 122eb2ff6a343..0b4a3f663eb6b 100644 --- a/src/plugins/data/public/query/state_sync/sync_state_with_url.test.ts +++ b/src/plugins/data/public/query/state_sync/sync_state_with_url.test.ts @@ -43,6 +43,8 @@ setupMock.uiSettings.get.mockImplementation((key: string) => { return true; case 'timepicker:timeDefaults': return { from: 'now-15m', to: 'now' }; + case 'search:queryLanguage': + return 'kuery'; case UI_SETTINGS.TIMEPICKER_REFRESH_INTERVAL_DEFAULTS: return { pause: false, value: 0 }; default: diff --git a/src/plugins/data/public/query/state_sync/sync_state_with_url.ts b/src/plugins/data/public/query/state_sync/sync_state_with_url.ts index 4d3da7b9313a3..46be800fbb558 100644 --- a/src/plugins/data/public/query/state_sync/sync_state_with_url.ts +++ b/src/plugins/data/public/query/state_sync/sync_state_with_url.ts @@ -35,7 +35,7 @@ const GLOBAL_STATE_STORAGE_KEY = '_g'; * @param kbnUrlStateStorage to use for syncing */ export const syncQueryStateWithUrl = ( - query: Pick, + query: Pick, kbnUrlStateStorage: IKbnUrlStateStorage ) => { const { diff --git a/src/plugins/data/public/query/state_sync/types.ts b/src/plugins/data/public/query/state_sync/types.ts index 747d4d45fe29b..2354db8cad11a 100644 --- a/src/plugins/data/public/query/state_sync/types.ts +++ b/src/plugins/data/public/query/state_sync/types.ts @@ -17,7 +17,7 @@ * under the License. */ -import { Filter, RefreshInterval, TimeRange } from '../../../common'; +import { Filter, RefreshInterval, TimeRange, Query } from '../../../common'; /** * All query state service state @@ -26,6 +26,7 @@ export interface QueryState { time?: TimeRange; refreshInterval?: RefreshInterval; filters?: Filter[]; + query?: Query; } type QueryStateChangePartial = { diff --git a/src/plugins/data/public/query/timefilter/index.ts b/src/plugins/data/public/query/timefilter/index.ts index 19386c10ab59f..dc9a4ef8c21a6 100644 --- a/src/plugins/data/public/query/timefilter/index.ts +++ b/src/plugins/data/public/query/timefilter/index.ts @@ -23,5 +23,5 @@ export * from './types'; export { Timefilter, TimefilterContract } from './timefilter'; export { TimeHistory, TimeHistoryContract } from './time_history'; export { changeTimeFilter, convertRangeFilterToTimeRangeString } from './lib/change_time_filter'; -export { extractTimeFilter } from './lib/extract_time_filter'; +export { extractTimeFilter, extractTimeRange } from './lib/extract_time_filter'; export { validateTimeRange } from './lib/validate_timerange'; diff --git a/src/plugins/data/public/query/timefilter/lib/extract_time_filter.ts b/src/plugins/data/public/query/timefilter/lib/extract_time_filter.ts index 23dd1547baf10..2f93196e3218b 100644 --- a/src/plugins/data/public/query/timefilter/lib/extract_time_filter.ts +++ b/src/plugins/data/public/query/timefilter/lib/extract_time_filter.ts @@ -18,7 +18,8 @@ */ import { keys, partition } from 'lodash'; -import { Filter, isRangeFilter, RangeFilter } from '../../../../common'; +import { Filter, isRangeFilter, RangeFilter, TimeRange } from '../../../../common'; +import { convertRangeFilterToTimeRangeString } from './change_time_filter'; export function extractTimeFilter(timeFieldName: string, filters: Filter[]) { const [timeRangeFilter, restOfFilters] = partition(filters, (obj: Filter) => { @@ -36,3 +37,15 @@ export function extractTimeFilter(timeFieldName: string, filters: Filter[]) { timeRangeFilter: timeRangeFilter[0] as RangeFilter | undefined, }; } + +export function extractTimeRange( + filters: Filter[], + timeFieldName?: string +): { restOfFilters: Filter[]; timeRange?: TimeRange } { + if (!timeFieldName) return { restOfFilters: filters, timeRange: undefined }; + const { timeRangeFilter, restOfFilters } = extractTimeFilter(timeFieldName, filters); + return { + restOfFilters, + timeRange: timeRangeFilter ? convertRangeFilterToTimeRangeString(timeRangeFilter) : undefined, + }; +} diff --git a/src/plugins/data/public/ui/search_bar/create_search_bar.tsx b/src/plugins/data/public/ui/search_bar/create_search_bar.tsx index f8b7e4f480911..9f0ba2378592a 100644 --- a/src/plugins/data/public/ui/search_bar/create_search_bar.tsx +++ b/src/plugins/data/public/ui/search_bar/create_search_bar.tsx @@ -18,7 +18,7 @@ */ import _ from 'lodash'; -import React, { useState, useEffect, useRef } from 'react'; +import React, { useEffect, useRef } from 'react'; import { CoreStart } from 'src/core/public'; import { IStorageWrapper } from 'src/plugins/kibana_utils/public'; import { KibanaContextProvider } from '../../../../kibana_react/public'; @@ -28,7 +28,8 @@ import { useFilterManager } from './lib/use_filter_manager'; import { useTimefilter } from './lib/use_timefilter'; import { useSavedQuery } from './lib/use_saved_query'; import { DataPublicPluginStart } from '../../types'; -import { Filter, Query, TimeRange, UI_SETTINGS } from '../../../common'; +import { Filter, Query, TimeRange } from '../../../common'; +import { useQueryStringManager } from './lib/use_query_string_manager'; interface StatefulSearchBarDeps { core: CoreStart; @@ -65,8 +66,7 @@ const defaultOnRefreshChange = (queryService: QueryStart) => { const defaultOnQuerySubmit = ( props: StatefulSearchBarProps, queryService: QueryStart, - currentQuery: Query, - setQueryStringState: Function + currentQuery: Query ) => { if (!props.useDefaultBehaviors) return props.onQuerySubmit; @@ -78,7 +78,11 @@ const defaultOnQuerySubmit = ( !_.isEqual(payload.query, currentQuery); if (isUpdate) { timefilter.setTime(payload.dateRange); - setQueryStringState(payload.query); + if (payload.query) { + queryService.queryString.setQuery(payload.query); + } else { + queryService.queryString.clearQuery(); + } } else { // Refresh button triggered for an update if (props.onQuerySubmit) @@ -121,30 +125,7 @@ export function createSearchBar({ core, storage, data }: StatefulSearchBarDeps) return (props: StatefulSearchBarProps) => { const { useDefaultBehaviors } = props; // Handle queries - const queryRef = useRef(props.query); const onQuerySubmitRef = useRef(props.onQuerySubmit); - const defaultQuery = { - query: '', - language: - storage.get('kibana.userQueryLanguage') || - core.uiSettings.get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE), - }; - const [query, setQuery] = useState(props.query || defaultQuery); - - useEffect(() => { - if (props.query !== queryRef.current) { - queryRef.current = props.query; - setQuery(props.query || defaultQuery); - } - /* eslint-disable-next-line react-hooks/exhaustive-deps */ - }, [defaultQuery, props.query]); - - useEffect(() => { - if (props.onQuerySubmit !== onQuerySubmitRef.current) { - onQuerySubmitRef.current = props.onQuerySubmit; - } - /* eslint-disable-next-line react-hooks/exhaustive-deps */ - }, [props.onQuerySubmit]); // handle service state updates. // i.e. filters being added from a visualization directly to filterManager. @@ -152,6 +133,10 @@ export function createSearchBar({ core, storage, data }: StatefulSearchBarDeps) filters: props.filters, filterManager: data.query.filterManager, }); + const { query } = useQueryStringManager({ + query: props.query, + queryStringManager: data.query.queryString, + }); const { timeRange, refreshInterval } = useTimefilter({ dateRangeFrom: props.dateRangeFrom, dateRangeTo: props.dateRangeTo, @@ -163,10 +148,8 @@ export function createSearchBar({ core, storage, data }: StatefulSearchBarDeps) // Fetch and update UI from saved query const { savedQuery, setSavedQuery, clearSavedQuery } = useSavedQuery({ queryService: data.query, - setQuery, savedQueryId: props.savedQueryId, notifications: core.notifications, - defaultLanguage: defaultQuery.language, }); // Fire onQuerySubmit on query or timerange change @@ -210,7 +193,7 @@ export function createSearchBar({ core, storage, data }: StatefulSearchBarDeps) onFiltersUpdated={defaultFiltersUpdated(data.query)} onRefreshChange={defaultOnRefreshChange(data.query)} savedQuery={savedQuery} - onQuerySubmit={defaultOnQuerySubmit(props, data.query, query, setQuery)} + onQuerySubmit={defaultOnQuerySubmit(props, data.query, query)} onClearSavedQuery={defaultOnClearSavedQuery(props, clearSavedQuery)} onSavedQueryUpdated={defaultOnSavedQueryUpdated(props, setSavedQuery)} onSaved={defaultOnSavedQueryUpdated(props, setSavedQuery)} diff --git a/src/plugins/data/public/ui/search_bar/lib/clear_saved_query.test.ts b/src/plugins/data/public/ui/search_bar/lib/clear_saved_query.test.ts index ccfe5464b9598..10520fc3714d5 100644 --- a/src/plugins/data/public/ui/search_bar/lib/clear_saved_query.test.ts +++ b/src/plugins/data/public/ui/search_bar/lib/clear_saved_query.test.ts @@ -21,10 +21,8 @@ import { clearStateFromSavedQuery } from './clear_saved_query'; import { dataPluginMock } from '../../../mocks'; import { DataPublicPluginStart } from '../../../types'; -import { Query } from '../../..'; describe('clearStateFromSavedQuery', () => { - const DEFAULT_LANGUAGE = 'banana'; let dataMock: jest.Mocked; beforeEach(() => { @@ -32,19 +30,9 @@ describe('clearStateFromSavedQuery', () => { }); it('should clear filters and query', async () => { - const setQueryState = jest.fn(); dataMock.query.filterManager.removeAll = jest.fn(); - clearStateFromSavedQuery(dataMock.query, setQueryState, DEFAULT_LANGUAGE); - expect(setQueryState).toHaveBeenCalled(); - expect(dataMock.query.filterManager.removeAll).toHaveBeenCalled(); - }); - - it('should use search:queryLanguage', async () => { - const setQueryState = jest.fn(); - dataMock.query.filterManager.removeAll = jest.fn(); - clearStateFromSavedQuery(dataMock.query, setQueryState, DEFAULT_LANGUAGE); - expect(setQueryState).toHaveBeenCalled(); - expect((setQueryState.mock.calls[0][0] as Query).language).toBe(DEFAULT_LANGUAGE); + clearStateFromSavedQuery(dataMock.query); + expect(dataMock.query.queryString.clearQuery).toHaveBeenCalled(); expect(dataMock.query.filterManager.removeAll).toHaveBeenCalled(); }); }); diff --git a/src/plugins/data/public/ui/search_bar/lib/clear_saved_query.ts b/src/plugins/data/public/ui/search_bar/lib/clear_saved_query.ts index b2c777261c257..06ee56e9e4385 100644 --- a/src/plugins/data/public/ui/search_bar/lib/clear_saved_query.ts +++ b/src/plugins/data/public/ui/search_bar/lib/clear_saved_query.ts @@ -18,14 +18,7 @@ */ import { QueryStart } from '../../../query'; -export const clearStateFromSavedQuery = ( - queryService: QueryStart, - setQueryStringState: Function, - defaultLanguage: string -) => { +export const clearStateFromSavedQuery = (queryService: QueryStart) => { queryService.filterManager.removeAll(); - setQueryStringState({ - query: '', - language: defaultLanguage, - }); + queryService.queryString.clearQuery(); }; diff --git a/src/plugins/data/public/ui/search_bar/lib/populate_state_from_saved_query.test.ts b/src/plugins/data/public/ui/search_bar/lib/populate_state_from_saved_query.test.ts index 1db900053e078..660aa2333d49c 100644 --- a/src/plugins/data/public/ui/search_bar/lib/populate_state_from_saved_query.test.ts +++ b/src/plugins/data/public/ui/search_bar/lib/populate_state_from_saved_query.test.ts @@ -47,37 +47,34 @@ describe('populateStateFromSavedQuery', () => { }); it('should set query', async () => { - const setQueryState = jest.fn(); const savedQuery: SavedQuery = { ...baseSavedQuery, }; - populateStateFromSavedQuery(dataMock.query, setQueryState, savedQuery); - expect(setQueryState).toHaveBeenCalled(); + populateStateFromSavedQuery(dataMock.query, savedQuery); + expect(dataMock.query.queryString.setQuery).toHaveBeenCalled(); }); it('should set filters', async () => { - const setQueryState = jest.fn(); const savedQuery: SavedQuery = { ...baseSavedQuery, }; const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); savedQuery.attributes.filters = [f1]; - populateStateFromSavedQuery(dataMock.query, setQueryState, savedQuery); - expect(setQueryState).toHaveBeenCalled(); + populateStateFromSavedQuery(dataMock.query, savedQuery); + expect(dataMock.query.queryString.setQuery).toHaveBeenCalled(); expect(dataMock.query.filterManager.setFilters).toHaveBeenCalledWith([f1]); }); it('should preserve global filters', async () => { const globalFilter = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); dataMock.query.filterManager.getGlobalFilters = jest.fn().mockReturnValue([globalFilter]); - const setQueryState = jest.fn(); const savedQuery: SavedQuery = { ...baseSavedQuery, }; const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); savedQuery.attributes.filters = [f1]; - populateStateFromSavedQuery(dataMock.query, setQueryState, savedQuery); - expect(setQueryState).toHaveBeenCalled(); + populateStateFromSavedQuery(dataMock.query, savedQuery); + expect(dataMock.query.queryString.setQuery).toHaveBeenCalled(); expect(dataMock.query.filterManager.setFilters).toHaveBeenCalledWith([globalFilter, f1]); }); @@ -97,7 +94,7 @@ describe('populateStateFromSavedQuery', () => { dataMock.query.timefilter.timefilter.setTime = jest.fn(); dataMock.query.timefilter.timefilter.setRefreshInterval = jest.fn(); - populateStateFromSavedQuery(dataMock.query, jest.fn(), savedQuery); + populateStateFromSavedQuery(dataMock.query, savedQuery); expect(dataMock.query.timefilter.timefilter.setTime).toHaveBeenCalledWith({ from: savedQuery.attributes.timefilter.from, diff --git a/src/plugins/data/public/ui/search_bar/lib/populate_state_from_saved_query.ts b/src/plugins/data/public/ui/search_bar/lib/populate_state_from_saved_query.ts index 7ae6726b36df0..bb4b97cc4a9fd 100644 --- a/src/plugins/data/public/ui/search_bar/lib/populate_state_from_saved_query.ts +++ b/src/plugins/data/public/ui/search_bar/lib/populate_state_from_saved_query.ts @@ -19,14 +19,11 @@ import { QueryStart, SavedQuery } from '../../../query'; -export const populateStateFromSavedQuery = ( - queryService: QueryStart, - setQueryStringState: Function, - savedQuery: SavedQuery -) => { +export const populateStateFromSavedQuery = (queryService: QueryStart, savedQuery: SavedQuery) => { const { timefilter: { timefilter }, filterManager, + queryString, } = queryService; // timefilter if (savedQuery.attributes.timefilter) { @@ -40,7 +37,7 @@ export const populateStateFromSavedQuery = ( } // query string - setQueryStringState(savedQuery.attributes.query); + queryString.setQuery(savedQuery.attributes.query); // filters const savedQueryFilters = savedQuery.attributes.filters || []; diff --git a/src/plugins/data/public/ui/search_bar/lib/use_query_string_manager.ts b/src/plugins/data/public/ui/search_bar/lib/use_query_string_manager.ts new file mode 100644 index 0000000000000..e28129f20bb86 --- /dev/null +++ b/src/plugins/data/public/ui/search_bar/lib/use_query_string_manager.ts @@ -0,0 +1,51 @@ +/* + * 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 { useState, useEffect } from 'react'; +import { Subscription } from 'rxjs'; +import { Query } from '../../..'; +import { QueryStringContract } from '../../../query/query_string'; + +interface UseQueryStringProps { + query?: Query; + queryStringManager: QueryStringContract; +} + +export const useQueryStringManager = (props: UseQueryStringProps) => { + // Filters should be either what's passed in the initial state or the current state of the filter manager + const [query, setQuery] = useState(props.query || props.queryStringManager.getQuery()); + useEffect(() => { + const subscriptions = new Subscription(); + + subscriptions.add( + props.queryStringManager.getUpdates$().subscribe({ + next: () => { + const newQuery = props.queryStringManager.getQuery(); + setQuery(newQuery); + }, + }) + ); + + return () => { + subscriptions.unsubscribe(); + }; + }, [props.queryStringManager]); + + return { query }; +}; diff --git a/src/plugins/data/public/ui/search_bar/lib/use_saved_query.ts b/src/plugins/data/public/ui/search_bar/lib/use_saved_query.ts index 79aee3438d7aa..9f73a401f563b 100644 --- a/src/plugins/data/public/ui/search_bar/lib/use_saved_query.ts +++ b/src/plugins/data/public/ui/search_bar/lib/use_saved_query.ts @@ -27,10 +27,8 @@ import { clearStateFromSavedQuery } from './clear_saved_query'; interface UseSavedQueriesProps { queryService: DataPublicPluginStart['query']; - setQuery: Function; notifications: CoreStart['notifications']; savedQueryId?: string; - defaultLanguage: string; } interface UseSavedQueriesReturn { @@ -41,7 +39,6 @@ interface UseSavedQueriesReturn { export const useSavedQuery = (props: UseSavedQueriesProps): UseSavedQueriesReturn => { // Handle saved queries - const defaultLanguage = props.defaultLanguage; const [savedQuery, setSavedQuery] = useState(); // Effect is used to convert a saved query id into an object @@ -53,12 +50,12 @@ export const useSavedQuery = (props: UseSavedQueriesProps): UseSavedQueriesRetur // Make sure we set the saved query to the most recent one if (newSavedQuery && newSavedQuery.id === savedQueryId) { setSavedQuery(newSavedQuery); - populateStateFromSavedQuery(props.queryService, props.setQuery, newSavedQuery); + populateStateFromSavedQuery(props.queryService, newSavedQuery); } } catch (error) { // Clear saved query setSavedQuery(undefined); - clearStateFromSavedQuery(props.queryService, props.setQuery, defaultLanguage); + clearStateFromSavedQuery(props.queryService); // notify of saving error props.notifications.toasts.addWarning({ title: i18n.translate('data.search.unableToGetSavedQueryToastTitle', { @@ -73,23 +70,21 @@ export const useSavedQuery = (props: UseSavedQueriesProps): UseSavedQueriesRetur if (props.savedQueryId) fetchSavedQuery(props.savedQueryId); else setSavedQuery(undefined); }, [ - defaultLanguage, props.notifications.toasts, props.queryService, props.queryService.savedQueries, props.savedQueryId, - props.setQuery, ]); return { savedQuery, setSavedQuery: (q: SavedQuery) => { setSavedQuery(q); - populateStateFromSavedQuery(props.queryService, props.setQuery, q); + populateStateFromSavedQuery(props.queryService, q); }, clearSavedQuery: () => { setSavedQuery(undefined); - clearStateFromSavedQuery(props.queryService, props.setQuery, defaultLanguage); + clearStateFromSavedQuery(props.queryService); }, }; }; diff --git a/src/plugins/data/server/plugin.ts b/src/plugins/data/server/plugin.ts index 8fa32f9bd564f..61d8e566d2d2b 100644 --- a/src/plugins/data/server/plugin.ts +++ b/src/plugins/data/server/plugin.ts @@ -62,11 +62,11 @@ export class DataServerPlugin implements Plugin) { - this.searchService = new SearchService(initializerContext); + this.logger = initializerContext.logger.get('data'); + this.searchService = new SearchService(initializerContext, this.logger); this.scriptsService = new ScriptsService(); this.kqlTelemetryService = new KqlTelemetryService(initializerContext); this.autocompleteService = new AutocompleteService(initializerContext); - this.logger = initializerContext.logger.get('data'); } public setup( diff --git a/src/plugins/data/server/search/es_search/es_search_strategy.test.ts b/src/plugins/data/server/search/es_search/es_search_strategy.test.ts index 1155a5491e8f3..bc59bdee6a40a 100644 --- a/src/plugins/data/server/search/es_search/es_search_strategy.test.ts +++ b/src/plugins/data/server/search/es_search/es_search_strategy.test.ts @@ -22,6 +22,9 @@ import { pluginInitializerContextConfigMock } from '../../../../../core/server/m import { esSearchStrategyProvider } from './es_search_strategy'; describe('ES search strategy', () => { + const mockLogger: any = { + info: () => {}, + }; const mockApiCaller = jest.fn().mockResolvedValue({ _shards: { total: 10, @@ -40,14 +43,14 @@ describe('ES search strategy', () => { }); it('returns a strategy with `search`', async () => { - const esSearch = await esSearchStrategyProvider(mockConfig$); + const esSearch = await esSearchStrategyProvider(mockConfig$, mockLogger); expect(typeof esSearch.search).toBe('function'); }); it('calls the API caller with the params with defaults', async () => { const params = { index: 'logstash-*' }; - const esSearch = await esSearchStrategyProvider(mockConfig$); + const esSearch = await esSearchStrategyProvider(mockConfig$, mockLogger); await esSearch.search((mockContext as unknown) as RequestHandlerContext, { params }); @@ -63,7 +66,7 @@ describe('ES search strategy', () => { it('calls the API caller with overridden defaults', async () => { const params = { index: 'logstash-*', ignoreUnavailable: false, timeout: '1000ms' }; - const esSearch = await esSearchStrategyProvider(mockConfig$); + const esSearch = await esSearchStrategyProvider(mockConfig$, mockLogger); await esSearch.search((mockContext as unknown) as RequestHandlerContext, { params }); @@ -77,7 +80,7 @@ describe('ES search strategy', () => { it('returns total, loaded, and raw response', async () => { const params = { index: 'logstash-*' }; - const esSearch = await esSearchStrategyProvider(mockConfig$); + const esSearch = await esSearchStrategyProvider(mockConfig$, mockLogger); const response = await esSearch.search((mockContext as unknown) as RequestHandlerContext, { params, diff --git a/src/plugins/data/server/search/es_search/es_search_strategy.ts b/src/plugins/data/server/search/es_search/es_search_strategy.ts index 82f8ef21ebb38..b8010f735c327 100644 --- a/src/plugins/data/server/search/es_search/es_search_strategy.ts +++ b/src/plugins/data/server/search/es_search/es_search_strategy.ts @@ -17,16 +17,18 @@ * under the License. */ import { first } from 'rxjs/operators'; -import { SharedGlobalConfig } from 'kibana/server'; +import { SharedGlobalConfig, Logger } from 'kibana/server'; import { SearchResponse } from 'elasticsearch'; import { Observable } from 'rxjs'; import { ISearchStrategy, getDefaultSearchParams, getTotalLoaded } from '..'; export const esSearchStrategyProvider = ( - config$: Observable + config$: Observable, + logger: Logger ): ISearchStrategy => { return { search: async (context, request, options) => { + logger.info(`search ${JSON.stringify(request.params)}`); const config = await config$.pipe(first()).toPromise(); const defaultParams = getDefaultSearchParams(config); diff --git a/src/plugins/data/server/search/search_service.test.ts b/src/plugins/data/server/search/search_service.test.ts index 8c2ed96503003..be00b7409fe4a 100644 --- a/src/plugins/data/server/search/search_service.test.ts +++ b/src/plugins/data/server/search/search_service.test.ts @@ -28,7 +28,10 @@ describe('Search service', () => { let mockCoreSetup: MockedKeys>; beforeEach(() => { - plugin = new SearchService(coreMock.createPluginInitializerContext({})); + const mockLogger: any = { + info: () => {}, + }; + plugin = new SearchService(coreMock.createPluginInitializerContext({}), mockLogger); mockCoreSetup = coreMock.createSetup(); }); diff --git a/src/plugins/data/server/search/search_service.ts b/src/plugins/data/server/search/search_service.ts index 5686023e9a667..bbd0671754749 100644 --- a/src/plugins/data/server/search/search_service.ts +++ b/src/plugins/data/server/search/search_service.ts @@ -22,6 +22,7 @@ import { PluginInitializerContext, CoreSetup, RequestHandlerContext, + Logger, } from '../../../../core/server'; import { ISearchSetup, ISearchStart, ISearchStrategy } from './types'; import { registerSearchRoute } from './routes'; @@ -41,7 +42,10 @@ interface StrategyMap { export class SearchService implements Plugin { private searchStrategies: StrategyMap = {}; - constructor(private initializerContext: PluginInitializerContext) {} + constructor( + private initializerContext: PluginInitializerContext, + private readonly logger: Logger + ) {} public setup( core: CoreSetup, @@ -49,7 +53,7 @@ export class SearchService implements Plugin { ): ISearchSetup { this.registerSearchStrategy( ES_SEARCH_STRATEGY, - esSearchStrategyProvider(this.initializerContext.config.legacy.globalConfig$) + esSearchStrategyProvider(this.initializerContext.config.legacy.globalConfig$, this.logger) ); core.savedObjects.registerType(searchTelemetry); @@ -65,7 +69,11 @@ export class SearchService implements Plugin { return { registerSearchStrategy: this.registerSearchStrategy, usage }; } - private search(context: RequestHandlerContext, searchRequest: IEsSearchRequest, options: any) { + private search( + context: RequestHandlerContext, + searchRequest: IEsSearchRequest, + options: Record + ) { return this.getSearchStrategy(options.strategy || ES_SEARCH_STRATEGY).search( context, searchRequest, @@ -76,17 +84,25 @@ export class SearchService implements Plugin { public start(): ISearchStart { return { getSearchStrategy: this.getSearchStrategy, - search: this.search, + search: ( + context: RequestHandlerContext, + searchRequest: IEsSearchRequest, + options: Record + ) => { + return this.search(context, searchRequest, options); + }, }; } public stop() {} private registerSearchStrategy = (name: string, strategy: ISearchStrategy) => { + this.logger.info(`Register strategy ${name}`); this.searchStrategies[name] = strategy; }; private getSearchStrategy = (name: string): ISearchStrategy => { + this.logger.info(`Get strategy ${name}`); const strategy = this.searchStrategies[name]; if (!strategy) { throw new Error(`Search strategy ${name} not found`); diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index 99a77ff9aeb10..7ad2f9edd3325 100644 --- a/src/plugins/data/server/server.api.md +++ b/src/plugins/data/server/server.api.md @@ -4,6 +4,7 @@ ```ts +import { ApiResponse } from '@elastic/elasticsearch/lib/Transport'; import Boom from 'boom'; import { BulkIndexDocumentsParams } from 'elasticsearch'; import { CatAliasesParams } from 'elasticsearch'; @@ -91,6 +92,7 @@ import { IngestDeletePipelineParams } from 'elasticsearch'; import { IngestGetPipelineParams } from 'elasticsearch'; import { IngestPutPipelineParams } from 'elasticsearch'; import { IngestSimulateParams } from 'elasticsearch'; +import { KibanaClient } from '@elastic/elasticsearch/api/kibana'; import { KibanaConfigType as KibanaConfigType_2 } from 'src/core/server/kibana_config'; import { KibanaRequest as KibanaRequest_2 } from 'kibana/server'; import { LegacyAPICaller as LegacyAPICaller_2 } from 'kibana/server'; @@ -143,6 +145,9 @@ import { TasksGetParams } from 'elasticsearch'; import { TasksListParams } from 'elasticsearch'; import { TermvectorsParams } from 'elasticsearch'; import { ToastInputFields } from 'src/core/public/notifications'; +import { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport'; +import { TransportRequestParams } from '@elastic/elasticsearch/lib/Transport'; +import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; import { Type } from '@kbn/config-schema'; import { TypeOf } from '@kbn/config-schema'; import { Unit } from '@elastic/datemath'; diff --git a/src/plugins/discover/public/application/angular/directives/fixed_scroll.test.js b/src/plugins/discover/public/application/angular/directives/fixed_scroll.test.js index 16293ca621e05..65255d6c0c4a4 100644 --- a/src/plugins/discover/public/application/angular/directives/fixed_scroll.test.js +++ b/src/plugins/discover/public/application/angular/directives/fixed_scroll.test.js @@ -230,6 +230,10 @@ describe('FixedScroll directive', function () { $to = els[names.to]; }); + afterAll(() => { + delete angular.element.prototype.scrollLeft; + }); + test('transfers the scrollLeft', function () { expect(spyJQueryScrollLeft.callCount).toBe(0); expect(spyJQLiteScrollLeft.callCount).toBe(0); diff --git a/src/plugins/discover/public/application/angular/discover.html b/src/plugins/discover/public/application/angular/discover.html index 48a8442b06316..d3d4f524873d8 100644 --- a/src/plugins/discover/public/application/angular/discover.html +++ b/src/plugins/discover/public/application/angular/discover.html @@ -6,9 +6,8 @@

{{screenTitle}}

app-name="'discover'" config="topNavMenu" index-patterns="[indexPattern]" - on-query-submit="updateQuery" + on-query-submit="handleRefresh" on-saved-query-id-change="updateSavedQueryId" - query="state.query" saved-query-id="state.savedQuery" screen-title="screenTitle" show-date-picker="indexPattern.isTimeBased()" diff --git a/src/plugins/discover/public/application/angular/discover.js b/src/plugins/discover/public/application/angular/discover.js index c791bdd850151..4a27f261a6220 100644 --- a/src/plugins/discover/public/application/angular/discover.js +++ b/src/plugins/discover/public/application/angular/discover.js @@ -70,9 +70,7 @@ import { indexPatterns as indexPatternsUtils, connectToQueryState, syncQueryStateWithUrl, - getDefaultQuery, search, - UI_SETTINGS, } from '../../../../data/public'; import { getIndexPatternId } from '../helpers/get_index_pattern_id'; import { addFatalError } from '../../../../kibana_legacy/public'; @@ -191,16 +189,7 @@ app.directive('discoverApp', function () { }; }); -function discoverController( - $element, - $route, - $scope, - $timeout, - $window, - Promise, - localStorage, - uiCapabilities -) { +function discoverController($element, $route, $scope, $timeout, $window, Promise, uiCapabilities) { const { isDefault: isDefaultType } = indexPatternsUtils; const subscriptions = new Subscription(); const $fetchObservable = new Subject(); @@ -246,11 +235,15 @@ function discoverController( // sync initial app filters from state to filterManager filterManager.setAppFilters(_.cloneDeep(appStateContainer.getState().filters)); + data.query.queryString.setQuery(appStateContainer.getState().query); const stopSyncingQueryAppStateWithStateContainer = connectToQueryState( data.query, appStateContainer, - { filters: esFilters.FilterStateStore.APP_STATE } + { + filters: esFilters.FilterStateStore.APP_STATE, + query: true, + } ); const appStateUnsubscribe = appStateContainer.subscribe(async (newState) => { @@ -262,7 +255,7 @@ function discoverController( $scope.state = { ...newState }; // detect changes that should trigger fetching of new data - const changes = ['interval', 'sort', 'query'].filter( + const changes = ['interval', 'sort'].filter( (prop) => !_.isEqual(newStatePartial[prop], oldStatePartial[prop]) ); @@ -593,12 +586,7 @@ function discoverController( }; function getStateDefaults() { - const query = - $scope.searchSource.getField('query') || - getDefaultQuery( - localStorage.get('kibana.userQueryLanguage') || - config.get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE) - ); + const query = $scope.searchSource.getField('query') || data.query.queryString.getDefaultQuery(); return { query, sort: getSortArray(savedSearch.sort, $scope.indexPattern), @@ -635,12 +623,7 @@ function discoverController( const init = _.once(() => { $scope.updateDataSource().then(async () => { - const searchBarChanges = merge( - timefilter.getAutoRefreshFetch$(), - timefilter.getFetch$(), - filterManager.getFetches$(), - $fetchObservable - ).pipe(debounceTime(100)); + const searchBarChanges = merge(data.query.state$, $fetchObservable).pipe(debounceTime(100)); subscriptions.add( subscribeWithScope( @@ -824,9 +807,8 @@ function discoverController( }); }; - $scope.updateQuery = function ({ query }, isUpdate = true) { - if (!_.isEqual(query, appStateContainer.getState().query) || isUpdate === false) { - setAppState({ query }); + $scope.handleRefresh = function (_payload, isUpdate) { + if (isUpdate === false) { $fetchObservable.next(); } }; @@ -976,7 +958,7 @@ function discoverController( config.get(SORT_DEFAULT_ORDER_SETTING) ) ) - .setField('query', $scope.state.query || null) + .setField('query', data.query.queryString.getQuery() || null) .setField('filter', filterManager.getFilters()); return Promise.resolve(); }; diff --git a/src/plugins/discover/public/application/angular/doc_table/components/row_headers.test.js b/src/plugins/discover/public/application/angular/doc_table/components/row_headers.test.js new file mode 100644 index 0000000000000..b30b13b1f0b6e --- /dev/null +++ b/src/plugins/discover/public/application/angular/doc_table/components/row_headers.test.js @@ -0,0 +1,485 @@ +/* + * 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 angular from 'angular'; +import 'angular-mocks'; +import 'angular-sanitize'; +import 'angular-route'; +import _ from 'lodash'; +import sinon from 'sinon'; +import { getFakeRow, getFakeRowVals } from 'fixtures/fake_row'; +import $ from 'jquery'; +import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; +import { setScopedHistory, setServices, setDocViewsRegistry } from '../../../../kibana_services'; +import { coreMock } from '../../../../../../../core/public/mocks'; +import { dataPluginMock } from '../../../../../../data/public/mocks'; +import { navigationPluginMock } from '../../../../../../navigation/public/mocks'; +import { getInnerAngularModule } from '../../../../get_inner_angular'; +import { createBrowserHistory } from 'history'; + +describe('Doc Table', () => { + const core = coreMock.createStart(); + const dataMock = dataPluginMock.createStartContract(); + let $parentScope; + let $scope; + let $elementScope; + let timeout; + let registry = []; + + // Stub out a minimal mapping of 4 fields + let mapping; + + let fakeRowVals; + let stubFieldFormatConverter; + beforeAll(() => setScopedHistory(createBrowserHistory())); + beforeEach(() => { + angular.element.prototype.slice = jest.fn(function (index) { + return $(this).slice(index); + }); + angular.element.prototype.filter = jest.fn(function (condition) { + return $(this).filter(condition); + }); + angular.element.prototype.toggle = jest.fn(function (name) { + return $(this).toggle(name); + }); + angular.element.prototype.is = jest.fn(function (name) { + return $(this).is(name); + }); + setServices({ + uiSettings: core.uiSettings, + filterManager: dataMock.query.filterManager, + }); + + setDocViewsRegistry({ + addDocView(view) { + registry.push(view); + }, + getDocViewsSorted() { + return registry; + }, + resetRegistry: () => { + registry = []; + }, + }); + + getInnerAngularModule( + 'app/discover', + core, + { + data: dataMock, + navigation: navigationPluginMock.createStartContract(), + }, + coreMock.createPluginInitializerContext() + ); + angular.mock.module('app/discover'); + }); + beforeEach( + angular.mock.inject(function ($rootScope, Private, $timeout) { + $parentScope = $rootScope; + timeout = $timeout; + $parentScope.indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + mapping = $parentScope.indexPattern.fields; + + // Stub `getConverterFor` for a field in the indexPattern to return mock data. + // Returns `val` if provided, otherwise generates fake data for the field. + fakeRowVals = getFakeRowVals('formatted', 0, mapping); + stubFieldFormatConverter = function ($root, field, val) { + const convertFn = (value, type, options) => { + if (val) { + return val; + } + const fieldName = _.get(options, 'field.name', null); + + return fakeRowVals[fieldName] || ''; + }; + + $root.indexPattern.fields.getByName(field).format.convert = convertFn; + $root.indexPattern.fields.getByName(field).format.getConverterFor = () => convertFn; + }; + }) + ); + + afterEach(() => { + delete angular.element.prototype.slice; + delete angular.element.prototype.filter; + delete angular.element.prototype.toggle; + delete angular.element.prototype.is; + }); + + // Sets up the directive, take an element, and a list of properties to attach to the parent scope. + const init = function ($elem, props) { + angular.mock.inject(function ($compile) { + _.assign($parentScope, props); + const el = $compile($elem)($parentScope); + $elementScope = el.scope(); + el.scope().$digest(); + $scope = el.isolateScope(); + }); + }; + + const destroy = () => { + $scope.$destroy(); + $parentScope.$destroy(); + }; + + // For testing column removing/adding for the header and the rows + const columnTests = function (elemType, parentElem) { + test('should create a time column if the timefield is defined', () => { + const childElems = parentElem.find(elemType); + expect(childElems.length).toBe(1); + }); + + test('should be able to add and remove columns', () => { + let childElems; + + stubFieldFormatConverter($parentScope, 'bytes'); + stubFieldFormatConverter($parentScope, 'request_body'); + + // Should include a column for toggling and the time column by default + $parentScope.columns = ['bytes']; + $elementScope.$digest(); + childElems = parentElem.find(elemType); + expect(childElems.length).toBe(2); + expect($(childElems[1]).text()).toContain('bytes'); + + $parentScope.columns = ['bytes', 'request_body']; + $elementScope.$digest(); + childElems = parentElem.find(elemType); + expect(childElems.length).toBe(3); + expect($(childElems[2]).text()).toContain('request_body'); + + $parentScope.columns = ['request_body']; + $elementScope.$digest(); + childElems = parentElem.find(elemType); + expect(childElems.length).toBe(2); + expect($(childElems[1]).text()).toContain('request_body'); + }); + + test('should create only the toggle column if there is no timeField', () => { + delete $scope.indexPattern.timeFieldName; + $scope.$digest(); + timeout.flush(); + + const childElems = parentElem.find(elemType); + expect(childElems.length).toBe(0); + }); + }; + + describe('kbnTableRow', () => { + const $elem = $( + '' + ); + let row; + + beforeEach(() => { + row = getFakeRow(0, mapping); + + init($elem, { + row, + columns: [], + sorting: [], + filter: sinon.spy(), + maxLength: 50, + }); + }); + afterEach(() => { + destroy(); + }); + + describe('adding and removing columns', () => { + columnTests('[data-test-subj~="docTableField"]', $elem); + }); + + describe('details row', () => { + test('should be an empty tr by default', () => { + expect($elem.next().is('tr')).toBe(true); + expect($elem.next().text()).toBe(''); + }); + + test('should expand the detail row when the toggle arrow is clicked', () => { + $elem.children(':first-child').click(); + expect($elem.next().text()).not.toBe(''); + }); + + describe('expanded', () => { + let $details; + beforeEach(() => { + // Open the row + $scope.toggleRow(); + timeout.flush(); + $details = $elem.next(); + }); + afterEach(() => { + // Close the row + $scope.toggleRow(); + }); + + test('should be a tr with something in it', () => { + expect($details.is('tr')).toBe(true); + expect($details.text()).toBeTruthy(); + }); + }); + }); + }); + + describe('kbnTableRow meta', () => { + const $elem = angular.element( + '' + ); + let row; + + beforeEach(() => { + row = getFakeRow(0, mapping); + + init($elem, { + row: row, + columns: [], + sorting: [], + filtering: sinon.spy(), + maxLength: 50, + }); + + // Open the row + $scope.toggleRow(); + $scope.$digest(); + timeout.flush(); + $elem.next(); + }); + + afterEach(() => { + destroy(); + }); + + /** this no longer works with the new plugin approach + test('should render even when the row source contains a field with the same name as a meta field', () => { + setTimeout(() => { + //this should be overridden by later changes + }, 100); + expect($details.find('tr').length).toBe(_.keys($parentScope.indexPattern.flattenHit($scope.row)).length); + }); */ + }); + + describe('row diffing', () => { + let $row; + let $scope; + let $root; + let $before; + + beforeEach( + angular.mock.inject(function ($rootScope, $compile, Private) { + $root = $rootScope; + $root.row = getFakeRow(0, mapping); + $root.columns = ['_source']; + $root.sorting = []; + $root.filtering = sinon.spy(); + $root.maxLength = 50; + $root.mapping = mapping; + $root.indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + + // Stub field format converters for every field in the indexPattern + $root.indexPattern.fields.forEach((f) => stubFieldFormatConverter($root, f.name)); + + $row = $('').attr({ + 'kbn-table-row': 'row', + columns: 'columns', + sorting: 'sorting', + filtering: 'filtering', + 'index-pattern': 'indexPattern', + }); + + $scope = $root.$new(); + $compile($row)($scope); + $root.$apply(); + + $before = $row.find('td'); + expect($before).toHaveLength(3); + expect($before.eq(0).text().trim()).toBe(''); + expect($before.eq(1).text().trim()).toMatch(/^time_formatted/); + }) + ); + + afterEach(() => { + $row.remove(); + }); + + test('handles a new column', () => { + $root.columns.push('bytes'); + $root.$apply(); + + const $after = $row.find('td'); + expect($after).toHaveLength(4); + expect($after[0].outerHTML).toBe($before[0].outerHTML); + expect($after[1].outerHTML).toBe($before[1].outerHTML); + expect($after[2].outerHTML).toBe($before[2].outerHTML); + expect($after.eq(3).text().trim()).toMatch(/^bytes_formatted/); + }); + + test('handles two new columns at once', () => { + $root.columns.push('bytes'); + $root.columns.push('request_body'); + $root.$apply(); + + const $after = $row.find('td'); + expect($after).toHaveLength(5); + expect($after[0].outerHTML).toBe($before[0].outerHTML); + expect($after[1].outerHTML).toBe($before[1].outerHTML); + expect($after[2].outerHTML).toBe($before[2].outerHTML); + expect($after.eq(3).text().trim()).toMatch(/^bytes_formatted/); + expect($after.eq(4).text().trim()).toMatch(/^request_body_formatted/); + }); + + test('handles three new columns in odd places', () => { + $root.columns = ['@timestamp', 'bytes', '_source', 'request_body']; + $root.$apply(); + + const $after = $row.find('td'); + expect($after).toHaveLength(6); + expect($after[0].outerHTML).toBe($before[0].outerHTML); + expect($after[1].outerHTML).toBe($before[1].outerHTML); + expect($after.eq(2).text().trim()).toMatch(/^@timestamp_formatted/); + expect($after.eq(3).text().trim()).toMatch(/^bytes_formatted/); + expect($after[4].outerHTML).toBe($before[2].outerHTML); + expect($after.eq(5).text().trim()).toMatch(/^request_body_formatted/); + }); + + test('handles a removed column', () => { + _.pull($root.columns, '_source'); + $root.$apply(); + + const $after = $row.find('td'); + expect($after).toHaveLength(2); + expect($after[0].outerHTML).toBe($before[0].outerHTML); + expect($after[1].outerHTML).toBe($before[1].outerHTML); + }); + + test('handles two removed columns', () => { + // first add a column + $root.columns.push('@timestamp'); + $root.$apply(); + + const $mid = $row.find('td'); + expect($mid).toHaveLength(4); + + $root.columns.pop(); + $root.columns.pop(); + $root.$apply(); + + const $after = $row.find('td'); + expect($after).toHaveLength(2); + expect($after[0].outerHTML).toBe($before[0].outerHTML); + expect($after[1].outerHTML).toBe($before[1].outerHTML); + }); + + test('handles three removed random columns', () => { + // first add two column + $root.columns.push('@timestamp', 'bytes'); + $root.$apply(); + + const $mid = $row.find('td'); + expect($mid).toHaveLength(5); + + $root.columns[0] = false; // _source + $root.columns[2] = false; // bytes + $root.columns = $root.columns.filter(Boolean); + $root.$apply(); + + const $after = $row.find('td'); + expect($after).toHaveLength(3); + expect($after[0].outerHTML).toBe($before[0].outerHTML); + expect($after[1].outerHTML).toBe($before[1].outerHTML); + expect($after.eq(2).text().trim()).toMatch(/^@timestamp_formatted/); + }); + + test('handles two columns with the same content', () => { + stubFieldFormatConverter($root, 'request_body', fakeRowVals.bytes); + + $root.columns.length = 0; + $root.columns.push('bytes'); + $root.columns.push('request_body'); + $root.$apply(); + + const $after = $row.find('td'); + expect($after).toHaveLength(4); + expect($after.eq(2).text().trim()).toMatch(/^bytes_formatted/); + expect($after.eq(3).text().trim()).toMatch(/^bytes_formatted/); + }); + + test('handles two columns swapping position', () => { + $root.columns.push('bytes'); + $root.$apply(); + + const $mid = $row.find('td'); + expect($mid).toHaveLength(4); + + $root.columns.reverse(); + $root.$apply(); + + const $after = $row.find('td'); + expect($after).toHaveLength(4); + expect($after[0].outerHTML).toBe($before[0].outerHTML); + expect($after[1].outerHTML).toBe($before[1].outerHTML); + expect($after[2].outerHTML).toBe($mid[3].outerHTML); + expect($after[3].outerHTML).toBe($mid[2].outerHTML); + }); + + test('handles four columns all reversing position', () => { + $root.columns.push('bytes', 'response', '@timestamp'); + $root.$apply(); + + const $mid = $row.find('td'); + expect($mid).toHaveLength(6); + + $root.columns.reverse(); + $root.$apply(); + + const $after = $row.find('td'); + expect($after).toHaveLength(6); + expect($after[0].outerHTML).toBe($before[0].outerHTML); + expect($after[1].outerHTML).toBe($before[1].outerHTML); + expect($after[2].outerHTML).toBe($mid[5].outerHTML); + expect($after[3].outerHTML).toBe($mid[4].outerHTML); + expect($after[4].outerHTML).toBe($mid[3].outerHTML); + expect($after[5].outerHTML).toBe($mid[2].outerHTML); + }); + + test('handles multiple columns with the same name', () => { + $root.columns.push('bytes', 'bytes', 'bytes'); + $root.$apply(); + + const $after = $row.find('td'); + expect($after).toHaveLength(6); + expect($after[0].outerHTML).toBe($before[0].outerHTML); + expect($after[1].outerHTML).toBe($before[1].outerHTML); + expect($after[2].outerHTML).toBe($before[2].outerHTML); + expect($after.eq(3).text().trim()).toMatch(/^bytes_formatted/); + expect($after.eq(4).text().trim()).toMatch(/^bytes_formatted/); + expect($after.eq(5).text().trim()).toMatch(/^bytes_formatted/); + }); + }); +}); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js b/src/plugins/discover/public/application/angular/doc_table/doc_table.test.js similarity index 52% rename from src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js rename to src/plugins/discover/public/application/angular/doc_table/doc_table.test.js index 504b00808718b..9722981df42b1 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js +++ b/src/plugins/discover/public/application/angular/doc_table/doc_table.test.js @@ -17,15 +17,18 @@ * under the License. */ import angular from 'angular'; -import expect from '@kbn/expect'; import _ from 'lodash'; -import ngMock from 'ng_mock'; -import 'ui/private'; -import { pluginInstance } from './legacy'; +import 'angular-mocks'; +import 'angular-sanitize'; +import 'angular-route'; +import { createBrowserHistory } from 'history'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; import hits from 'fixtures/real_hits'; -import { setScopedHistory } from '../../../../../../plugins/discover/public/kibana_services'; -import { createBrowserHistory } from 'history'; +import { coreMock } from '../../../../../../core/public/mocks'; +import { dataPluginMock } from '../../../../../data/public/mocks'; +import { navigationPluginMock } from '../../../../../navigation/public/mocks'; +import { setScopedHistory, setServices } from '../../../kibana_services'; +import { getInnerAngularModule } from '../../../get_inner_angular'; let $parentScope; @@ -36,7 +39,7 @@ let $timeout; let indexPattern; const init = function ($elem, props) { - ngMock.inject(function ($rootScope, $compile, _$timeout_) { + angular.mock.inject(function ($rootScope, $compile, _$timeout_) { $timeout = _$timeout_; $parentScope = $rootScope; _.assign($parentScope, props); @@ -44,7 +47,7 @@ const init = function ($elem, props) { $compile($elem)($parentScope); // I think the prereq requires this? - $timeout(function () { + $timeout(() => { $elem.scope().$digest(); }, 0); @@ -52,19 +55,40 @@ const init = function ($elem, props) { }); }; -const destroy = function () { +const destroy = () => { $scope.$destroy(); $parentScope.$destroy(); }; -describe('docTable', function () { +describe('docTable', () => { + const core = coreMock.createStart(); let $elem; - before(() => setScopedHistory(createBrowserHistory())); - beforeEach(() => pluginInstance.initializeInnerAngular()); - beforeEach(() => pluginInstance.initializeServices()); - beforeEach(ngMock.module('app/discover')); - beforeEach(function () { + beforeAll(() => setScopedHistory(createBrowserHistory())); + beforeEach(() => { + angular.element.prototype.slice = jest.fn(() => { + return null; + }); + angular.element.prototype.filter = jest.fn(() => { + return { + remove: jest.fn(), + }; + }); + setServices({ + uiSettings: core.uiSettings, + }); + getInnerAngularModule( + 'app/discover', + core, + { + data: dataPluginMock.createStartContract(), + navigation: navigationPluginMock.createStartContract(), + }, + coreMock.createPluginInitializerContext() + ); + angular.mock.module('app/discover'); + }); + beforeEach(() => { $elem = angular.element(` `); - ngMock.inject(function (Private) { + angular.mock.inject(function (Private) { indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); }); init($elem, { @@ -87,34 +111,36 @@ describe('docTable', function () { $scope.$digest(); }); - afterEach(function () { + afterEach(() => { + delete angular.element.prototype.slice; + delete angular.element.prototype.filter; destroy(); }); - it('should compile', function () { - expect($elem.text()).to.not.be.empty(); + test('should compile', () => { + expect($elem.text()).toBeTruthy(); }); - it('should have an addRows function that increases the row count', function () { - expect($scope.addRows).to.be.a(Function); + test('should have an addRows function that increases the row count', () => { + expect($scope.addRows).toBeInstanceOf(Function); $scope.$digest(); - expect($scope.limit).to.be(50); + expect($scope.limit).toBe(50); $scope.addRows(); - expect($scope.limit).to.be(100); + expect($scope.limit).toBe(100); }); - it('should reset the row limit when results are received', function () { + test('should reset the row limit when results are received', () => { $scope.limit = 100; - expect($scope.limit).to.be(100); + expect($scope.limit).toBe(100); $scope.hits = [...hits]; $scope.$digest(); - expect($scope.limit).to.be(50); + expect($scope.limit).toBe(50); }); - it('should have a header and a table element', function () { + test('should have a header and a table element', () => { $scope.$digest(); - expect($elem.find('thead').length).to.be(1); - expect($elem.find('table').length).to.be(1); + expect($elem.find('thead').length).toBe(1); + expect($elem.find('table').length).toBe(1); }); }); diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/global_flyout/global_flyout.tsx b/src/plugins/es_ui_shared/__packages_do_not_import__/global_flyout/global_flyout.tsx new file mode 100644 index 0000000000000..aa575cd64944c --- /dev/null +++ b/src/plugins/es_ui_shared/__packages_do_not_import__/global_flyout/global_flyout.tsx @@ -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 React, { + createContext, + useContext, + useState, + useCallback, + useMemo, + useEffect, + useRef, +} from 'react'; +import { EuiFlyout } from '@elastic/eui'; + +interface Context { + addContent:

(content: Content

) => void; + removeContent: (contentId: string) => void; + closeFlyout: () => void; +} + +interface Content

{ + id: string; + Component: React.FunctionComponent

; + props?: P; + flyoutProps?: { [key: string]: any }; + cleanUpFunc?: () => void; +} + +const FlyoutMultiContentContext = createContext(undefined); + +const DEFAULT_FLYOUT_PROPS = { + 'data-test-subj': 'flyout', + size: 'm' as 'm', + maxWidth: 500, +}; + +export const GlobalFlyoutProvider: React.FC = ({ children }) => { + const [showFlyout, setShowFlyout] = useState(false); + const [activeContent, setActiveContent] = useState | undefined>(undefined); + + const { id, Component, props, flyoutProps } = activeContent ?? {}; + + const addContent: Context['addContent'] = useCallback((content) => { + setActiveContent((prev) => { + if (prev !== undefined) { + if (prev.id !== content.id && prev.cleanUpFunc) { + // Clean up anything from the content about to be removed + prev.cleanUpFunc(); + } + } + return content; + }); + + setShowFlyout(true); + }, []); + + const closeFlyout: Context['closeFlyout'] = useCallback(() => { + setActiveContent(undefined); + setShowFlyout(false); + }, []); + + const removeContent: Context['removeContent'] = useCallback( + (contentId: string) => { + if (contentId === id) { + closeFlyout(); + } + }, + [id, closeFlyout] + ); + + const mergedFlyoutProps = useMemo(() => { + return { + ...DEFAULT_FLYOUT_PROPS, + onClose: closeFlyout, + ...flyoutProps, + }; + }, [flyoutProps, closeFlyout]); + + const context: Context = { + addContent, + removeContent, + closeFlyout, + }; + + const ContentFlyout = showFlyout && Component !== undefined ? Component : null; + + return ( + + <> + {children} + {ContentFlyout && ( + + + + )} + + + ); +}; + +export const useGlobalFlyout = () => { + const ctx = useContext(FlyoutMultiContentContext); + + if (ctx === undefined) { + throw new Error('useGlobalFlyout must be used within a '); + } + + const isMounted = useRef(false); + /** + * A component can add one or multiple content to the flyout + * during its lifecycle. When it unmounts, we will remove + * all those content added to the flyout. + */ + const contents = useRef | undefined>(undefined); + const { removeContent, addContent: addContentToContext } = ctx; + + useEffect(() => { + isMounted.current = true; + + return () => { + isMounted.current = false; + }; + }, []); + + const getContents = useCallback(() => { + if (contents.current === undefined) { + contents.current = new Set(); + } + return contents.current; + }, []); + + const addContent: Context['addContent'] = useCallback( + (content) => { + getContents().add(content.id); + return addContentToContext(content); + }, + [getContents, addContentToContext] + ); + + useEffect(() => { + return () => { + if (!isMounted.current) { + // When the component unmounts, remove all the content it has added to the flyout + Array.from(getContents()).forEach(removeContent); + } + }; + }, [removeContent]); + + return { ...ctx, addContent }; +}; diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/global_flyout/index.ts b/src/plugins/es_ui_shared/__packages_do_not_import__/global_flyout/index.ts new file mode 100644 index 0000000000000..c49692547fb25 --- /dev/null +++ b/src/plugins/es_ui_shared/__packages_do_not_import__/global_flyout/index.ts @@ -0,0 +1,20 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export { GlobalFlyoutProvider, useGlobalFlyout } from './global_flyout'; diff --git a/src/plugins/es_ui_shared/public/forms/form_wizard/form_wizard.tsx b/src/plugins/es_ui_shared/public/forms/form_wizard/form_wizard.tsx index cdb332e9e9130..642a21eae50e9 100644 --- a/src/plugins/es_ui_shared/public/forms/form_wizard/form_wizard.tsx +++ b/src/plugins/es_ui_shared/public/forms/form_wizard/form_wizard.tsx @@ -27,13 +27,14 @@ import { } from './form_wizard_context'; import { FormWizardNav, NavTexts } from './form_wizard_nav'; -interface Props extends ProviderProps { +interface Props extends ProviderProps { isSaving?: boolean; apiError: JSX.Element | null; texts?: Partial; + rightContentNav?: JSX.Element | null | ((stepId: S) => JSX.Element | null); } -export function FormWizard({ +export function FormWizard({ texts, defaultActiveStep, defaultValue, @@ -43,7 +44,8 @@ export function FormWizard({ onSave, onChange, children, -}: Props) { + rightContentNav, +}: Props) { return ( defaultValue={defaultValue} @@ -53,7 +55,14 @@ export function FormWizard({ defaultActiveStep={defaultActiveStep} > - {({ activeStepIndex, lastStep, steps, isCurrentStepValid, navigateToStep }) => { + {({ + activeStepIndex, + lastStep, + steps, + isCurrentStepValid, + navigateToStep, + activeStepId, + }) => { const stepsRequiredArray = Object.values(steps).map( (step) => Boolean(step.isRequired) && step.isComplete === false ); @@ -95,6 +104,13 @@ export function FormWizard({ }; }); + const getRightContentNav = () => { + if (typeof rightContentNav === 'function') { + return rightContentNav(activeStepId); + } + return rightContentNav; + }; + const onBack = () => { const prevStep = activeStepIndex - 1; navigateToStep(prevStep); @@ -129,6 +145,7 @@ export function FormWizard({ onBack={onBack} onNext={onNext} texts={texts} + getRightContent={getRightContentNav} /> ); diff --git a/src/plugins/es_ui_shared/public/forms/form_wizard/form_wizard_nav.tsx b/src/plugins/es_ui_shared/public/forms/form_wizard/form_wizard_nav.tsx index 3e0e9cf897b5d..0af99e8bce35a 100644 --- a/src/plugins/es_ui_shared/public/forms/form_wizard/form_wizard_nav.tsx +++ b/src/plugins/es_ui_shared/public/forms/form_wizard/form_wizard_nav.tsx @@ -29,6 +29,7 @@ interface Props { isSaving?: boolean; isStepValid?: boolean; texts?: Partial; + getRightContent?: () => JSX.Element | null | undefined; } export interface NavTexts { @@ -53,6 +54,7 @@ export const FormWizardNav = ({ onBack, onNext, texts, + getRightContent, }: Props) => { const isLastStep = activeStepIndex === lastStep; const labels = { @@ -66,6 +68,8 @@ export const FormWizardNav = ({ : labels.save : labels.next; + const rightContent = getRightContent !== undefined ? getRightContent() : undefined; + return ( @@ -100,6 +104,8 @@ export const FormWizardNav = ({ + + {rightContent && {rightContent}} ); }; diff --git a/src/plugins/es_ui_shared/public/forms/multi_content/use_multi_content.ts b/src/plugins/es_ui_shared/public/forms/multi_content/use_multi_content.ts index 8d470f6454b0e..2e7c91a26e1fc 100644 --- a/src/plugins/es_ui_shared/public/forms/multi_content/use_multi_content.ts +++ b/src/plugins/es_ui_shared/public/forms/multi_content/use_multi_content.ts @@ -94,7 +94,7 @@ export function useMultiContent({ const activeContentData: Partial = {}; for (const [id, _content] of Object.entries(contents.current)) { - if (validation.contents[id as keyof T]) { + if (validation.contents[id as keyof T] !== false) { const contentData = (_content as Content).getData(); // Replace the getData() handler with the cached value @@ -161,7 +161,7 @@ export function useMultiContent({ ); /** - * Validate the multi-content active content(s) in the DOM + * Validate the content(s) currently in the DOM */ const validate = useCallback(async () => { if (Object.keys(contents.current).length === 0) { diff --git a/scripts/build_renovate_config.js b/src/plugins/es_ui_shared/public/global_flyout/index.ts similarity index 88% rename from scripts/build_renovate_config.js rename to src/plugins/es_ui_shared/public/global_flyout/index.ts index b9171c44f4a8a..e876594337c1e 100644 --- a/scripts/build_renovate_config.js +++ b/src/plugins/es_ui_shared/public/global_flyout/index.ts @@ -17,5 +17,7 @@ * under the License. */ -require('../src/setup_node_env'); -require('../src/dev/renovate/run_build_renovate_config_cli'); +export { + GlobalFlyoutProvider, + useGlobalFlyout, +} from '../../__packages_do_not_import__/global_flyout'; diff --git a/src/plugins/es_ui_shared/public/index.ts b/src/plugins/es_ui_shared/public/index.ts index 98a305fe68f08..bdea5ccf5fe26 100644 --- a/src/plugins/es_ui_shared/public/index.ts +++ b/src/plugins/es_ui_shared/public/index.ts @@ -24,6 +24,7 @@ import * as Forms from './forms'; import * as Monaco from './monaco'; import * as ace from './ace'; +import * as GlobalFlyout from './global_flyout'; export { JsonEditor, OnJsonEditorUpdateHandler } from './components/json_editor'; @@ -65,7 +66,7 @@ export { useAuthorizationContext, } from './authorization'; -export { Monaco, Forms, ace }; +export { Monaco, Forms, ace, GlobalFlyout }; export { extractQueryParams } from './url'; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/serializers.ts b/src/plugins/es_ui_shared/static/forms/helpers/serializers.ts index 98287f6bac35d..733a60f1f86ff 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/serializers.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/serializers.ts @@ -64,9 +64,13 @@ interface StripEmptyFieldsOptions { * @param options An optional configuration object. By default recursive it turned on. */ export const stripEmptyFields = ( - object: { [key: string]: any }, + object?: { [key: string]: any }, options?: StripEmptyFieldsOptions ): { [key: string]: any } => { + if (object === undefined) { + return {}; + } + const { types = ['string', 'object'], recursive = false } = options || {}; return Object.entries(object).reduce((acc, [key, value]) => { diff --git a/src/plugins/expressions/common/execution/execution.test.ts b/src/plugins/expressions/common/execution/execution.test.ts index 4e73d27c1c4a1..2b8aa4b5e68f0 100644 --- a/src/plugins/expressions/common/execution/execution.test.ts +++ b/src/plugins/expressions/common/execution/execution.test.ts @@ -376,6 +376,38 @@ describe('Execution', () => { value: 5, }); }); + + test('can use global variables', async () => { + const result = await run( + 'add val={var foo}', + { + variables: { + foo: 3, + }, + }, + null + ); + + expect(result).toMatchObject({ + type: 'num', + value: 3, + }); + }); + + test('can modify global variables', async () => { + const result = await run( + 'add val={var_set name=foo value=66 | var bar} | var foo', + { + variables: { + foo: 3, + bar: 25, + }, + }, + null + ); + + expect(result).toBe(66); + }); }); describe('when arguments are missing', () => { diff --git a/src/plugins/home/server/services/sample_data/routes/list.ts b/src/plugins/home/server/services/sample_data/routes/list.ts index 770b3116b74f1..7cce0fa5cccb3 100644 --- a/src/plugins/home/server/services/sample_data/routes/list.ts +++ b/src/plugins/home/server/services/sample_data/routes/list.ts @@ -16,7 +16,6 @@ * specific language governing permissions and limitations * under the License. */ -import { isBoom } from 'boom'; import { IRouter } from 'src/core/server'; import { SampleDatasetSchema } from '../lib/sample_dataset_registry_types'; import { createIndexName } from '../lib/create_index_name'; @@ -75,8 +74,7 @@ export const createListRoute = (router: IRouter, sampleDatasets: SampleDatasetSc try { await context.core.savedObjects.client.get('dashboard', sampleDataset.overviewDashboard); } catch (err) { - // savedObjectClient.get() throws an boom error when object is not found. - if (isBoom(err) && err.output.statusCode === 404) { + if (context.core.savedObjects.client.errors.isNotFoundError(err)) { sampleDataset.status = NOT_INSTALLED; return; } diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/test_script.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/test_script.tsx index c97f19f59d340..cb1d5a25c01ae 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/test_script.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/test_script.tsx @@ -35,12 +35,7 @@ import { import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; -import { - esQuery, - IndexPattern, - Query, - UI_SETTINGS, -} from '../../../../../../../plugins/data/public'; +import { esQuery, IndexPattern, Query } from '../../../../../../../plugins/data/public'; import { context as contextType } from '../../../../../../kibana_react/public'; import { IndexPatternManagmentContextValue } from '../../../../types'; import { ExecuteScript } from '../../types'; @@ -248,10 +243,7 @@ export class TestScript extends Component { showFilterBar={false} showDatePicker={false} showQueryInput={true} - query={{ - language: this.context.services.uiSettings.get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE), - query: '', - }} + query={this.context.services.data.query.queryString.getDefaultQuery()} onQuerySubmit={this.previewScript} indexPatterns={[this.props.indexPattern]} customSubmitButton={ diff --git a/src/plugins/inspector/public/views/data/components/data_view.test.tsx b/src/plugins/inspector/public/views/data/components/data_view.test.tsx index 2772069d36877..bd78bca42c479 100644 --- a/src/plugins/inspector/public/views/data/components/data_view.test.tsx +++ b/src/plugins/inspector/public/views/data/components/data_view.test.tsx @@ -51,13 +51,13 @@ describe('Inspector Data View', () => { }); it('should render loading state', () => { - const component = mountWithIntl(); + const component = mountWithIntl(); // eslint-disable-line react/jsx-pascal-case expect(component).toMatchSnapshot(); }); it('should render empty state', async () => { - const component = mountWithIntl(); + const component = mountWithIntl(); // eslint-disable-line react/jsx-pascal-case const tabularLoader = Promise.resolve(null); adapters.data.setTabularLoader(() => tabularLoader); await tabularLoader; diff --git a/src/plugins/status_page/kibana.json b/src/plugins/status_page/kibana.json deleted file mode 100644 index 0d54f6a39e2b1..0000000000000 --- a/src/plugins/status_page/kibana.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "id": "statusPage", - "version": "kibana", - "server": false, - "ui": true -} diff --git a/src/plugins/status_page/public/plugin.ts b/src/plugins/status_page/public/plugin.ts deleted file mode 100644 index d072fd4a67c30..0000000000000 --- a/src/plugins/status_page/public/plugin.ts +++ /dev/null @@ -1,39 +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 { Plugin, CoreSetup } from 'kibana/public'; - -export class StatusPagePlugin implements Plugin { - public setup(core: CoreSetup) { - const isStatusPageAnonymous = core.injectedMetadata.getInjectedVar( - 'isStatusPageAnonymous' - ) as boolean; - - if (isStatusPageAnonymous) { - core.http.anonymousPaths.register('/status'); - } - } - - public start() {} - - public stop() {} -} - -export type StatusPagePluginSetup = ReturnType; -export type StatusPagePluginStart = ReturnType; diff --git a/src/plugins/timelion/public/directives/timelion_expression_suggestions/__tests__/timelion_expression_suggestions.js b/src/plugins/timelion/public/directives/timelion_expression_suggestions/__tests__/timelion_expression_suggestions.js deleted file mode 100644 index 8a35a72ed19e6..0000000000000 --- a/src/plugins/timelion/public/directives/timelion_expression_suggestions/__tests__/timelion_expression_suggestions.js +++ /dev/null @@ -1,58 +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 expect from '@kbn/expect'; -import ngMock from 'ng_mock'; -import '../timelion_expression_suggestions'; - -describe('Timelion expression suggestions directive', function () { - let scope; - let $compile; - - beforeEach(ngMock.module('kibana')); - - beforeEach( - ngMock.inject(function ($injector) { - $compile = $injector.get('$compile'); - scope = $injector.get('$rootScope').$new(); - }) - ); - - describe('attributes', function () { - describe('suggestions', function () { - let element = null; - const template = ``; - - beforeEach(function () { - element = $compile(template)(scope); - scope.$apply(() => { - scope.list = [{ name: 'suggestion1' }, { name: 'suggestion2' }, { name: 'suggestion3' }]; - }); - }); - - it('are rendered', function () { - expect(element.find('[data-test-subj="timelionSuggestionListItem"]').length).to.be( - scope.list.length - ); - }); - }); - }); -}); diff --git a/src/plugins/vis_default_editor/public/components/controls/filters.tsx b/src/plugins/vis_default_editor/public/components/controls/filters.tsx index 04d0df27927fa..fc676e25ff6d7 100644 --- a/src/plugins/vis_default_editor/public/components/controls/filters.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/filters.tsx @@ -23,7 +23,7 @@ import { htmlIdGenerator, EuiButton, EuiSpacer } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { useMount } from 'react-use'; -import { Query, UI_SETTINGS } from '../../../../data/public'; +import { Query } from '../../../../data/public'; import { useKibana } from '../../../../kibana_react/public'; import { FilterRow } from './filter'; import { AggParamEditorProps } from '../agg_param_props'; @@ -70,7 +70,7 @@ function FiltersParamEditor({ agg, value = [], setValue }: AggParamEditorProps { application.navigateToApp('discover', { - path: `#/${savedSearch.id}`, + path: `#/view/${savedSearch.id}`, }); }, [application, savedSearch.id]); @@ -128,7 +128,12 @@ export function LinkedSearch({ savedSearch, eventEmitter }: LinkedSearchProps) {

- +

"`; -exports[`VegaVisualizations VegaVisualization - basics should show vegalite graph and update on resize (may fail in dev env) 1`] = `"
"`; +exports[`VegaVisualizations VegaVisualization - basics should show vegalite graph and update on resize (may fail in dev env) 1`] = `"
"`; -exports[`VegaVisualizations VegaVisualization - basics should show vegalite graph and update on resize (may fail in dev env) 2`] = `"
"`; +exports[`VegaVisualizations VegaVisualization - basics should show vegalite graph and update on resize (may fail in dev env) 2`] = `"
"`; diff --git a/src/plugins/vis_type_vega/public/vega_view/vega_base_view.js b/src/plugins/vis_type_vega/public/vega_view/vega_base_view.js index 8f88d5c5b2056..4596b47364494 100644 --- a/src/plugins/vis_type_vega/public/vega_view/vega_base_view.js +++ b/src/plugins/vis_type_vega/public/vega_view/vega_base_view.js @@ -195,13 +195,9 @@ export class VegaBaseView { const width = Math.max(0, this._$container.width() - this._parser.paddingWidth); const height = Math.max(0, this._$container.height() - this._parser.paddingHeight) - heightExtraPadding; - // Somehow the `height` signal in vega becomes zero if the height is set exactly to - // an even number. This is a dirty workaround for this. - // when vega itself is updated again, it should be checked whether this is still - // necessary. - const adjustedHeight = height + 0.00000001; - if (view.width() !== width || view.height() !== adjustedHeight) { - view.width(width).height(adjustedHeight); + + if (view.width() !== width || view.height() !== height) { + view.width(width).height(height); return true; } return false; 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 108b34b36c66f..3e318fa22c195 100644 --- a/src/plugins/vis_type_vega/public/vega_visualization.test.js +++ b/src/plugins/vis_type_vega/public/vega_visualization.test.js @@ -53,7 +53,7 @@ jest.mock('./lib/vega', () => ({ })); // FLAKY: https://github.com/elastic/kibana/issues/71713 -describe.skip('VegaVisualizations', () => { +describe('VegaVisualizations', () => { let domNode; let VegaVisualization; let vis; @@ -77,17 +77,17 @@ describe.skip('VegaVisualizations', () => { mockHeight = jest.spyOn($.prototype, 'height').mockImplementation(() => mockedHeightValue); }; - setKibanaMapFactory((...args) => new KibanaMap(...args)); - setInjectedVars({ - emsTileLayerId: {}, - enableExternalUrls: true, - esShardTimeout: 10000, - }); - setData(dataPluginStart); - setSavedObjects(coreStart.savedObjects); - setNotifications(coreStart.notifications); - beforeEach(() => { + setKibanaMapFactory((...args) => new KibanaMap(...args)); + setInjectedVars({ + emsTileLayerId: {}, + enableExternalUrls: true, + esShardTimeout: 10000, + }); + setData(dataPluginStart); + setSavedObjects(coreStart.savedObjects); + setNotifications(coreStart.notifications); + vegaVisualizationDependencies = { core: coreMock.createSetup(), plugins: { @@ -185,49 +185,5 @@ describe.skip('VegaVisualizations', () => { vegaVis.destroy(); } }); - - test('should add a small subpixel value to the height of the canvas to avoid getting it set to 0', async () => { - let vegaVis; - try { - vegaVis = new VegaVisualization(domNode, vis); - const vegaParser = new VegaParser( - `{ - "$schema": "https://vega.github.io/schema/vega/v5.json", - "marks": [ - { - "type": "text", - "encode": { - "update": { - "text": { - "value": "Test" - }, - "align": {"value": "center"}, - "baseline": {"value": "middle"}, - "xc": {"signal": "width/2"}, - "yc": {"signal": "height/2"} - fontSize: {value: "14"} - } - } - } - ] - }`, - new SearchAPI({ - search: dataPluginStart.search, - uiSettings: coreStart.uiSettings, - injectedMetadata: coreStart.injectedMetadata, - }) - ); - await vegaParser.parseAsync(); - - mockedWidthValue = 256; - mockedHeightValue = 256; - - await vegaVis.render(vegaParser); - const vegaView = vegaVis._vegaView._view; - expect(vegaView.height()).toBe(250.00000001); - } finally { - vegaVis.destroy(); - } - }); }); }); diff --git a/src/plugins/vis_type_vislib/public/components/options/metrics_axes/__snapshots__/value_axis_options.test.tsx.snap b/src/plugins/vis_type_vislib/public/components/options/metrics_axes/__snapshots__/value_axis_options.test.tsx.snap index b89d193c7c751..36f5480e85406 100644 --- a/src/plugins/vis_type_vislib/public/components/options/metrics_axes/__snapshots__/value_axis_options.test.tsx.snap +++ b/src/plugins/vis_type_vislib/public/components/options/metrics_axes/__snapshots__/value_axis_options.test.tsx.snap @@ -102,7 +102,7 @@ exports[`ValueAxisOptions component should init with the default set of props 1` value="" /> diff --git a/src/plugins/visualizations/public/legacy/build_pipeline.ts b/src/plugins/visualizations/public/legacy/build_pipeline.ts index e74a83d91fabf..d3fe814f3b010 100644 --- a/src/plugins/visualizations/public/legacy/build_pipeline.ts +++ b/src/plugins/visualizations/public/legacy/build_pipeline.ts @@ -255,7 +255,7 @@ export const buildPipelineVisFunction: BuildPipelineVisFunction = { input_control_vis: (params) => { return `input_control_vis ${prepareJson('visConfig', params)}`; }, - metrics: (params, schemas, uiState = {}) => { + metrics: ({ title, ...params }, schemas, uiState = {}) => { const paramsJson = prepareJson('params', params); const uiStateJson = prepareJson('uiState', uiState); diff --git a/src/plugins/visualize/public/application/components/visualize_editor.tsx b/src/plugins/visualize/public/application/components/visualize_editor.tsx index c571a5fb078bc..516dcacfe5813 100644 --- a/src/plugins/visualize/public/application/components/visualize_editor.tsx +++ b/src/plugins/visualize/public/application/components/visualize_editor.tsx @@ -89,6 +89,7 @@ export const VisualizeEditor = () => { isEmbeddableRendered={isEmbeddableRendered} hasUnappliedChanges={hasUnappliedChanges} originatingApp={originatingApp} + setOriginatingApp={setOriginatingApp} savedVisInstance={savedVisInstance} stateContainer={appState} visualizationIdFromUrl={visualizationIdFromUrl} diff --git a/src/plugins/visualize/public/application/components/visualize_top_nav.tsx b/src/plugins/visualize/public/application/components/visualize_top_nav.tsx index 2e7dba46487ad..f2cb2d49f59b0 100644 --- a/src/plugins/visualize/public/application/components/visualize_top_nav.tsx +++ b/src/plugins/visualize/public/application/components/visualize_top_nav.tsx @@ -18,10 +18,8 @@ */ import React, { memo, useCallback, useMemo, useState, useEffect } from 'react'; -import { isEqual } from 'lodash'; import { OverlayRef } from 'kibana/public'; -import { Query } from 'src/plugins/data/public'; import { useKibana } from '../../../../kibana_react/public'; import { VisualizeServices, @@ -40,6 +38,7 @@ interface VisualizeTopNavProps { setHasUnsavedChanges: (value: boolean) => void; hasUnappliedChanges: boolean; originatingApp?: string; + setOriginatingApp?: (originatingApp: string | undefined) => void; savedVisInstance: SavedVisInstance; stateContainer: VisualizeAppStateContainer; visualizationIdFromUrl?: string; @@ -53,6 +52,7 @@ const TopNav = ({ setHasUnsavedChanges, hasUnappliedChanges, originatingApp, + setOriginatingApp, savedVisInstance, stateContainer, visualizationIdFromUrl, @@ -66,15 +66,13 @@ const TopNav = ({ setInspectorSession(session); }, [embeddableHandler]); - const updateQuery = useCallback( - ({ query }: { query?: Query }) => { - if (!isEqual(currentAppState.query, query)) { - stateContainer.transitions.set('query', query || currentAppState.query); - } else { + const handleRefresh = useCallback( + (_payload: any, isUpdate?: boolean) => { + if (isUpdate === false) { savedVisInstance.embeddableHandler.reload(); } }, - [currentAppState.query, savedVisInstance.embeddableHandler, stateContainer.transitions] + [savedVisInstance.embeddableHandler] ); const config = useMemo(() => { @@ -86,6 +84,7 @@ const TopNav = ({ hasUnappliedChanges, openInspector, originatingApp, + setOriginatingApp, savedVisInstance, stateContainer, visualizationIdFromUrl, @@ -100,6 +99,7 @@ const TopNav = ({ hasUnappliedChanges, openInspector, originatingApp, + setOriginatingApp, savedVisInstance, stateContainer, visualizationIdFromUrl, @@ -145,8 +145,7 @@ const TopNav = ({ void; openInspector: () => void; originatingApp?: string; + setOriginatingApp?: (originatingApp: string | undefined) => void; hasUnappliedChanges: boolean; savedVisInstance: SavedVisInstance; stateContainer: VisualizeAppStateContainer; @@ -51,6 +52,7 @@ export const getTopNavConfig = ( setHasUnsavedChanges, openInspector, originatingApp, + setOriginatingApp, hasUnappliedChanges, savedVisInstance: { embeddableHandler, savedVis, vis }, stateContainer, @@ -112,6 +114,9 @@ export const getTopNavConfig = ( application.navigateToApp(originatingApp); } } else { + if (setOriginatingApp && originatingApp && savedVis.copyOnSave) { + setOriginatingApp(undefined); + } chrome.docTitle.change(savedVis.lastSavedTitle); chrome.setBreadcrumbs(getEditBreadcrumbs(savedVis.lastSavedTitle)); diff --git a/src/plugins/visualize/public/application/utils/use/use_editor_updates.test.ts b/src/plugins/visualize/public/application/utils/use/use_editor_updates.test.ts index 3546ee7b321bb..23894368d606c 100644 --- a/src/plugins/visualize/public/application/utils/use/use_editor_updates.test.ts +++ b/src/plugins/visualize/public/application/utils/use/use_editor_updates.test.ts @@ -105,10 +105,16 @@ describe('useEditorUpdates', () => { to: 'now', }; mockFilters = ['mockFilters']; + const mockQuery = { + query: '', + language: 'kuery', + }; // @ts-expect-error mockServices.data.query.timefilter.timefilter.getTime.mockImplementation(() => timeRange); // @ts-expect-error mockServices.data.query.filterManager.getFilters.mockImplementation(() => mockFilters); + // @ts-expect-error + mockServices.data.query.queryString.getQuery.mockImplementation(() => mockQuery); }); test('should set up current app state and render the editor', () => { diff --git a/src/plugins/visualize/public/application/utils/use/use_editor_updates.ts b/src/plugins/visualize/public/application/utils/use/use_editor_updates.ts index 360e7560b1932..0f4b2d34e8e87 100644 --- a/src/plugins/visualize/public/application/utils/use/use_editor_updates.ts +++ b/src/plugins/visualize/public/application/utils/use/use_editor_updates.ts @@ -20,9 +20,7 @@ import { useEffect, useState } from 'react'; import { isEqual } from 'lodash'; import { EventEmitter } from 'events'; -import { merge } from 'rxjs'; -import { migrateLegacyQuery } from '../../../../../kibana_legacy/public'; import { VisualizeServices, VisualizeAppState, @@ -47,6 +45,8 @@ export const useEditorUpdates = ( const { timefilter: { timefilter }, filterManager, + queryString, + state$, } = services.data.query; const { embeddableHandler, savedVis, savedSearch, vis } = savedVisInstance; const initialState = appState.getState(); @@ -60,7 +60,7 @@ export const useEditorUpdates = ( uiState: vis.uiState, timeRange: timefilter.getTime(), filters: filterManager.getFilters(), - query: appState.getState().query, + query: queryString.getQuery(), linked: !!vis.data.savedSearchId, savedSearch, }); @@ -68,17 +68,12 @@ export const useEditorUpdates = ( embeddableHandler.updateInput({ timeRange: timefilter.getTime(), filters: filterManager.getFilters(), - query: appState.getState().query, + query: queryString.getQuery(), }); } }; - const subscriptions = merge( - timefilter.getTimeUpdate$(), - timefilter.getAutoRefreshFetch$(), - timefilter.getFetch$(), - filterManager.getFetches$() - ).subscribe({ + const subscriptions = state$.subscribe({ next: reloadVisualization, error: services.fatalErrors.add, }); @@ -116,10 +111,6 @@ export const useEditorUpdates = ( // and initializing different visualizations return; } - const newQuery = migrateLegacyQuery(state.query); - if (!isEqual(state.query, newQuery)) { - appState.transitions.set('query', newQuery); - } if (!isEqual(state.uiState, vis.uiState.getChanges())) { vis.uiState.set(state.uiState); diff --git a/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.test.ts b/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.test.ts index e885067c58184..8bde9a049c492 100644 --- a/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.test.ts +++ b/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.test.ts @@ -96,6 +96,7 @@ describe('useVisualizeAppState', () => { ); expect(connectToQueryState).toHaveBeenCalledWith(mockServices.data.query, expect.any(Object), { filters: 'appState', + query: true, }); expect(result.current).toEqual({ appState: stateContainer, diff --git a/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.tsx b/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.tsx index e4d891472fbfd..c44f67df3729f 100644 --- a/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.tsx +++ b/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.tsx @@ -24,6 +24,7 @@ import { EventEmitter } from 'events'; import { i18n } from '@kbn/i18n'; import { MarkdownSimple, toMountPoint } from '../../../../../kibana_react/public'; +import { migrateLegacyQuery } from '../../../../../kibana_legacy/public'; import { esFilters, connectToQueryState } from '../../../../../data/public'; import { VisualizeServices, VisualizeAppStateContainer, SavedVisInstance } from '../../types'; import { visStateToEditorState } from '../utils'; @@ -61,19 +62,35 @@ export const useVisualizeAppState = ( eventEmitter.on('dirtyStateChange', onDirtyStateChange); - const { filterManager } = services.data.query; - // sync initial app filters from state to filterManager + const { filterManager, queryString } = services.data.query; + // sync initial app state from state to managers filterManager.setAppFilters(cloneDeep(stateContainer.getState().filters)); - // setup syncing of app filters between appState and filterManager + queryString.setQuery(migrateLegacyQuery(stateContainer.getState().query)); + + // setup syncing of app filters between appState and query services const stopSyncingAppFilters = connectToQueryState( services.data.query, { - set: ({ filters }) => stateContainer.transitions.set('filters', filters), - get: () => ({ filters: stateContainer.getState().filters }), - state$: stateContainer.state$.pipe(map((state) => ({ filters: state.filters }))), + set: ({ filters, query }) => { + stateContainer.transitions.set('filters', filters); + stateContainer.transitions.set('query', query); + }, + get: () => { + return { + filters: stateContainer.getState().filters, + query: stateContainer.getState().query, + }; + }, + state$: stateContainer.state$.pipe( + map((state) => ({ + filters: state.filters, + query: state.query, + })) + ), }, { filters: esFilters.FilterStateStore.APP_STATE, + query: true, } ); diff --git a/src/plugins/visualize/public/application/utils/utils.ts b/src/plugins/visualize/public/application/utils/utils.ts index 9f32da3f785b5..532d87985a0b6 100644 --- a/src/plugins/visualize/public/application/utils/utils.ts +++ b/src/plugins/visualize/public/application/utils/utils.ts @@ -20,7 +20,7 @@ import { i18n } from '@kbn/i18n'; import { ChromeStart, DocLinksStart } from 'kibana/public'; -import { Filter, UI_SETTINGS } from '../../../../data/public'; +import { Filter } from '../../../../data/public'; import { VisualizeServices, SavedVisInstance } from '../types'; export const addHelpMenuToAppChrome = (chrome: ChromeStart, docLinks: DocLinksStart) => { @@ -49,12 +49,9 @@ export const addBadgeToAppChrome = (chrome: ChromeStart) => { }); }; -export const getDefaultQuery = ({ localStorage, uiSettings }: VisualizeServices) => ({ - query: '', - language: - localStorage.get('kibana.userQueryLanguage') || - uiSettings.get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE), -}); +export const getDefaultQuery = ({ data }: VisualizeServices) => { + return data.query.queryString.getDefaultQuery(); +}; export const visStateToEditorState = ( { vis, savedVis }: SavedVisInstance, diff --git a/tasks/config/karma.js b/tasks/config/karma.js deleted file mode 100644 index 114e09876406c..0000000000000 --- a/tasks/config/karma.js +++ /dev/null @@ -1,207 +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 { dirname } from 'path'; -import { times } from 'lodash'; -import { makeJunitReportPath } from '@kbn/test'; -import * as UiSharedDeps from '@kbn/ui-shared-deps'; - -const TOTAL_CI_SHARDS = 4; -const ROOT = dirname(require.resolve('../../package.json')); -const buildHash = String(Number.MAX_SAFE_INTEGER); - -module.exports = function (grunt) { - function pickBrowser() { - if (grunt.option('browser')) { - return grunt.option('browser'); - } - if (process.env.TEST_BROWSER_HEADLESS === '1') { - return 'Chrome_Headless'; - } - return 'Chrome'; - } - - function pickReporters() { - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - if (process.env.CI && process.env.DISABLE_JUNIT_REPORTER) { - return ['dots']; - } - - if (process.env.CI) { - return ['dots', 'junit']; - } - - return ['progress']; - } - - function getKarmaFiles(shardNum) { - return [ - 'http://localhost:5610/test_bundle/built_css.css', - // Sets global variables normally set by the bootstrap.js script - 'http://localhost:5610/test_bundle/karma/globals.js', - - ...UiSharedDeps.jsDepFilenames.map( - (chunkFilename) => - `http://localhost:5610/${buildHash}/bundles/kbn-ui-shared-deps/${chunkFilename}` - ), - `http://localhost:5610/${buildHash}/bundles/kbn-ui-shared-deps/${UiSharedDeps.jsFilename}`, - - shardNum === undefined - ? `http://localhost:5610/${buildHash}/bundles/tests.bundle.js` - : `http://localhost:5610/${buildHash}/bundles/tests.bundle.js?shards=${TOTAL_CI_SHARDS}&shard_num=${shardNum}`, - - `http://localhost:5610/${buildHash}/bundles/kbn-ui-shared-deps/${UiSharedDeps.baseCssDistFilename}`, - // this causes tilemap tests to fail, probably because the eui styles haven't been - // included in the karma harness a long some time, if ever - // `http://localhost:5610/bundles/kbn-ui-shared-deps/${UiSharedDeps.lightCssDistFilename}`, - `http://localhost:5610/${buildHash}/bundles/tests.style.css`, - ]; - } - - const config = { - options: { - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: '', - - captureTimeout: 30000, - browserNoActivityTimeout: 120000, - frameworks: ['mocha'], - plugins: [ - 'karma-chrome-launcher', - 'karma-coverage', - 'karma-firefox-launcher', - 'karma-ie-launcher', - 'karma-junit-reporter', - 'karma-mocha', - 'karma-safari-launcher', - ], - port: 9876, - colors: true, - logLevel: grunt.option('debug') || grunt.option('verbose') ? 'DEBUG' : 'INFO', - autoWatch: false, - browsers: [pickBrowser()], - customLaunchers: { - Chrome_Headless: { - base: 'Chrome', - flags: ['--headless', '--disable-gpu', '--remote-debugging-port=9222'], - }, - }, - - reporters: pickReporters(), - - junitReporter: { - outputFile: makeJunitReportPath(ROOT, 'karma'), - useBrowserName: false, - nameFormatter: (_, result) => [...result.suite, result.description].join(' '), - classNameFormatter: (_, result) => { - const rootSuite = result.suite[0] || result.description; - return `Browser Unit Tests.${rootSuite.replace(/\./g, '·')}`; - }, - }, - - // list of files / patterns to load in the browser - files: getKarmaFiles(), - - proxies: { - '/tests/': 'http://localhost:5610/tests/', - '/test_bundle/': 'http://localhost:5610/test_bundle/', - [`/${buildHash}/bundles/`]: `http://localhost:5610/${buildHash}/bundles/`, - }, - - client: { - mocha: { - reporter: 'html', // change Karma's debug.html to the mocha web reporter - timeout: 10000, - slow: 5000, - }, - }, - }, - - dev: { singleRun: false }, - unit: { singleRun: true }, - coverage: { - singleRun: true, - reporters: ['coverage'], - coverageReporter: { - reporters: [{ type: 'html', dir: 'coverage' }, { type: 'text-summary' }], - }, - }, - }; - - /** - * ------------------------------------------------------------ - * CI sharding - * ------------------------------------------------------------ - * - * Every test retains nearly all of the memory it causes to be allocated, - * which has started to kill the test browser as the size of the test suite - * increases. This is a deep-rooted problem that will take some serious - * work to fix. - * - * CI sharding is a short-term solution that splits the top-level describe - * calls into different "shards" and instructs karma to only run one shard - * at a time, reloading the browser in between each shard and forcing the - * memory from the previous shard to be released. - * - * ## how - * - * Rather than modify the bundling process to produce multiple testing - * bundles, top-level describe calls are sharded by their first argument, - * the suite name. - * - * The number of shards to create is controlled with the TOTAL_CI_SHARDS - * constant defined at the top of this file. - * - * ## controlling sharding - * - * To control sharding in a specific karma configuration, the total number - * of shards to create (?shards=X), and the current shard number - * (&shard_num=Y), are added to the testing bundle url and read by the - * test_harness/setup_test_sharding[1] module. This allows us to use a - * different number of shards in different scenarios (ie. running - * `yarn test:karma` runs the tests in a single shard, effectively - * disabling sharding) - * - * These same parameters can also be defined in the URL/query string of the - * karma debug page (started when you run `yarn test:karma:debug`). - * - * ## debugging - * - * It is *possible* that some tests will only pass if run after/with certain - * other suites. To debug this, make sure that your tests pass in isolation - * (by clicking the suite name on the karma debug page) and that it runs - * correctly in it's given shard (using the `?shards=X&shard_num=Y` query - * string params on the karma debug page). You can spot the shard number - * a test is running in by searching for the "ready to load tests for shard X" - * log message. - * - * [1]: src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js - */ - times(TOTAL_CI_SHARDS, (i) => { - const n = i + 1; - config[`ciShard-${n}`] = { - singleRun: true, - options: { - files: getKarmaFiles(n), - }, - }; - }); - - return config; -}; diff --git a/tasks/config/run.js b/tasks/config/run.js index 98a1226834bc6..9ac8f72d56d4a 100644 --- a/tasks/config/run.js +++ b/tasks/config/run.js @@ -17,7 +17,6 @@ * under the License. */ -import { resolve } from 'path'; import { getFunctionalTestGroupRunConfigs } from '../function_test_groups'; const { version } = require('../../package.json'); @@ -25,44 +24,7 @@ const KIBANA_INSTALL_DIR = process.env.KIBANA_INSTALL_DIR || `./build/oss/kibana-${version}-SNAPSHOT-${process.platform}-x86_64`; -module.exports = function (grunt) { - function createKbnServerTask({ runBuild, flags = [] }) { - return { - options: { - wait: false, - ready: /http server running/, - quiet: false, - failOnError: false, - }, - cmd: runBuild ? `./build/${runBuild}/bin/kibana` : process.execPath, - args: [ - ...(runBuild ? [] : [require.resolve('../../scripts/kibana'), '--oss']), - - '--logging.json=false', - - ...flags, - - // allow the user to override/inject flags by defining cli args starting with `--kbnServer.` - ...grunt.option.flags().reduce(function (flags, flag) { - if (flag.startsWith('--kbnServer.')) { - flags.push(`--${flag.slice(12)}`); - } - - return flags; - }, []), - ], - }; - } - - const karmaTestServerFlags = [ - '--env.name=development', - '--plugins.initialize=false', - '--optimize.bundleFilter=tests', - '--optimize.validateSyntaxOfNodeModules=false', - '--server.port=5610', - '--migrations.skip=true', - ]; - +module.exports = function () { const NODE = 'node'; const YARN = 'yarn'; const scriptWithGithubChecks = ({ title, options, cmd, args }) => @@ -177,37 +139,6 @@ module.exports = function (grunt) { ], }), - // used by the test:karma task - // runs the kibana server to serve the browser test bundle - karmaTestServer: createKbnServerTask({ - flags: [...karmaTestServerFlags], - }), - browserSCSS: createKbnServerTask({ - flags: [...karmaTestServerFlags, '--optimize', '--optimize.enabled=false'], - }), - - // used by the test:coverage task - // runs the kibana server to serve the instrumented version of the browser test bundle - karmaTestCoverageServer: createKbnServerTask({ - flags: [...karmaTestServerFlags, '--tests_bundle.instrument=true'], - }), - - // used by the test:karma:debug task - // runs the kibana server to serve the browser test bundle, but listens for changes - // to the public/browser code and rebuilds the test bundle on changes - karmaTestDebugServer: createKbnServerTask({ - flags: [ - ...karmaTestServerFlags, - '--dev', - '--no-dev-config', - '--no-watch', - '--no-base-path', - '--optimize.watchPort=5611', - '--optimize.watchPrebuild=true', - '--optimize.bundleDir=' + resolve(__dirname, '../../data/optimize/testdev'), - ], - }), - verifyNotice: scriptWithGithubChecks({ title: 'Verify NOTICE.txt', options: { @@ -325,7 +256,6 @@ module.exports = function (grunt) { 'test:jest_integration' ), test_projects: gruntTaskWithGithubChecks('Project tests', 'test:projects'), - test_karma_ci: gruntTaskWithGithubChecks('Browser tests', 'test:karma-ci'), ...getFunctionalTestGroupRunConfigs({ kibanaInstallDir: KIBANA_INSTALL_DIR, diff --git a/tasks/jenkins.js b/tasks/jenkins.js index eece5df61a7d1..adfb6f0f46868 100644 --- a/tasks/jenkins.js +++ b/tasks/jenkins.js @@ -37,7 +37,6 @@ module.exports = function (grunt) { 'run:test_jest', 'run:test_jest_integration', 'run:test_projects', - 'run:test_karma_ci', 'run:test_hardening', 'run:test_package_safer_lodash_set', 'run:apiIntegrationTests', diff --git a/tasks/test.js b/tasks/test.js index 09821b97fe2e8..f370ea0b948c6 100644 --- a/tasks/test.js +++ b/tasks/test.js @@ -17,8 +17,6 @@ * under the License. */ -import _, { keys } from 'lodash'; - import { run } from '../utilities/visual_regression'; module.exports = function (grunt) { @@ -31,25 +29,6 @@ module.exports = function (grunt) { } ); - grunt.registerTask('test:karma', [ - 'checkPlugins', - 'run:browserSCSS', - 'run:karmaTestServer', - 'karma:unit', - ]); - - grunt.registerTask('test:karma-ci', () => { - const ciShardTasks = keys(grunt.config.get('karma')) - .filter((key) => key.startsWith('ciShard-')) - .map((key) => `karma:${key}`); - - grunt.log.ok(`Running UI tests in ${ciShardTasks.length} shards`); - grunt.task.run(['run:browserSCSS']); - grunt.task.run(['run:karmaTestServer', ...ciShardTasks]); - }); - - grunt.registerTask('test:coverage', ['run:karmaTestCoverageServer', 'karma:coverage']); - grunt.registerTask('test:quick', [ 'checkPlugins', 'run:mocha', @@ -57,18 +36,16 @@ module.exports = function (grunt) { 'test:jest', 'test:jest_integration', 'test:projects', - 'test:karma', 'run:apiIntegrationTests', ]); - grunt.registerTask('test:karmaDebug', ['checkPlugins', 'run:karmaTestDebugServer', 'karma:dev']); grunt.registerTask('test:mochaCoverage', ['run:mochaCoverage']); grunt.registerTask('test', (subTask) => { if (subTask) grunt.fail.fatal(`invalid task "test:${subTask}"`); grunt.task.run( - _.compact([ + [ !grunt.option('quick') && 'run:eslint', !grunt.option('quick') && 'run:sasslint', !grunt.option('quick') && 'run:checkTsProjects', @@ -78,7 +55,7 @@ module.exports = function (grunt) { 'run:checkFileCasing', 'run:licenses', 'test:quick', - ]) + ].filter(Boolean) ); }); diff --git a/test/api_integration/apis/saved_objects/migrations.js b/test/api_integration/apis/saved_objects/migrations.ts similarity index 68% rename from test/api_integration/apis/saved_objects/migrations.js rename to test/api_integration/apis/saved_objects/migrations.ts index ed259ccec0114..9997d9710e212 100644 --- a/test/api_integration/apis/saved_objects/migrations.js +++ b/test/api_integration/apis/saved_objects/migrations.ts @@ -23,22 +23,39 @@ import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; -import { assert } from 'chai'; +import expect from '@kbn/expect'; +import { ElasticsearchClient, SavedObjectMigrationMap, SavedObjectsType } from 'src/core/server'; +import { SearchResponse } from '../../../../src/core/server/elasticsearch/client'; import { DocumentMigrator, IndexMigrator, + createMigrationEsClient, } from '../../../../src/core/server/saved_objects/migrations/core'; +import { SavedObjectsTypeMappingDefinitions } from '../../../../src/core/server/saved_objects/mappings'; + import { SavedObjectsSerializer, SavedObjectTypeRegistry, } from '../../../../src/core/server/saved_objects'; - -export default ({ getService }) => { - const es = getService('legacyEs'); - const callCluster = (path, ...args) => _.get(es, path).call(es, ...args); +import { FtrProviderContext } from '../../ftr_provider_context'; + +function getLogMock() { + return { + debug() {}, + error() {}, + fatal() {}, + info() {}, + log() {}, + trace() {}, + warn() {}, + get: getLogMock, + }; +} +export default ({ getService }: FtrProviderContext) => { + const esClient = getService('es'); describe('Kibana index migration', () => { - before(() => callCluster('indices.delete', { index: '.migrate-*' })); + before(() => esClient.indices.delete({ index: '.migrate-*' })); it('Migrates an existing index that has never been migrated before', async () => { const index = '.migration-a'; @@ -55,7 +72,7 @@ export default ({ getService }) => { bar: { properties: { mynum: { type: 'integer' } } }, }; - const migrations = { + const migrations: Record = { foo: { '1.0.0': (doc) => set(doc, 'attributes.name', doc.attributes.name.toUpperCase()), }, @@ -66,11 +83,11 @@ export default ({ getService }) => { }, }; - await createIndex({ callCluster, index }); - await createDocs({ callCluster, index, docs: originalDocs }); + await createIndex({ esClient, index }); + await createDocs({ esClient, index, docs: originalDocs }); // Test that unrelated index templates are unaffected - await callCluster('indices.putTemplate', { + await esClient.indices.putTemplate({ name: 'migration_test_a_template', body: { index_patterns: 'migration_test_a', @@ -82,7 +99,7 @@ export default ({ getService }) => { }); // Test that obsolete index templates get removed - await callCluster('indices.putTemplate', { + await esClient.indices.putTemplate({ name: 'migration_a_template', body: { index_patterns: index, @@ -93,29 +110,37 @@ export default ({ getService }) => { }, }); - assert.isTrue(await callCluster('indices.existsTemplate', { name: 'migration_a_template' })); + const migrationATemplate = await esClient.indices.existsTemplate({ + name: 'migration_a_template', + }); + expect(migrationATemplate.body).to.be.ok(); const result = await migrateIndex({ - callCluster, + esClient, index, migrations, mappingProperties, obsoleteIndexTemplatePattern: 'migration_a*', }); - assert.isFalse(await callCluster('indices.existsTemplate', { name: 'migration_a_template' })); - assert.isTrue( - await callCluster('indices.existsTemplate', { name: 'migration_test_a_template' }) - ); + const migrationATemplateAfter = await esClient.indices.existsTemplate({ + name: 'migration_a_template', + }); - assert.deepEqual(_.omit(result, 'elapsedMs'), { + expect(migrationATemplateAfter.body).not.to.be.ok(); + const migrationTestATemplateAfter = await esClient.indices.existsTemplate({ + name: 'migration_test_a_template', + }); + + expect(migrationTestATemplateAfter.body).to.be.ok(); + expect(_.omit(result, 'elapsedMs')).to.eql({ destIndex: '.migration-a_2', sourceIndex: '.migration-a_1', status: 'migrated', }); // The docs in the original index are unchanged - assert.deepEqual(await fetchDocs({ callCluster, index: `${index}_1` }), [ + expect(await fetchDocs(esClient, `${index}_1`)).to.eql([ { id: 'bar:i', type: 'bar', bar: { nomnom: 33 } }, { id: 'bar:o', type: 'bar', bar: { nomnom: 2 } }, { id: 'baz:u', type: 'baz', baz: { title: 'Terrific!' } }, @@ -124,7 +149,7 @@ export default ({ getService }) => { ]); // The docs in the alias have been migrated - assert.deepEqual(await fetchDocs({ callCluster, index }), [ + expect(await fetchDocs(esClient, index)).to.eql([ { id: 'bar:i', type: 'bar', @@ -171,7 +196,7 @@ export default ({ getService }) => { bar: { properties: { mynum: { type: 'integer' } } }, }; - const migrations = { + const migrations: Record = { foo: { '1.0.0': (doc) => set(doc, 'attributes.name', doc.attributes.name.toUpperCase()), }, @@ -182,19 +207,20 @@ export default ({ getService }) => { }, }; - await createIndex({ callCluster, index }); - await createDocs({ callCluster, index, docs: originalDocs }); + await createIndex({ esClient, index }); + await createDocs({ esClient, index, docs: originalDocs }); - await migrateIndex({ callCluster, index, migrations, mappingProperties }); + await migrateIndex({ esClient, index, migrations, mappingProperties }); + // @ts-expect-error name doesn't exist on mynum type mappingProperties.bar.properties.name = { type: 'keyword' }; migrations.foo['2.0.1'] = (doc) => set(doc, 'attributes.name', `${doc.attributes.name}v2`); migrations.bar['2.3.4'] = (doc) => set(doc, 'attributes.name', `NAME ${doc.id}`); - await migrateIndex({ callCluster, index, migrations, mappingProperties }); + await migrateIndex({ esClient, index, migrations, mappingProperties }); // The index for the initial migration has not been destroyed... - assert.deepEqual(await fetchDocs({ callCluster, index: `${index}_2` }), [ + expect(await fetchDocs(esClient, `${index}_2`)).to.eql([ { id: 'bar:i', type: 'bar', @@ -226,7 +252,7 @@ export default ({ getService }) => { ]); // The docs were migrated again... - assert.deepEqual(await fetchDocs({ callCluster, index }), [ + expect(await fetchDocs(esClient, index)).to.eql([ { id: 'bar:i', type: 'bar', @@ -266,48 +292,43 @@ export default ({ getService }) => { foo: { properties: { name: { type: 'text' } } }, }; - const migrations = { + const migrations: Record = { foo: { '1.0.0': (doc) => set(doc, 'attributes.name', 'LOTR'), }, }; - await createIndex({ callCluster, index }); - await createDocs({ callCluster, index, docs: originalDocs }); + await createIndex({ esClient, index }); + await createDocs({ esClient, index, docs: originalDocs }); const result = await Promise.all([ - migrateIndex({ callCluster, index, migrations, mappingProperties }), - migrateIndex({ callCluster, index, migrations, mappingProperties }), + migrateIndex({ esClient, index, migrations, mappingProperties }), + migrateIndex({ esClient, index, migrations, mappingProperties }), ]); // The polling instance and the migrating instance should both - // return a similar migraiton result. - assert.deepEqual( + // return a similar migration result. + expect( result + // @ts-expect-error destIndex exists only on MigrationResult status: 'migrated'; .map(({ status, destIndex }) => ({ status, destIndex })) - .sort((a) => (a.destIndex ? 0 : 1)), - [ - { status: 'migrated', destIndex: '.migration-c_2' }, - { status: 'skipped', destIndex: undefined }, - ] - ); + .sort((a) => (a.destIndex ? 0 : 1)) + ).to.eql([ + { status: 'migrated', destIndex: '.migration-c_2' }, + { status: 'skipped', destIndex: undefined }, + ]); + const { body } = await esClient.cat.indices({ index: '.migration-c*', format: 'json' }); // It only created the original and the dest - assert.deepEqual( - _.map( - await callCluster('cat.indices', { index: '.migration-c*', format: 'json' }), - 'index' - ).sort(), - ['.migration-c_1', '.migration-c_2'] - ); + expect(_.map(body, 'index').sort()).to.eql(['.migration-c_1', '.migration-c_2']); // The docs in the original index are unchanged - assert.deepEqual(await fetchDocs({ callCluster, index: `${index}_1` }), [ + expect(await fetchDocs(esClient, `${index}_1`)).to.eql([ { id: 'foo:lotr', type: 'foo', foo: { name: 'Lord of the Rings' } }, ]); // The docs in the alias have been migrated - assert.deepEqual(await fetchDocs({ callCluster, index }), [ + expect(await fetchDocs(esClient, index)).to.eql([ { id: 'foo:lotr', type: 'foo', @@ -320,38 +341,53 @@ export default ({ getService }) => { }); }; -async function createIndex({ callCluster, index }) { - await callCluster('indices.delete', { index: `${index}*`, ignore: [404] }); +async function createIndex({ esClient, index }: { esClient: ElasticsearchClient; index: string }) { + await esClient.indices.delete({ index: `${index}*` }, { ignore: [404] }); const properties = { type: { type: 'keyword' }, foo: { properties: { name: { type: 'keyword' } } }, bar: { properties: { nomnom: { type: 'integer' } } }, baz: { properties: { title: { type: 'keyword' } } }, }; - await callCluster('indices.create', { + await esClient.indices.create({ index, body: { mappings: { dynamic: 'strict', properties } }, }); } -async function createDocs({ callCluster, index, docs }) { - await callCluster('bulk', { +async function createDocs({ + esClient, + index, + docs, +}: { + esClient: ElasticsearchClient; + index: string; + docs: any[]; +}) { + await esClient.bulk({ body: docs.reduce((acc, doc) => { acc.push({ index: { _id: doc.id, _index: index } }); acc.push(_.omit(doc, 'id')); return acc; }, []), }); - await callCluster('indices.refresh', { index }); + await esClient.indices.refresh({ index }); } async function migrateIndex({ - callCluster, + esClient, index, migrations, mappingProperties, validateDoc, obsoleteIndexTemplatePattern, +}: { + esClient: ElasticsearchClient; + index: string; + migrations: Record; + mappingProperties: SavedObjectsTypeMappingDefinitions; + validateDoc?: (doc: any) => void; + obsoleteIndexTemplatePattern?: string; }) { const typeRegistry = new SavedObjectTypeRegistry(); const types = migrationsToTypes(migrations); @@ -361,17 +397,17 @@ async function migrateIndex({ kibanaVersion: '99.9.9', typeRegistry, validateDoc: validateDoc || _.noop, - log: { info: _.noop, debug: _.noop, warn: _.noop }, + log: getLogMock(), }); const migrator = new IndexMigrator({ - callCluster, + client: createMigrationEsClient(esClient, getLogMock()), documentMigrator, index, obsoleteIndexTemplatePattern, mappingProperties, batchSize: 10, - log: { info: _.noop, debug: _.noop, warn: _.noop }, + log: getLogMock(), pollInterval: 50, scrollDuration: '5m', serializer: new SavedObjectsSerializer(typeRegistry), @@ -380,21 +416,22 @@ async function migrateIndex({ return await migrator.migrate(); } -function migrationsToTypes(migrations) { - return Object.entries(migrations).map(([type, migrations]) => ({ +function migrationsToTypes( + migrations: Record +): SavedObjectsType[] { + return Object.entries(migrations).map(([type, migrationsMap]) => ({ name: type, hidden: false, namespaceType: 'single', mappings: { properties: {} }, - migrations: { ...migrations }, + migrations: { ...migrationsMap }, })); } -async function fetchDocs({ callCluster, index }) { - const { - hits: { hits }, - } = await callCluster('search', { index }); - return hits +async function fetchDocs(esClient: ElasticsearchClient, index: string) { + const { body } = await esClient.search>({ index }); + + return body.hits.hits .map((h) => ({ ...h._source, id: h._id, diff --git a/test/common/services/elasticsearch.ts b/test/common/services/elasticsearch.ts index 0436dc901292d..a01f9ff3c8da5 100644 --- a/test/common/services/elasticsearch.ts +++ b/test/common/services/elasticsearch.ts @@ -27,11 +27,18 @@ import { FtrProviderContext } from '../ftr_provider_context'; export function ElasticsearchProvider({ getService }: FtrProviderContext) { const config = getService('config'); - return new Client({ - ssl: { - ca: fs.readFileSync(CA_CERT_PATH, 'utf-8'), - }, - nodes: [formatUrl(config.get('servers.elasticsearch'))], - requestTimeout: config.get('timeouts.esRequestTimeout'), - }); + if (process.env.TEST_CLOUD) { + return new Client({ + nodes: [formatUrl(config.get('servers.elasticsearch'))], + requestTimeout: config.get('timeouts.esRequestTimeout'), + }); + } else { + return new Client({ + ssl: { + ca: fs.readFileSync(CA_CERT_PATH, 'utf-8'), + }, + nodes: [formatUrl(config.get('servers.elasticsearch'))], + requestTimeout: config.get('timeouts.esRequestTimeout'), + }); + } } diff --git a/test/common/services/es_archiver.ts b/test/common/services/es_archiver.ts index cfe0610414b4f..9c99445fa4827 100644 --- a/test/common/services/es_archiver.ts +++ b/test/common/services/es_archiver.ts @@ -18,9 +18,9 @@ */ import { format as formatUrl } from 'url'; +import { EsArchiver } from '@kbn/es-archiver'; import { FtrProviderContext } from '../ftr_provider_context'; -import { EsArchiver } from '../../../src/es_archiver'; // @ts-ignore not TS yet import * as KibanaServer from './kibana_server'; diff --git a/test/functional/apps/dashboard/dashboard_filter_bar.js b/test/functional/apps/dashboard/dashboard_filter_bar.js index f3241568bbb3e..273779a42d3f9 100644 --- a/test/functional/apps/dashboard/dashboard_filter_bar.js +++ b/test/functional/apps/dashboard/dashboard_filter_bar.js @@ -30,8 +30,7 @@ export default function ({ getService, getPageObjects }) { const browser = getService('browser'); const PageObjects = getPageObjects(['common', 'dashboard', 'header', 'visualize', 'timePicker']); - // FLAKY: https://github.com/elastic/kibana/issues/71987 - describe.skip('dashboard filter bar', () => { + describe('dashboard filter bar', () => { before(async () => { await esArchiver.load('dashboard/current/kibana'); await kibanaServer.uiSettings.replace({ @@ -69,6 +68,7 @@ export default function ({ getService, getPageObjects }) { it('uses default index pattern on an empty dashboard', async () => { await testSubjects.click('addFilter'); await dashboardExpect.fieldSuggestions(['bytes']); + await filterBar.ensureFieldEditorModalIsClosed(); }); it('shows index pattern of vis when one is added', async () => { @@ -77,6 +77,7 @@ export default function ({ getService, getPageObjects }) { await filterBar.ensureFieldEditorModalIsClosed(); await testSubjects.click('addFilter'); await dashboardExpect.fieldSuggestions(['animal']); + await filterBar.ensureFieldEditorModalIsClosed(); }); it('works when a vis with no index pattern is added', async () => { @@ -171,8 +172,6 @@ export default function ({ getService, getPageObjects }) { }); describe('saved search filtering', function () { - // https://github.com/elastic/kibana/issues/47286#issuecomment-644687577 - this.tags('skipCoverage'); before(async () => { await filterBar.ensureFieldEditorModalIsClosed(); await PageObjects.dashboard.gotoDashboardLandingPage(); diff --git a/test/functional/apps/dashboard/dashboard_filtering.js b/test/functional/apps/dashboard/dashboard_filtering.js index cd80f915775c9..0be4fbbebe7c5 100644 --- a/test/functional/apps/dashboard/dashboard_filtering.js +++ b/test/functional/apps/dashboard/dashboard_filtering.js @@ -183,9 +183,6 @@ export default function ({ getService, getPageObjects }) { }); describe('disabling a filter unfilters the data on', function () { - // Flaky test - // https://github.com/elastic/kibana/issues/41087 - this.tags('skipFirefox'); before(async () => { await filterBar.toggleFilterEnabled('bytes'); await PageObjects.header.waitUntilLoadingHasFinished(); diff --git a/test/functional/apps/dashboard/dashboard_snapshots.js b/test/functional/apps/dashboard/dashboard_snapshots.js index 20bc30c889d65..787e839aa08a5 100644 --- a/test/functional/apps/dashboard/dashboard_snapshots.js +++ b/test/functional/apps/dashboard/dashboard_snapshots.js @@ -28,8 +28,7 @@ export default function ({ getService, getPageObjects, updateBaselines }) { const dashboardPanelActions = getService('dashboardPanelActions'); const dashboardAddPanel = getService('dashboardAddPanel'); - // FLAKY: https://github.com/elastic/kibana/issues/52854 - describe.skip('dashboard snapshots', function describeIndexTests() { + describe('dashboard snapshots', function describeIndexTests() { before(async function () { await esArchiver.load('dashboard/current/kibana'); await kibanaServer.uiSettings.replace({ diff --git a/test/functional/apps/dashboard/edit_embeddable_redirects.js b/test/functional/apps/dashboard/edit_embeddable_redirects.js index a366e34b121d9..6d3d43890a962 100644 --- a/test/functional/apps/dashboard/edit_embeddable_redirects.js +++ b/test/functional/apps/dashboard/edit_embeddable_redirects.js @@ -75,5 +75,17 @@ export default function ({ getService, getPageObjects }) { const titles = await PageObjects.dashboard.getPanelTitles(); expect(titles.indexOf(newTitle)).to.not.be(-1); }); + + it('loses originatingApp connection after save as when redirectToOrigin is false', async () => { + const newTitle = 'wowee, my title just got cooler again'; + await PageObjects.header.waitUntilLoadingHasFinished(); + await dashboardPanelActions.openContextMenu(); + await dashboardPanelActions.clickEdit(); + await PageObjects.visualize.saveVisualizationExpectSuccess(newTitle, { + saveAsNew: true, + redirectToOrigin: false, + }); + await PageObjects.visualize.notLinkedToOriginatingApp(); + }); }); } diff --git a/test/functional/apps/management/_create_index_pattern_wizard.js b/test/functional/apps/management/_create_index_pattern_wizard.js index 160b052e70d30..9760527371408 100644 --- a/test/functional/apps/management/_create_index_pattern_wizard.js +++ b/test/functional/apps/management/_create_index_pattern_wizard.js @@ -25,8 +25,7 @@ export default function ({ getService, getPageObjects }) { const es = getService('legacyEs'); const PageObjects = getPageObjects(['settings', 'common']); - // Flaky: https://github.com/elastic/kibana/issues/71501 - describe.skip('"Create Index Pattern" wizard', function () { + describe('"Create Index Pattern" wizard', function () { before(async function () { // delete .kibana index and then wait for Kibana to re-create it await kibanaServer.uiSettings.replace({}); diff --git a/test/functional/apps/management/_handle_alias.js b/test/functional/apps/management/_handle_alias.js index 902b49eacdc00..67a4445d17aa0 100644 --- a/test/functional/apps/management/_handle_alias.js +++ b/test/functional/apps/management/_handle_alias.js @@ -26,8 +26,7 @@ export default function ({ getService, getPageObjects }) { const security = getService('security'); const PageObjects = getPageObjects(['common', 'home', 'settings', 'discover', 'timePicker']); - // FLAKY: https://github.com/elastic/kibana/issues/59717 - describe.skip('Index patterns on aliases', function () { + describe('Index patterns on aliases', function () { before(async function () { await security.testUser.setRoles(['kibana_admin', 'test_alias_reader']); await esArchiver.loadIfNeeded('alias'); @@ -50,9 +49,8 @@ export default function ({ getService, getPageObjects }) { }); it('should be able to create index pattern without time field', async function () { - await PageObjects.settings.createIndexPattern('alias1', null); - const patternName = await PageObjects.settings.getIndexPageHeading(); - expect(patternName).to.be('alias1*'); + await PageObjects.settings.navigateTo(); + await PageObjects.settings.createIndexPattern('alias1*', null); }); it('should be able to discover and verify no of hits for alias1', async function () { @@ -64,9 +62,8 @@ export default function ({ getService, getPageObjects }) { }); it('should be able to create index pattern with timefield', async function () { - await PageObjects.settings.createIndexPattern('alias2', 'date'); - const patternName = await PageObjects.settings.getIndexPageHeading(); - expect(patternName).to.be('alias2*'); + await PageObjects.settings.navigateTo(); + await PageObjects.settings.createIndexPattern('alias2*', 'date'); }); it('should be able to discover and verify no of hits for alias2', async function () { diff --git a/test/functional/apps/status_page/index.js b/test/functional/apps/status_page/index.ts similarity index 56% rename from test/functional/apps/status_page/index.js rename to test/functional/apps/status_page/index.ts index 34f2df287dd6b..65349aba93b9b 100644 --- a/test/functional/apps/status_page/index.js +++ b/test/functional/apps/status_page/index.ts @@ -18,8 +18,9 @@ */ import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../ftr_provider_context'; -export default function ({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const retry = getService('retry'); const testSubjects = getService('testSubjects'); const PageObjects = getPageObjects(['common']); @@ -31,11 +32,32 @@ export default function ({ getService, getPageObjects }) { await PageObjects.common.navigateToApp('status_page'); }); - it('should show the kibana plugin as ready', async function () { + it('should show the kibana plugin as ready', async () => { await retry.tryForTime(6000, async () => { const text = await testSubjects.getVisibleText('statusBreakdown'); expect(text.indexOf('plugin:kibana')).to.be.above(-1); }); }); + + it('should show the build hash and number', async () => { + const buildNumberText = await testSubjects.getVisibleText('statusBuildNumber'); + expect(buildNumberText).to.contain('BUILD '); + + const hashText = await testSubjects.getVisibleText('statusBuildHash'); + expect(hashText).to.contain('COMMIT '); + }); + + it('should display the server metrics', async () => { + const metrics = await testSubjects.findAll('serverMetric'); + expect(metrics).to.have.length(6); + }); + + it('should display the server status', async () => { + const titleText = await testSubjects.getVisibleText('serverStatusTitle'); + expect(titleText).to.contain('Kibana status is'); + + const serverStatus = await testSubjects.getAttribute('serverStatusTitleBadge', 'aria-label'); + expect(serverStatus).to.be('Green'); + }); }); } diff --git a/test/functional/apps/visualize/_area_chart.js b/test/functional/apps/visualize/_area_chart.js index 41e56986f677b..9ac2160a359da 100644 --- a/test/functional/apps/visualize/_area_chart.js +++ b/test/functional/apps/visualize/_area_chart.js @@ -298,7 +298,7 @@ export default function ({ getService, getPageObjects }) { }); }); - describe.skip('switch between Y axis scale types', () => { + describe('switch between Y axis scale types', () => { before(initAreaChart); const axisId = 'ValueAxis-1'; @@ -308,57 +308,25 @@ export default function ({ getService, getPageObjects }) { await PageObjects.visEditor.selectYAxisScaleType(axisId, 'log'); await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, false); await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - const expectedLabels = [ - '2', - '3', - '5', - '7', - '10', - '20', - '30', - '50', - '70', - '100', - '200', - '300', - '500', - '700', - '1,000', - '2,000', - '3,000', - '5,000', - '7,000', - ]; - expect(labels).to.eql(expectedLabels); + const labels = await PageObjects.visChart.getYAxisLabelsAsNumbers(); + const minLabel = 2; + const maxLabel = 5000; + const numberOfLabels = 10; + expect(labels.length).to.be.greaterThan(numberOfLabels); + expect(labels[0]).to.eql(minLabel); + expect(labels[labels.length - 1]).to.be.greaterThan(maxLabel); }); it('should show filtered ticks on selecting log scale', async () => { await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, true); await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - const expectedLabels = [ - '2', - '3', - '5', - '7', - '10', - '20', - '30', - '50', - '70', - '100', - '200', - '300', - '500', - '700', - '1,000', - '2,000', - '3,000', - '5,000', - '7,000', - ]; - expect(labels).to.eql(expectedLabels); + const labels = await PageObjects.visChart.getYAxisLabelsAsNumbers(); + const minLabel = 2; + const maxLabel = 5000; + const numberOfLabels = 10; + expect(labels.length).to.be.greaterThan(numberOfLabels); + expect(labels[0]).to.eql(minLabel); + expect(labels[labels.length - 1]).to.be.greaterThan(maxLabel); }); it('should show ticks on selecting square root scale', async () => { @@ -595,6 +563,10 @@ export default function ({ getService, getPageObjects }) { it('should display updated scaled label text after time range is changed', async () => { await PageObjects.visEditor.setInterval('Millisecond'); + + // Apply interval + await testSubjects.clickWhenNotDisabled('visualizeEditorRenderButton'); + const isHelperScaledLabelExists = await find.existsByCssSelector( '[data-test-subj="currentlyScaledText"]' ); diff --git a/test/functional/apps/visualize/_gauge_chart.js b/test/functional/apps/visualize/_gauge_chart.js index aa94e596319c2..0f870b1fb545f 100644 --- a/test/functional/apps/visualize/_gauge_chart.js +++ b/test/functional/apps/visualize/_gauge_chart.js @@ -26,7 +26,6 @@ export default function ({ getService, getPageObjects }) { const testSubjects = getService('testSubjects'); const PageObjects = getPageObjects(['visualize', 'visEditor', 'visChart', 'timePicker']); - // FLAKY: https://github.com/elastic/kibana/issues/45089 describe('gauge chart', function indexPatternCreation() { async function initGaugeVis() { log.debug('navigateToApp visualize'); diff --git a/test/functional/apps/visualize/_line_chart.js b/test/functional/apps/visualize/_line_chart.js index a492f3858b524..24e4ef4a7fe25 100644 --- a/test/functional/apps/visualize/_line_chart.js +++ b/test/functional/apps/visualize/_line_chart.js @@ -181,7 +181,7 @@ export default function ({ getService, getPageObjects }) { await PageObjects.visChart.waitForVisualization(); }); - describe.skip('switch between Y axis scale types', () => { + describe('switch between Y axis scale types', () => { before(initLineChart); const axisId = 'ValueAxis-1'; @@ -191,57 +191,25 @@ export default function ({ getService, getPageObjects }) { await PageObjects.visEditor.selectYAxisScaleType(axisId, 'log'); await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, false); await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - const expectedLabels = [ - '2', - '3', - '5', - '7', - '10', - '20', - '30', - '50', - '70', - '100', - '200', - '300', - '500', - '700', - '1,000', - '2,000', - '3,000', - '5,000', - '7,000', - ]; - expect(labels).to.eql(expectedLabels); + const labels = await PageObjects.visChart.getYAxisLabelsAsNumbers(); + const minLabel = 2; + const maxLabel = 5000; + const numberOfLabels = 10; + expect(labels.length).to.be.greaterThan(numberOfLabels); + expect(labels[0]).to.eql(minLabel); + expect(labels[labels.length - 1]).to.be.greaterThan(maxLabel); }); it('should show filtered ticks on selecting log scale', async () => { await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, true); await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - const expectedLabels = [ - '2', - '3', - '5', - '7', - '10', - '20', - '30', - '50', - '70', - '100', - '200', - '300', - '500', - '700', - '1,000', - '2,000', - '3,000', - '5,000', - '7,000', - ]; - expect(labels).to.eql(expectedLabels); + const labels = await PageObjects.visChart.getYAxisLabelsAsNumbers(); + const minLabel = 2; + const maxLabel = 5000; + const numberOfLabels = 10; + expect(labels.length).to.be.greaterThan(numberOfLabels); + expect(labels[0]).to.eql(minLabel); + expect(labels[labels.length - 1]).to.be.greaterThan(maxLabel); }); it('should show ticks on selecting square root scale', async () => { diff --git a/test/functional/apps/visualize/_linked_saved_searches.ts b/test/functional/apps/visualize/_linked_saved_searches.ts index b0edcb68f3efc..e7b2909afa5a1 100644 --- a/test/functional/apps/visualize/_linked_saved_searches.ts +++ b/test/functional/apps/visualize/_linked_saved_searches.ts @@ -21,8 +21,10 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; // eslint-disable-next-line import/no-default-export export default function ({ getService, getPageObjects }: FtrProviderContext) { + const browser = getService('browser'); const filterBar = getService('filterBar'); const retry = getService('retry'); + const testSubjects = getService('testSubjects'); const PageObjects = getPageObjects([ 'common', 'discover', @@ -35,12 +37,14 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { describe('saved search visualizations from visualize app', function describeIndexTests() { describe('linked saved searched', () => { const savedSearchName = 'vis_saved_search'; + let discoverSavedSearchUrlPath: string; before(async () => { await PageObjects.common.navigateToApp('discover'); await filterBar.addFilter('extension.raw', 'is', 'jpg'); await PageObjects.header.waitUntilLoadingHasFinished(); await PageObjects.discover.saveSearch(savedSearchName); + discoverSavedSearchUrlPath = (await browser.getCurrentUrl()).split('?')[0]; }); it('should create a visualization from a saved search', async () => { @@ -54,6 +58,24 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { }); }); + it('should have a valid link to the saved search from the visualization', async () => { + await testSubjects.click('showUnlinkSavedSearchPopover'); + await testSubjects.click('viewSavedSearch'); + await PageObjects.header.waitUntilLoadingHasFinished(); + + await retry.waitFor('wait discover load its breadcrumbs', async () => { + const discoverBreadcrumb = await PageObjects.discover.getCurrentQueryName(); + return discoverBreadcrumb === savedSearchName; + }); + + const discoverURLPath = (await browser.getCurrentUrl()).split('?')[0]; + expect(discoverURLPath).to.equal(discoverSavedSearchUrlPath); + + // go back to visualize + await browser.goBack(); + await PageObjects.header.waitUntilLoadingHasFinished(); + }); + it('should respect the time filter when linked to a saved search', async () => { await PageObjects.timePicker.setAbsoluteRange( 'Sep 19, 2015 @ 06:31:44.000', diff --git a/test/functional/apps/visualize/_tsvb_chart.ts b/test/functional/apps/visualize/_tsvb_chart.ts index 5e8d2ef5653f2..7e1f88650cbba 100644 --- a/test/functional/apps/visualize/_tsvb_chart.ts +++ b/test/functional/apps/visualize/_tsvb_chart.ts @@ -25,11 +25,11 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const log = getService('log'); const inspector = getService('inspector'); + const retry = getService('retry'); const security = getService('security'); const PageObjects = getPageObjects(['visualize', 'visualBuilder', 'timePicker', 'visChart']); - // FLAKY: https://github.com/elastic/kibana/issues/71979 - describe.skip('visual builder', function describeIndexTests() { + describe('visual builder', function describeIndexTests() { this.tags('includeFirefox'); beforeEach(async () => { await security.testUser.setRoles([ @@ -129,9 +129,12 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.visualBuilder.clickPanelOptions('metric'); const fromTime = 'Oct 22, 2018 @ 00:00:00.000'; const toTime = 'Oct 28, 2018 @ 23:59:59.999'; - await PageObjects.timePicker.setAbsoluteRange(fromTime, toTime); - await PageObjects.visualBuilder.setIndexPatternValue('kibana_sample_data_flights'); - await PageObjects.visualBuilder.selectIndexPatternTimeField('timestamp'); + // Sometimes popovers take some time to appear in Firefox (#71979) + await retry.try(async () => { + await PageObjects.timePicker.setAbsoluteRange(fromTime, toTime); + await PageObjects.visualBuilder.setIndexPatternValue('kibana_sample_data_flights'); + await PageObjects.visualBuilder.selectIndexPatternTimeField('timestamp'); + }); const newValue = await PageObjects.visualBuilder.getMetricValue(); expect(newValue).to.eql('10'); }); diff --git a/test/functional/apps/visualize/_tsvb_time_series.ts b/test/functional/apps/visualize/_tsvb_time_series.ts index e0d512c1f4861..c048755fc5fbe 100644 --- a/test/functional/apps/visualize/_tsvb_time_series.ts +++ b/test/functional/apps/visualize/_tsvb_time_series.ts @@ -107,7 +107,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { expect(actualCount).to.be(expectedLegendValue); }); - it.skip('should show the correct count in the legend with "Human readable" duration formatter', async () => { + it('should show the correct count in the legend with "Human readable" duration formatter', async () => { await visualBuilder.clickSeriesOption(); await visualBuilder.changeDataFormatter('Duration'); await visualBuilder.setDurationFormatterSettings({ to: 'Human readable' }); diff --git a/test/functional/apps/visualize/_vega_chart.js b/test/functional/apps/visualize/_vega_chart.ts similarity index 59% rename from test/functional/apps/visualize/_vega_chart.js rename to test/functional/apps/visualize/_vega_chart.ts index c530c6f823133..6c0b77411ae99 100644 --- a/test/functional/apps/visualize/_vega_chart.js +++ b/test/functional/apps/visualize/_vega_chart.ts @@ -18,9 +18,17 @@ */ import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../ftr_provider_context'; -export default function ({ getService, getPageObjects }) { - const PageObjects = getPageObjects(['timePicker', 'visualize', 'visChart', 'vegaChart']); +// eslint-disable-next-line import/no-default-export +export default function ({ getPageObjects, getService }: FtrProviderContext) { + const PageObjects = getPageObjects([ + 'timePicker', + 'visualize', + 'visChart', + 'visEditor', + 'vegaChart', + ]); const filterBar = getService('filterBar'); const log = getService('log'); @@ -30,13 +38,15 @@ export default function ({ getService, getPageObjects }) { await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickVega'); await PageObjects.visualize.clickVega(); + await PageObjects.visChart.waitForVisualizationRenderingStabilized(); }); describe('vega chart', () => { describe('initial render', () => { - it.skip('should have some initial vega spec text', async function () { + it('should have some initial vega spec text', async function () { const vegaSpec = await PageObjects.vegaChart.getSpec(); - expect(vegaSpec).to.contain('{').and.to.contain('data'); + expect(vegaSpec).to.contain('{'); + expect(vegaSpec).to.contain('data'); expect(vegaSpec.length).to.be.above(500); }); @@ -44,7 +54,8 @@ export default function ({ getService, getPageObjects }) { const view = await PageObjects.vegaChart.getViewContainer(); expect(view).to.be.ok(); const size = await view.getSize(); - expect(size).to.have.property('width').and.to.have.property('height'); + expect(size).to.have.property('width'); + expect(size).to.have.property('height'); expect(size.width).to.be.above(0); expect(size.height).to.be.above(0); @@ -63,10 +74,18 @@ export default function ({ getService, getPageObjects }) { await filterBar.removeAllFilters(); }); - it.skip('should render different data in response to filter change', async function () { - await PageObjects.vegaChart.expectVisToMatchScreenshot('vega_chart'); + it('should render different data in response to filter change', async function () { + await PageObjects.vegaChart.typeInSpec('"config": { "kibana": {"renderer": "svg"} },'); + await PageObjects.visEditor.clickGo(); + await PageObjects.visChart.waitForVisualizationRenderingStabilized(); + const fullDataLabels = await PageObjects.vegaChart.getYAxisLabels(); + expect(fullDataLabels[0]).to.eql('0'); + expect(fullDataLabels[fullDataLabels.length - 1]).to.eql('1,600'); await filterBar.addFilter('@tags.raw', 'is', 'error'); - await PageObjects.vegaChart.expectVisToMatchScreenshot('vega_chart_filtered'); + await PageObjects.visChart.waitForVisualizationRenderingStabilized(); + const filteredDataLabels = await PageObjects.vegaChart.getYAxisLabels(); + expect(filteredDataLabels[0]).to.eql('0'); + expect(filteredDataLabels[filteredDataLabels.length - 1]).to.eql('90'); }); }); }); diff --git a/test/functional/apps/visualize/_vertical_bar_chart.js b/test/functional/apps/visualize/_vertical_bar_chart.js index f1d83908b9b6d..ff0423eb531da 100644 --- a/test/functional/apps/visualize/_vertical_bar_chart.js +++ b/test/functional/apps/visualize/_vertical_bar_chart.js @@ -28,19 +28,28 @@ export default function ({ getService, getPageObjects }) { const PageObjects = getPageObjects(['visualize', 'visEditor', 'visChart', 'timePicker']); describe('vertical bar chart', function () { + const vizName1 = 'Visualization VerticalBarChart'; + + const initBarChart = async () => { + log.debug('navigateToApp visualize'); + await PageObjects.visualize.navigateToNewVisualization(); + log.debug('clickVerticalBarChart'); + await PageObjects.visualize.clickVerticalBarChart(); + await PageObjects.visualize.clickNewSearch(); + await PageObjects.timePicker.setDefaultAbsoluteRange(); + log.debug('Bucket = X-Axis'); + await PageObjects.visEditor.clickBucket('X-axis'); + log.debug('Aggregation = Date Histogram'); + await PageObjects.visEditor.selectAggregation('Date Histogram'); + log.debug('Field = @timestamp'); + await PageObjects.visEditor.selectField('@timestamp'); + // leaving Interval set to Auto + await PageObjects.visEditor.clickGo(); + }; + describe('bar charts x axis tick labels', () => { it('should show tick labels also after rotation of the chart', async function () { - await PageObjects.visualize.navigateToNewVisualization(); - await PageObjects.visualize.clickVerticalBarChart(); - await PageObjects.visualize.clickNewSearch(); - await PageObjects.timePicker.setDefaultAbsoluteRange(); - await PageObjects.visEditor.clickBucket('X-axis'); - log.debug('Aggregation = Date Histogram'); - await PageObjects.visEditor.selectAggregation('Date Histogram'); - log.debug('Field = @timestamp'); - await PageObjects.visEditor.selectField('@timestamp'); - // leaving Interval set to Auto - await PageObjects.visEditor.clickGo(); + await initBarChart(); const bottomLabels = await PageObjects.visChart.getXAxisLabels(); log.debug(`${bottomLabels.length} tick labels on bottom x axis`); @@ -62,6 +71,7 @@ export default function ({ getService, getPageObjects }) { await PageObjects.visEditor.clickBucket('X-axis'); await PageObjects.visEditor.selectAggregation('Date Range'); await PageObjects.visEditor.selectField('@timestamp'); + await PageObjects.visEditor.clickGo(); const bottomLabels = await PageObjects.visChart.getXAxisLabels(); expect(bottomLabels.length).to.be(1); @@ -95,519 +105,456 @@ export default function ({ getService, getPageObjects }) { }); }); - // FLAKY: https://github.com/elastic/kibana/issues/22322 - describe.skip('vertical bar chart flaky part', function () { - const vizName1 = 'Visualization VerticalBarChart'; + it('should save and load', async function () { + await initBarChart(); + await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb(vizName1); - const initBarChart = async () => { - log.debug('navigateToApp visualize'); - await PageObjects.visualize.navigateToNewVisualization(); - log.debug('clickVerticalBarChart'); - await PageObjects.visualize.clickVerticalBarChart(); - await PageObjects.visualize.clickNewSearch(); - await PageObjects.timePicker.setDefaultAbsoluteRange(); - log.debug('Bucket = X-Axis'); - await PageObjects.visEditor.clickBucket('X-axis'); - log.debug('Aggregation = Date Histogram'); - await PageObjects.visEditor.selectAggregation('Date Histogram'); - log.debug('Field = @timestamp'); - await PageObjects.visEditor.selectField('@timestamp'); - // leaving Interval set to Auto - await PageObjects.visEditor.clickGo(); - }; + await PageObjects.visualize.loadSavedVisualization(vizName1); + await PageObjects.visChart.waitForVisualization(); + }); - before(initBarChart); + it('should have inspector enabled', async function () { + await inspector.expectIsEnabled(); + }); - it('should save and load', async function () { - await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb(vizName1); + it('should show correct chart', async function () { + const expectedChartValues = [ + 37, + 202, + 740, + 1437, + 1371, + 751, + 188, + 31, + 42, + 202, + 683, + 1361, + 1415, + 707, + 177, + 27, + 32, + 175, + 707, + 1408, + 1355, + 726, + 201, + 29, + ]; + + // Most recent failure on Jenkins usually indicates the bar chart is still being drawn? + // return arguments[0].getAttribute(arguments[1]);","args":[{"ELEMENT":"592"},"fill"]}] arguments[0].getAttribute is not a function + // try sleeping a bit before getting that data + await retry.try(async () => { + const data = await PageObjects.visChart.getBarChartData(); + log.debug('data=' + data); + log.debug('data.length=' + data.length); + expect(data).to.eql(expectedChartValues); + }); + }); - await PageObjects.visualize.loadSavedVisualization(vizName1); - await PageObjects.visChart.waitForVisualization(); + it('should show correct data', async function () { + // this is only the first page of the tabular data. + const expectedChartData = [ + ['2015-09-20 00:00', '37'], + ['2015-09-20 03:00', '202'], + ['2015-09-20 06:00', '740'], + ['2015-09-20 09:00', '1,437'], + ['2015-09-20 12:00', '1,371'], + ['2015-09-20 15:00', '751'], + ['2015-09-20 18:00', '188'], + ['2015-09-20 21:00', '31'], + ['2015-09-21 00:00', '42'], + ['2015-09-21 03:00', '202'], + ['2015-09-21 06:00', '683'], + ['2015-09-21 09:00', '1,361'], + ['2015-09-21 12:00', '1,415'], + ['2015-09-21 15:00', '707'], + ['2015-09-21 18:00', '177'], + ['2015-09-21 21:00', '27'], + ['2015-09-22 00:00', '32'], + ['2015-09-22 03:00', '175'], + ['2015-09-22 06:00', '707'], + ['2015-09-22 09:00', '1,408'], + ]; + + await inspector.open(); + await inspector.expectTableData(expectedChartData); + await inspector.close(); + }); + + it('should have `drop partial buckets` option', async () => { + const fromTime = 'Sep 20, 2015 @ 06:31:44.000'; + const toTime = 'Sep 22, 2015 @ 18:31:44.000'; + + await PageObjects.timePicker.setAbsoluteRange(fromTime, toTime); + + let expectedChartValues = [ + 82, + 218, + 341, + 440, + 480, + 517, + 522, + 446, + 403, + 321, + 258, + 172, + 95, + 55, + 38, + 24, + 3, + 4, + 11, + 14, + 17, + 38, + 49, + 115, + 152, + 216, + 315, + 402, + 446, + 513, + 520, + 474, + 421, + 307, + 230, + 170, + 99, + 48, + 30, + 15, + 10, + 2, + 8, + 7, + 17, + 34, + 37, + 104, + 153, + 241, + 313, + 404, + 492, + 512, + 503, + 473, + 379, + 293, + 277, + 156, + 56, + ]; + + // Most recent failure on Jenkins usually indicates the bar chart is still being drawn? + // return arguments[0].getAttribute(arguments[1]);","args":[{"ELEMENT":"592"},"fill"]}] arguments[0].getAttribute is not a function + // try sleeping a bit before getting that data + await retry.try(async () => { + const data = await PageObjects.visChart.getBarChartData(); + log.debug('data=' + data); + log.debug('data.length=' + data.length); + expect(data).to.eql(expectedChartValues); }); - it('should have inspector enabled', async function () { - await inspector.expectIsEnabled(); + await PageObjects.visEditor.toggleOpenEditor(2); + await PageObjects.visEditor.clickDropPartialBuckets(); + await PageObjects.visEditor.clickGo(); + + expectedChartValues = [ + 218, + 341, + 440, + 480, + 517, + 522, + 446, + 403, + 321, + 258, + 172, + 95, + 55, + 38, + 24, + 3, + 4, + 11, + 14, + 17, + 38, + 49, + 115, + 152, + 216, + 315, + 402, + 446, + 513, + 520, + 474, + 421, + 307, + 230, + 170, + 99, + 48, + 30, + 15, + 10, + 2, + 8, + 7, + 17, + 34, + 37, + 104, + 153, + 241, + 313, + 404, + 492, + 512, + 503, + 473, + 379, + 293, + 277, + 156, + ]; + + // Most recent failure on Jenkins usually indicates the bar chart is still being drawn? + // return arguments[0].getAttribute(arguments[1]);","args":[{"ELEMENT":"592"},"fill"]}] arguments[0].getAttribute is not a function + // try sleeping a bit before getting that data + await retry.try(async () => { + const data = await PageObjects.visChart.getBarChartData(); + log.debug('data=' + data); + log.debug('data.length=' + data.length); + expect(data).to.eql(expectedChartValues); }); + }); - it('should show correct chart', async function () { - const expectedChartValues = [ - 37, - 202, - 740, - 1437, - 1371, - 751, - 188, - 31, - 42, - 202, - 683, - 1361, - 1415, - 707, - 177, - 27, - 32, - 175, - 707, - 1408, - 1355, - 726, - 201, - 29, - ]; + describe('switch between Y axis scale types', () => { + before(initBarChart); + const axisId = 'ValueAxis-1'; - // Most recent failure on Jenkins usually indicates the bar chart is still being drawn? - // return arguments[0].getAttribute(arguments[1]);","args":[{"ELEMENT":"592"},"fill"]}] arguments[0].getAttribute is not a function - // try sleeping a bit before getting that data - await retry.try(async () => { - const data = await PageObjects.visChart.getBarChartData(); - log.debug('data=' + data); - log.debug('data.length=' + data.length); - expect(data).to.eql(expectedChartValues); - }); + it('should show ticks on selecting log scale', async () => { + await PageObjects.visEditor.clickMetricsAndAxes(); + await PageObjects.visEditor.clickYAxisOptions(axisId); + await PageObjects.visEditor.selectYAxisScaleType(axisId, 'log'); + await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, false); + await PageObjects.visEditor.clickGo(); + const labels = await PageObjects.visChart.getYAxisLabelsAsNumbers(); + const minLabel = 2; + const maxLabel = 5000; + const numberOfLabels = 10; + expect(labels.length).to.be.greaterThan(numberOfLabels); + expect(labels[0]).to.eql(minLabel); + expect(labels[labels.length - 1]).to.be.greaterThan(maxLabel); }); - it('should show correct data', async function () { - // this is only the first page of the tabular data. - const expectedChartData = [ - ['2015-09-20 00:00', '37'], - ['2015-09-20 03:00', '202'], - ['2015-09-20 06:00', '740'], - ['2015-09-20 09:00', '1,437'], - ['2015-09-20 12:00', '1,371'], - ['2015-09-20 15:00', '751'], - ['2015-09-20 18:00', '188'], - ['2015-09-20 21:00', '31'], - ['2015-09-21 00:00', '42'], - ['2015-09-21 03:00', '202'], - ['2015-09-21 06:00', '683'], - ['2015-09-21 09:00', '1,361'], - ['2015-09-21 12:00', '1,415'], - ['2015-09-21 15:00', '707'], - ['2015-09-21 18:00', '177'], - ['2015-09-21 21:00', '27'], - ['2015-09-22 00:00', '32'], - ['2015-09-22 03:00', '175'], - ['2015-09-22 06:00', '707'], - ['2015-09-22 09:00', '1,408'], - ]; - - await inspector.open(); - await inspector.expectTableData(expectedChartData); - await inspector.close(); + it('should show filtered ticks on selecting log scale', async () => { + await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, true); + await PageObjects.visEditor.clickGo(); + const labels = await PageObjects.visChart.getYAxisLabelsAsNumbers(); + const minLabel = 2; + const maxLabel = 5000; + const numberOfLabels = 10; + expect(labels.length).to.be.greaterThan(numberOfLabels); + expect(labels[0]).to.eql(minLabel); + expect(labels[labels.length - 1]).to.be.greaterThan(maxLabel); }); - it('should have `drop partial buckets` option', async () => { - const fromTime = 'Sep 20, 2015 @ 06:31:44.000'; - const toTime = 'Sep 22, 2015 @ 18:31:44.000'; - - await PageObjects.timePicker.setAbsoluteRange(fromTime, toTime); - - let expectedChartValues = [ - 82, - 218, - 341, - 440, - 480, - 517, - 522, - 446, - 403, - 321, - 258, - 172, - 95, - 55, - 38, - 24, - 3, - 4, - 11, - 14, - 17, - 38, - 49, - 115, - 152, - 216, - 315, - 402, - 446, - 513, - 520, - 474, - 421, - 307, - 230, - 170, - 99, - 48, - 30, - 15, - 10, - 2, - 8, - 7, - 17, - 34, - 37, - 104, - 153, - 241, - 313, - 404, - 492, - 512, - 503, - 473, - 379, - 293, - 277, - 156, - 56, + it('should show ticks on selecting square root scale', async () => { + await PageObjects.visEditor.selectYAxisScaleType(axisId, 'square root'); + await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, false); + await PageObjects.visEditor.clickGo(); + const labels = await PageObjects.visChart.getYAxisLabels(); + const expectedLabels = [ + '0', + '200', + '400', + '600', + '800', + '1,000', + '1,200', + '1,400', + '1,600', ]; + expect(labels).to.eql(expectedLabels); + }); - // Most recent failure on Jenkins usually indicates the bar chart is still being drawn? - // return arguments[0].getAttribute(arguments[1]);","args":[{"ELEMENT":"592"},"fill"]}] arguments[0].getAttribute is not a function - // try sleeping a bit before getting that data - await retry.try(async () => { - const data = await PageObjects.visChart.getBarChartData(); - log.debug('data=' + data); - log.debug('data.length=' + data.length); - expect(data).to.eql(expectedChartValues); - }); - - await PageObjects.visEditor.toggleOpenEditor(2); - await PageObjects.visEditor.clickDropPartialBuckets(); + it('should show filtered ticks on selecting square root scale', async () => { + await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, true); await PageObjects.visEditor.clickGo(); + const labels = await PageObjects.visChart.getYAxisLabels(); + const expectedLabels = ['200', '400', '600', '800', '1,000', '1,200', '1,400']; + expect(labels).to.eql(expectedLabels); + }); - expectedChartValues = [ - 218, - 341, - 440, - 480, - 517, - 522, - 446, - 403, - 321, - 258, - 172, - 95, - 55, - 38, - 24, - 3, - 4, - 11, - 14, - 17, - 38, - 49, - 115, - 152, - 216, - 315, - 402, - 446, - 513, - 520, - 474, - 421, - 307, - 230, - 170, - 99, - 48, - 30, - 15, - 10, - 2, - 8, - 7, - 17, - 34, - 37, - 104, - 153, - 241, - 313, - 404, - 492, - 512, - 503, - 473, - 379, - 293, - 277, - 156, + it('should show ticks on selecting linear scale', async () => { + await PageObjects.visEditor.selectYAxisScaleType(axisId, 'linear'); + await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, false); + await PageObjects.visEditor.clickGo(); + const labels = await PageObjects.visChart.getYAxisLabels(); + log.debug(labels); + const expectedLabels = [ + '0', + '200', + '400', + '600', + '800', + '1,000', + '1,200', + '1,400', + '1,600', ]; + expect(labels).to.eql(expectedLabels); + }); - // Most recent failure on Jenkins usually indicates the bar chart is still being drawn? - // return arguments[0].getAttribute(arguments[1]);","args":[{"ELEMENT":"592"},"fill"]}] arguments[0].getAttribute is not a function - // try sleeping a bit before getting that data - await retry.try(async () => { - const data = await PageObjects.visChart.getBarChartData(); - log.debug('data=' + data); - log.debug('data.length=' + data.length); - expect(data).to.eql(expectedChartValues); - }); + it('should show filtered ticks on selecting linear scale', async () => { + await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, true); + await PageObjects.visEditor.clickGo(); + const labels = await PageObjects.visChart.getYAxisLabels(); + const expectedLabels = ['200', '400', '600', '800', '1,000', '1,200', '1,400']; + expect(labels).to.eql(expectedLabels); }); + }); - describe('switch between Y axis scale types', () => { - before(initBarChart); + describe('vertical bar in percent mode', async () => { + it('should show ticks with percentage values', async function () { const axisId = 'ValueAxis-1'; + await PageObjects.visEditor.clickMetricsAndAxes(); + await PageObjects.visEditor.clickYAxisOptions(axisId); + await PageObjects.visEditor.selectYAxisMode('percentage'); + await PageObjects.visEditor.changeYAxisShowCheckbox(axisId, true); + await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, false); + await PageObjects.visEditor.clickGo(); + const labels = await PageObjects.visChart.getYAxisLabels(); + expect(labels[0]).to.eql('0%'); + expect(labels[labels.length - 1]).to.eql('100%'); + }); + }); - it('should show ticks on selecting log scale', async () => { - await PageObjects.visEditor.clickMetricsAndAxes(); - await PageObjects.visEditor.clickYAxisOptions(axisId); - await PageObjects.visEditor.selectYAxisScaleType(axisId, 'log'); - await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, false); - await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - const expectedLabels = [ - '2', - '3', - '4', - '5', - '7', - '9', - '20', - '30', - '40', - '50', - '70', - '90', - '200', - '300', - '400', - '500', - '700', - '900', - '2,000', - '3,000', - '4,000', - '5,000', - '7,000', - ]; - expect(labels).to.eql(expectedLabels); - }); - - it('should show filtered ticks on selecting log scale', async () => { - await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, true); - await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - const expectedLabels = [ - '2', - '3', - '4', - '5', - '7', - '9', - '20', - '30', - '40', - '50', - '70', - '90', - '200', - '300', - '400', - '500', - '700', - '900', - '2,000', - '3,000', - '4,000', - '5,000', - '7,000', - ]; - expect(labels).to.eql(expectedLabels); - }); - - it('should show ticks on selecting square root scale', async () => { - await PageObjects.visEditor.selectYAxisScaleType(axisId, 'square root'); - await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, false); - await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - const expectedLabels = [ - '0', - '200', - '400', - '600', - '800', - '1,000', - '1,200', - '1,400', - '1,600', - ]; - expect(labels).to.eql(expectedLabels); - }); - - it('should show filtered ticks on selecting square root scale', async () => { - await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, true); - await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - const expectedLabels = ['200', '400', '600', '800', '1,000', '1,200', '1,400']; - expect(labels).to.eql(expectedLabels); - }); - - it('should show ticks on selecting linear scale', async () => { - await PageObjects.visEditor.selectYAxisScaleType(axisId, 'linear'); - await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, false); - await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - log.debug(labels); - const expectedLabels = [ - '0', - '200', - '400', - '600', - '800', - '1,000', - '1,200', - '1,400', - '1,600', - ]; - expect(labels).to.eql(expectedLabels); - }); - - it('should show filtered ticks on selecting linear scale', async () => { - await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, true); - await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - const expectedLabels = ['200', '400', '600', '800', '1,000', '1,200', '1,400']; - expect(labels).to.eql(expectedLabels); - }); + describe('vertical bar with Split series', function () { + before(initBarChart); + + it('should show correct series', async function () { + await PageObjects.visEditor.toggleOpenEditor(2, 'false'); + await PageObjects.visEditor.clickBucket('Split series'); + await PageObjects.visEditor.selectAggregation('Terms'); + await PageObjects.visEditor.selectField('response.raw'); + await PageObjects.visChart.waitForVisualizationRenderingStabilized(); + await PageObjects.visEditor.clickGo(); + + const expectedEntries = ['200', '404', '503']; + const legendEntries = await PageObjects.visChart.getLegendEntries(); + expect(legendEntries).to.eql(expectedEntries); }); - describe('vertical bar in percent mode', async () => { - it('should show ticks with percentage values', async function () { - const axisId = 'ValueAxis-1'; - await PageObjects.visEditor.clickMetricsAndAxes(); - await PageObjects.visEditor.clickYAxisOptions(axisId); - await PageObjects.visEditor.selectYAxisMode('percentage'); - await PageObjects.visEditor.changeYAxisShowCheckbox(axisId, true); - await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, false); - await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - expect(labels[0]).to.eql('0%'); - expect(labels[labels.length - 1]).to.eql('100%'); - }); + it('should allow custom sorting of series', async () => { + await PageObjects.visEditor.toggleOpenEditor(1, 'false'); + await PageObjects.visEditor.selectCustomSortMetric(3, 'Min', 'bytes'); + await PageObjects.visEditor.clickGo(); + + const expectedEntries = ['404', '200', '503']; + const legendEntries = await PageObjects.visChart.getLegendEntries(); + expect(legendEntries).to.eql(expectedEntries); }); - describe('vertical bar with Split series', function () { - before(initBarChart); - - it('should show correct series', async function () { - await PageObjects.visEditor.toggleOpenEditor(2, 'false'); - await PageObjects.visEditor.clickBucket('Split series'); - await PageObjects.visEditor.selectAggregation('Terms'); - await PageObjects.visEditor.selectField('response.raw'); - await PageObjects.visChart.waitForVisualizationRenderingStabilized(); - await PageObjects.visEditor.clickGo(); - - const expectedEntries = ['200', '404', '503']; - const legendEntries = await PageObjects.visChart.getLegendEntries(); - expect(legendEntries).to.eql(expectedEntries); - }); - - it('should allow custom sorting of series', async () => { - await PageObjects.visEditor.toggleOpenEditor(1, 'false'); - await PageObjects.visEditor.selectCustomSortMetric(3, 'Min', 'bytes'); - await PageObjects.visEditor.clickGo(); - - const expectedEntries = ['404', '200', '503']; - const legendEntries = await PageObjects.visChart.getLegendEntries(); - expect(legendEntries).to.eql(expectedEntries); - }); - - it('should correctly filter by legend', async () => { - await PageObjects.visChart.filterLegend('200'); - await PageObjects.visChart.waitForVisualization(); - const legendEntries = await PageObjects.visChart.getLegendEntries(); - const expectedEntries = ['200']; - expect(legendEntries).to.eql(expectedEntries); - await filterBar.removeFilter('response.raw'); - await PageObjects.visChart.waitForVisualization(); - }); + it('should correctly filter by legend', async () => { + await PageObjects.visChart.filterLegend('200'); + await PageObjects.visChart.waitForVisualization(); + const legendEntries = await PageObjects.visChart.getLegendEntries(); + const expectedEntries = ['200']; + expect(legendEntries).to.eql(expectedEntries); + await filterBar.removeFilter('response.raw'); + await PageObjects.visChart.waitForVisualization(); }); + }); - describe('vertical bar with multiple splits', function () { - before(initBarChart); - - it('should show correct series', async function () { - await PageObjects.visEditor.toggleOpenEditor(2, 'false'); - await PageObjects.visEditor.clickBucket('Split series'); - await PageObjects.visEditor.selectAggregation('Terms'); - await PageObjects.visEditor.selectField('response.raw'); - await PageObjects.visChart.waitForVisualizationRenderingStabilized(); - - await PageObjects.visEditor.toggleOpenEditor(3, 'false'); - await PageObjects.visEditor.clickBucket('Split series'); - await PageObjects.visEditor.selectAggregation('Terms'); - await PageObjects.visEditor.selectField('machine.os'); - await PageObjects.visChart.waitForVisualizationRenderingStabilized(); - await PageObjects.visEditor.clickGo(); - - const expectedEntries = [ - '200 - win 8', - '200 - win xp', - '200 - ios', - '200 - osx', - '200 - win 7', - '404 - ios', - '503 - ios', - '503 - osx', - '503 - win 7', - '503 - win 8', - '503 - win xp', - '404 - osx', - '404 - win 7', - '404 - win 8', - '404 - win xp', - ]; - const legendEntries = await PageObjects.visChart.getLegendEntries(); - expect(legendEntries).to.eql(expectedEntries); - }); - - it('should show correct series when disabling first agg', async function () { - // this will avoid issues with the play tooltip covering the disable agg button - await testSubjects.scrollIntoView('metricsAggGroup'); - await PageObjects.visEditor.toggleDisabledAgg(3); - await PageObjects.visEditor.clickGo(); - - const expectedEntries = ['win 8', 'win xp', 'ios', 'osx', 'win 7']; - const legendEntries = await PageObjects.visChart.getLegendEntries(); - expect(legendEntries).to.eql(expectedEntries); - }); + describe('vertical bar with multiple splits', function () { + before(initBarChart); + + it('should show correct series', async function () { + await PageObjects.visEditor.toggleOpenEditor(2, 'false'); + await PageObjects.visEditor.clickBucket('Split series'); + await PageObjects.visEditor.selectAggregation('Terms'); + await PageObjects.visEditor.selectField('response.raw'); + await PageObjects.visChart.waitForVisualizationRenderingStabilized(); + + await PageObjects.visEditor.toggleOpenEditor(3, 'false'); + await PageObjects.visEditor.clickBucket('Split series'); + await PageObjects.visEditor.selectAggregation('Terms'); + await PageObjects.visEditor.selectField('machine.os'); + await PageObjects.visChart.waitForVisualizationRenderingStabilized(); + await PageObjects.visEditor.clickGo(); + + const expectedEntries = [ + '200 - win 8', + '200 - win xp', + '200 - ios', + '200 - osx', + '200 - win 7', + '404 - ios', + '503 - ios', + '503 - osx', + '503 - win 7', + '503 - win 8', + '503 - win xp', + '404 - osx', + '404 - win 7', + '404 - win 8', + '404 - win xp', + ]; + const legendEntries = await PageObjects.visChart.getLegendEntries(); + expect(legendEntries).to.eql(expectedEntries); + }); + + it('should show correct series when disabling first agg', async function () { + // this will avoid issues with the play tooltip covering the disable agg button + await testSubjects.scrollIntoView('metricsAggGroup'); + await PageObjects.visEditor.toggleDisabledAgg(3); + await PageObjects.visEditor.clickGo(); + + const expectedEntries = ['win 8', 'win xp', 'ios', 'osx', 'win 7']; + const legendEntries = await PageObjects.visChart.getLegendEntries(); + expect(legendEntries).to.eql(expectedEntries); }); + }); + + describe('vertical bar with derivative', function () { + before(initBarChart); + + it('should show correct series', async function () { + await PageObjects.visEditor.toggleOpenEditor(2, 'false'); + await PageObjects.visEditor.toggleOpenEditor(1); + await PageObjects.visEditor.selectAggregation('Derivative', 'metrics'); + await PageObjects.visChart.waitForVisualizationRenderingStabilized(); + await PageObjects.visEditor.clickGo(); + + const expectedEntries = ['Derivative of Count']; + const legendEntries = await PageObjects.visChart.getLegendEntries(); + expect(legendEntries).to.eql(expectedEntries); + }); + + it('should show an error if last bucket aggregation is terms', async () => { + await PageObjects.visEditor.toggleOpenEditor(2, 'false'); + await PageObjects.visEditor.clickBucket('Split series'); + await PageObjects.visEditor.selectAggregation('Terms'); + await PageObjects.visEditor.selectField('response.raw'); - describe('vertical bar with derivative', function () { - before(initBarChart); - - it('should show correct series', async function () { - await PageObjects.visEditor.toggleOpenEditor(2, 'false'); - await PageObjects.visEditor.toggleOpenEditor(1); - await PageObjects.visEditor.selectAggregation('Derivative', 'metrics'); - await PageObjects.visChart.waitForVisualizationRenderingStabilized(); - await PageObjects.visEditor.clickGo(); - - const expectedEntries = ['Derivative of Count']; - const legendEntries = await PageObjects.visChart.getLegendEntries(); - expect(legendEntries).to.eql(expectedEntries); - }); - - it('should show an error if last bucket aggregation is terms', async () => { - await PageObjects.visEditor.toggleOpenEditor(2, 'false'); - await PageObjects.visEditor.clickBucket('Split series'); - await PageObjects.visEditor.selectAggregation('Terms'); - await PageObjects.visEditor.selectField('response.raw'); - - const errorMessage = await PageObjects.visEditor.getBucketErrorMessage(); - expect(errorMessage).to.contain('Last bucket aggregation must be "Date Histogram"'); - }); + const errorMessage = await PageObjects.visEditor.getBucketErrorMessage(); + expect(errorMessage).to.contain('Last bucket aggregation must be "Date Histogram"'); }); }); }); diff --git a/test/functional/apps/visualize/_vertical_bar_chart_nontimeindex.js b/test/functional/apps/visualize/_vertical_bar_chart_nontimeindex.js index 42dfd791321a1..f95781c9bbb33 100644 --- a/test/functional/apps/visualize/_vertical_bar_chart_nontimeindex.js +++ b/test/functional/apps/visualize/_vertical_bar_chart_nontimeindex.js @@ -25,8 +25,7 @@ export default function ({ getService, getPageObjects }) { const inspector = getService('inspector'); const PageObjects = getPageObjects(['common', 'visualize', 'header', 'visEditor', 'visChart']); - // FLAKY: https://github.com/elastic/kibana/issues/22322 - describe.skip('vertical bar chart with index without time filter', function () { + describe('vertical bar chart with index without time filter', function () { const vizName1 = 'Visualization VerticalBarChart without time filter'; const initBarChart = async () => { @@ -46,6 +45,7 @@ export default function ({ getService, getPageObjects }) { await PageObjects.visEditor.selectField('@timestamp'); await PageObjects.visEditor.setInterval('3h', { type: 'custom' }); await PageObjects.visChart.waitForVisualizationRenderingStabilized(); + await PageObjects.visEditor.clickGo(); }; before(initBarChart); @@ -129,7 +129,7 @@ export default function ({ getService, getPageObjects }) { await inspector.expectTableData(expectedChartData); }); - describe.skip('switch between Y axis scale types', () => { + describe('switch between Y axis scale types', () => { before(initBarChart); const axisId = 'ValueAxis-1'; @@ -139,57 +139,25 @@ export default function ({ getService, getPageObjects }) { await PageObjects.visEditor.selectYAxisScaleType(axisId, 'log'); await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, false); await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - const expectedLabels = [ - '2', - '3', - '5', - '7', - '10', - '20', - '30', - '50', - '70', - '100', - '200', - '300', - '500', - '700', - '1,000', - '2,000', - '3,000', - '5,000', - '7,000', - ]; - expect(labels).to.eql(expectedLabels); + const labels = await PageObjects.visChart.getYAxisLabelsAsNumbers(); + const minLabel = 2; + const maxLabel = 5000; + const numberOfLabels = 10; + expect(labels.length).to.be.greaterThan(numberOfLabels); + expect(labels[0]).to.eql(minLabel); + expect(labels[labels.length - 1]).to.be.greaterThan(maxLabel); }); it('should show filtered ticks on selecting log scale', async () => { await PageObjects.visEditor.changeYAxisFilterLabelsCheckbox(axisId, true); await PageObjects.visEditor.clickGo(); - const labels = await PageObjects.visChart.getYAxisLabels(); - const expectedLabels = [ - '2', - '3', - '5', - '7', - '10', - '20', - '30', - '50', - '70', - '100', - '200', - '300', - '500', - '700', - '1,000', - '2,000', - '3,000', - '5,000', - '7,000', - ]; - expect(labels).to.eql(expectedLabels); + const labels = await PageObjects.visChart.getYAxisLabelsAsNumbers(); + const minLabel = 2; + const maxLabel = 5000; + const numberOfLabels = 10; + expect(labels.length).to.be.greaterThan(numberOfLabels); + expect(labels[0]).to.eql(minLabel); + expect(labels[labels.length - 1]).to.be.greaterThan(maxLabel); }); it('should show ticks on selecting square root scale', async () => { diff --git a/test/functional/apps/visualize/input_control_vis/chained_controls.js b/test/functional/apps/visualize/input_control_vis/chained_controls.js index 179ffa5125a9a..89cca7dc7827e 100644 --- a/test/functional/apps/visualize/input_control_vis/chained_controls.js +++ b/test/functional/apps/visualize/input_control_vis/chained_controls.js @@ -34,6 +34,7 @@ export default function ({ getService, getPageObjects }) { await PageObjects.visualize.loadSavedVisualization('chained input control', { navigateToVisualize: false, }); + await testSubjects.waitForEnabled('addFilter', 10000); }); it('should disable child control when parent control is not set', async () => { diff --git a/test/functional/page_objects/common_page.ts b/test/functional/page_objects/common_page.ts index 8c5a99204bab6..d6a96eb651d02 100644 --- a/test/functional/page_objects/common_page.ts +++ b/test/functional/page_objects/common_page.ts @@ -407,7 +407,11 @@ export function CommonPageProvider({ getService, getPageObjects }: FtrProviderCo async closeToastIfExists() { const toastShown = await find.existsByCssSelector('.euiToast'); if (toastShown) { - await find.clickByCssSelector('.euiToast__closeButton'); + try { + await find.clickByCssSelector('.euiToast__closeButton'); + } catch (err) { + // ignore errors, toast clear themselves after timeout + } } } diff --git a/test/functional/page_objects/dashboard_page.ts b/test/functional/page_objects/dashboard_page.ts index 7c325ba6d4aec..b662fd62e4b02 100644 --- a/test/functional/page_objects/dashboard_page.ts +++ b/test/functional/page_objects/dashboard_page.ts @@ -294,6 +294,7 @@ export function DashboardPageProvider({ getService, getPageObjects }: FtrProvide await this.enterDashboardTitleAndClickSave(dashboardName, saveOptions); if (saveOptions.needsConfirm) { + await this.ensureDuplicateTitleCallout(); await this.clickSave(); } diff --git a/test/functional/page_objects/login_page.ts b/test/functional/page_objects/login_page.ts index c84f47a342155..350ab8be1a274 100644 --- a/test/functional/page_objects/login_page.ts +++ b/test/functional/page_objects/login_page.ts @@ -7,26 +7,76 @@ * not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *    http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied.  See the License for the * specific language governing permissions and limitations * under the License. */ +import { delay } from 'bluebird'; import { FtrProviderContext } from '../ftr_provider_context'; export function LoginPageProvider({ getService }: FtrProviderContext) { const testSubjects = getService('testSubjects'); + const log = getService('log'); + const find = getService('find'); + + const regularLogin = async (user: string, pwd: string) => { + await testSubjects.setValue('loginUsername', user); + await testSubjects.setValue('loginPassword', pwd); + await testSubjects.click('loginSubmit'); + await find.waitForDeletedByCssSelector('.kibanaWelcomeLogo'); + await find.byCssSelector('[data-test-subj="kibanaChrome"]', 60000); // 60 sec waiting + }; + + const samlLogin = async (user: string, pwd: string) => { + try { + await find.clickByButtonText('Login using SAML'); + await find.setValue('input[name="email"]', user); + await find.setValue('input[type="password"]', pwd); + await find.clickByCssSelector('.auth0-label-submit'); + await find.byCssSelector('[data-test-subj="kibanaChrome"]', 60000); // 60 sec waiting + } catch (err) { + log.debug(`${err} \nFailed to find Auth0 login page, trying the Auth0 last login page`); + await find.clickByCssSelector('.auth0-lock-social-button'); + } + }; class LoginPage { async login(user: string, pwd: string) { - await testSubjects.setValue('loginUsername', user); - await testSubjects.setValue('loginPassword', pwd); - await testSubjects.click('loginSubmit'); + if ( + process.env.VM === 'ubuntu18_deb_oidc' || + process.env.VM === 'ubuntu16_deb_desktop_saml' + ) { + await samlLogin(user, pwd); + return; + } + + await regularLogin(user, pwd); + } + + async logoutLogin(user: string, pwd: string) { + await this.logout(); + await this.sleep(3002); + await this.login(user, pwd); + } + + async logout() { + await testSubjects.click('userMenuButton'); + await this.sleep(500); + await testSubjects.click('logoutLink'); + log.debug('### found and clicked log out--------------------------'); + await this.sleep(8002); + } + + async sleep(sleepMilliseconds: number) { + log.debug(`... sleep(${sleepMilliseconds}) start`); + await delay(sleepMilliseconds); + log.debug(`... sleep(${sleepMilliseconds}) end`); } } diff --git a/test/functional/page_objects/timelion_page.ts b/test/functional/page_objects/timelion_page.ts index f025fc946bef1..23a9cc514a444 100644 --- a/test/functional/page_objects/timelion_page.ts +++ b/test/functional/page_objects/timelion_page.ts @@ -47,7 +47,7 @@ export function TimelionPageProvider({ getService, getPageObjects }: FtrProvider public async updateExpression(updates: string) { const input = await testSubjects.find('timelionExpressionTextArea'); await input.type(updates); - await PageObjects.common.sleep(500); + await PageObjects.common.sleep(1000); } public async getExpression() { @@ -60,7 +60,7 @@ export function TimelionPageProvider({ getService, getPageObjects }: FtrProvider return await Promise.all(elements.map(async (element) => await element.getVisibleText())); } - public async clickSuggestion(suggestionIndex = 0, waitTime = 500) { + public async clickSuggestion(suggestionIndex = 0, waitTime = 1000) { const elements = await testSubjects.findAll('timelionSuggestionListItem'); if (suggestionIndex > elements.length) { throw new Error( diff --git a/test/functional/page_objects/vega_chart_page.ts b/test/functional/page_objects/vega_chart_page.ts index 488f4cfd0d0ce..b9906911b00f1 100644 --- a/test/functional/page_objects/vega_chart_page.ts +++ b/test/functional/page_objects/vega_chart_page.ts @@ -17,20 +17,17 @@ * under the License. */ -import expect from '@kbn/expect'; +import { Key } from 'selenium-webdriver'; import { FtrProviderContext } from '../ftr_provider_context'; export function VegaChartPageProvider({ getService, getPageObjects, - updateBaselines, }: FtrProviderContext & { updateBaselines: boolean }) { const find = getService('find'); const testSubjects = getService('testSubjects'); const browser = getService('browser'); - const screenshot = getService('screenshots'); - const log = getService('log'); - const { visEditor, visChart } = getPageObjects(['visEditor', 'visChart']); + const { common } = getPageObjects(['common']); class VegaChartPage { public async getSpec() { @@ -45,6 +42,19 @@ export function VegaChartPageProvider({ return linesText.join('\n'); } + public async typeInSpec(text: string) { + const editor = await testSubjects.find('vega-editor'); + const textarea = await editor.findByClassName('ace_content'); + await textarea.click(); + let repeats = 20; + while (--repeats > 0) { + await browser.pressKeys(Key.ARROW_UP); + await common.sleep(50); + } + await browser.pressKeys(Key.ARROW_RIGHT); + await browser.pressKeys(text); + } + public async getViewContainer() { return await find.byCssSelector('div.vgaVis__view'); } @@ -53,37 +63,16 @@ export function VegaChartPageProvider({ return await find.byCssSelector('div.vgaVis__controls'); } - /** - * Removes chrome and takes a small screenshot of a vis to compare against a baseline. - * @param {string} name The name of the baseline image. - * @param {object} opts Options object. - * @param {number} opts.threshold Threshold for allowed variance when comparing images. - */ - public async expectVisToMatchScreenshot(name: string, opts = { threshold: 0.05 }) { - log.debug(`expectVisToMatchScreenshot(${name})`); - - // Collapse sidebar and inject some CSS to hide the nav so we have a focused screenshot - await visEditor.clickEditorSidebarCollapse(); - await visChart.waitForVisualizationRenderingStabilized(); - await browser.execute(` - var el = document.createElement('style'); - el.id = '__data-test-style'; - el.innerHTML = '[data-test-subj="headerGlobalNav"] { display: none; } '; - el.innerHTML += '[data-test-subj="top-nav"] { display: none; } '; - el.innerHTML += '[data-test-subj="experimentalVisInfo"] { display: none; } '; - document.body.appendChild(el); - `); - - const percentDifference = await screenshot.compareAgainstBaseline(name, updateBaselines); - - // Reset the chart to its original state - await browser.execute(` - var el = document.getElementById('__data-test-style'); - document.body.removeChild(el); - `); - await visEditor.clickEditorSidebarCollapse(); - await visChart.waitForVisualizationRenderingStabilized(); - expect(percentDifference).to.be.lessThan(opts.threshold); + public async getYAxisLabels() { + const chart = await testSubjects.find('visualizationLoader'); + const yAxis = await chart.findByCssSelector('[aria-label^="Y-axis"]'); + const tickGroup = await yAxis.findByClassName('role-axis-label'); + const labels = await tickGroup.findAllByCssSelector('text'); + const labelTexts: string[] = []; + for (const label of labels) { + labelTexts.push(await label.getVisibleText()); + } + return labelTexts; } } diff --git a/test/functional/page_objects/visual_builder_page.ts b/test/functional/page_objects/visual_builder_page.ts index 4a4beca959540..2771982fecdea 100644 --- a/test/functional/page_objects/visual_builder_page.ts +++ b/test/functional/page_objects/visual_builder_page.ts @@ -279,8 +279,10 @@ export function VisualBuilderPageProvider({ getService, getPageObjects }: FtrPro decimalPlaces?: string; }) { if (from) { - const fromCombobox = await find.byCssSelector('[id$="from-row"] .euiComboBox'); - await comboBox.setElement(fromCombobox, from, { clickWithMouse: true }); + await retry.try(async () => { + const fromCombobox = await find.byCssSelector('[id$="from-row"] .euiComboBox'); + await comboBox.setElement(fromCombobox, from, { clickWithMouse: true }); + }); } if (to) { const toCombobox = await find.byCssSelector('[id$="to-row"] .euiComboBox'); @@ -313,9 +315,9 @@ export function VisualBuilderPageProvider({ getService, getPageObjects }: FtrPro public async getRhythmChartLegendValue(nth = 0) { await PageObjects.visChart.waitForVisualizationRenderingStabilized(); - const metricValue = (await find.allByCssSelector(`.echLegendItem .echLegendItem__extra`))[ - nth - ]; + const metricValue = ( + await find.allByCssSelector(`.echLegendItem .echLegendItem__extra`, 20000) + )[nth]; await metricValue.moveMouseTo(); return await metricValue.getVisibleText(); } @@ -406,7 +408,7 @@ export function VisualBuilderPageProvider({ getService, getPageObjects }: FtrPro * @memberof VisualBuilderPage */ public async getViewTable(): Promise { - const tableView = await testSubjects.find('tableView'); + const tableView = await testSubjects.find('tableView', 20000); return await tableView.getVisibleText(); } diff --git a/test/functional/page_objects/visualize_chart_page.ts b/test/functional/page_objects/visualize_chart_page.ts index 590631ad48b00..ade78cbb810d5 100644 --- a/test/functional/page_objects/visualize_chart_page.ts +++ b/test/functional/page_objects/visualize_chart_page.ts @@ -51,6 +51,10 @@ export function VisualizeChartPageProvider({ getService, getPageObjects }: FtrPr .map((tick) => $(tick).text().trim()); } + public async getYAxisLabelsAsNumbers() { + return (await this.getYAxisLabels()).map((label) => Number(label.replace(',', ''))); + } + /** * Gets the chart data and scales it based on chart height and label. * @param dataLabel data-label value diff --git a/test/functional/page_objects/visualize_page.ts b/test/functional/page_objects/visualize_page.ts index a08598fc42d68..92692767b096d 100644 --- a/test/functional/page_objects/visualize_page.ts +++ b/test/functional/page_objects/visualize_page.ts @@ -352,6 +352,16 @@ export function VisualizePageProvider({ getService, getPageObjects }: FtrProvide await testSubjects.existOrFail('visualizesaveAndReturnButton'); await testSubjects.click('visualizesaveAndReturnButton'); } + + public async linkedToOriginatingApp() { + await header.waitUntilLoadingHasFinished(); + await testSubjects.existOrFail('visualizesaveAndReturnButton'); + } + + public async notLinkedToOriginatingApp() { + await header.waitUntilLoadingHasFinished(); + await testSubjects.missingOrFail('visualizesaveAndReturnButton'); + } } return new VisualizePage(); diff --git a/test/functional/screenshots/baseline/vega_chart.png b/test/functional/screenshots/baseline/vega_chart.png deleted file mode 100644 index 5288bd9c7b924..0000000000000 Binary files a/test/functional/screenshots/baseline/vega_chart.png and /dev/null differ diff --git a/test/functional/screenshots/baseline/vega_chart_filtered.png b/test/functional/screenshots/baseline/vega_chart_filtered.png deleted file mode 100644 index 974ede74095d2..0000000000000 Binary files a/test/functional/screenshots/baseline/vega_chart_filtered.png and /dev/null differ diff --git a/test/functional/services/combo_box.ts b/test/functional/services/combo_box.ts index 60fea7ea86cf9..ac7a40361d065 100644 --- a/test/functional/services/combo_box.ts +++ b/test/functional/services/combo_box.ts @@ -90,7 +90,7 @@ export function ComboBoxProvider({ getService, getPageObjects }: FtrProviderCont await this.clickOption(options.clickWithMouse, selectOptions[0]); } else { // if it doesn't find the item which text starts with value, it will choose the first option - const firstOption = await find.byCssSelector('.euiFilterSelectItem'); + const firstOption = await find.byCssSelector('.euiFilterSelectItem', 5000); await this.clickOption(options.clickWithMouse, firstOption); } } else { diff --git a/test/plugin_functional/plugins/core_app_status/public/plugin.tsx b/test/plugin_functional/plugins/core_app_status/public/plugin.tsx index af23bfbe1f8f5..bdc08c03c1912 100644 --- a/test/plugin_functional/plugins/core_app_status/public/plugin.tsx +++ b/test/plugin_functional/plugins/core_app_status/public/plugin.tsx @@ -26,6 +26,7 @@ import { CoreStart, AppMountParameters, } from 'kibana/public'; +import { renderApp } from './application'; import './types'; export class CoreAppStatusPlugin implements Plugin<{}, CoreAppStatusPluginStart> { @@ -36,7 +37,6 @@ export class CoreAppStatusPlugin implements Plugin<{}, CoreAppStatusPluginStart> id: 'app_status_start', title: 'App Status Start Page', async mount(params: AppMountParameters) { - const { renderApp } = await import('./application'); return renderApp('app_status_start', params); }, }); @@ -47,7 +47,6 @@ export class CoreAppStatusPlugin implements Plugin<{}, CoreAppStatusPluginStart> euiIconType: 'snowflake', updater$: this.appUpdater, async mount(params: AppMountParameters) { - const { renderApp } = await import('./application'); return renderApp('app_status', params); }, }); diff --git a/test/plugin_functional/test_suites/core_plugins/application_status.ts b/test/plugin_functional/test_suites/core_plugins/application_status.ts index 31a1c28b50842..a4c2db733b894 100644 --- a/test/plugin_functional/test_suites/core_plugins/application_status.ts +++ b/test/plugin_functional/test_suites/core_plugins/application_status.ts @@ -41,6 +41,7 @@ export default function ({ getService, getPageObjects }: PluginFunctionalProvide const PageObjects = getPageObjects(['common']); const browser = getService('browser'); const appsMenu = getService('appsMenu'); + const retry = getService('retry'); const testSubjects = getService('testSubjects'); const setAppStatus = async (s: Partial) => { @@ -50,15 +51,14 @@ export default function ({ getService, getPageObjects }: PluginFunctionalProvide }, s); }; - const navigateToApp = async (i: string) => { + const navigateToApp = async (id: string) => { return await browser.executeAsync(async (appId, cb) => { await window.__coreAppStatus.navigateToApp(appId); cb(); - }, i); + }, id); }; - // FLAKY: https://github.com/elastic/kibana/issues/65423 - describe.skip('application status management', () => { + describe('application status management', () => { beforeEach(async () => { await PageObjects.common.navigateToApp('app_status_start'); }); @@ -101,15 +101,17 @@ export default function ({ getService, getPageObjects }: PluginFunctionalProvide }); it('allows to change the defaultPath of an application', async () => { - let link = await appsMenu.getLink('App Status'); + const link = await appsMenu.getLink('App Status'); expect(link!.href).to.eql(getKibanaUrl('/app/app_status')); await setAppStatus({ defaultPath: '/arbitrary/path', }); - link = await appsMenu.getLink('App Status'); - expect(link!.href).to.eql(getKibanaUrl('/app/app_status/arbitrary/path')); + await retry.waitFor('link url updated with "defaultPath"', async () => { + const updatedLink = await appsMenu.getLink('App Status'); + return updatedLink?.href === getKibanaUrl('/app/app_status/arbitrary/path'); + }); await navigateToApp('app_status'); expect(await testSubjects.exists('appStatusApp')).to.eql(true); diff --git a/test/scripts/jenkins_xpack.sh b/test/scripts/jenkins_xpack.sh index bc927b1ed7b4d..77480554f738c 100755 --- a/test/scripts/jenkins_xpack.sh +++ b/test/scripts/jenkins_xpack.sh @@ -3,9 +3,9 @@ source test/scripts/jenkins_test_setup.sh if [[ -z "$CODE_COVERAGE" ]] ; then - echo " -> Running mocha tests" - cd "$XPACK_DIR" - checks-reporter-with-killswitch "X-Pack Karma Tests" yarn test:karma + echo " -> Building legacy styles for x-pack canvas storyshot tests" + cd "$KIBANA_DIR" + node scripts/build_sass echo "" echo "" diff --git a/vars/slackNotifications.groovy b/vars/slackNotifications.groovy index 2ffb420ecf3f4..30f86e6d6f0ad 100644 --- a/vars/slackNotifications.groovy +++ b/vars/slackNotifications.groovy @@ -13,12 +13,35 @@ def dividerBlock() { return [ type: "divider" ] } +// If a message is longer than the limit, split it up by '\n' into parts, and return as many parts as will fit within the limit +def shortenMessage(message, sizeLimit = 3000) { + if (message.size() <= sizeLimit) { + return message + } + + def truncatedMessage = "[...truncated...]" + + def parts = message.split("\n") + message = "" + + for(def part in parts) { + if ((message.size() + part.size() + truncatedMessage.size() + 1) > sizeLimit) { + break; + } + message += part+"\n" + } + + message += truncatedMessage + + return message.size() <= sizeLimit ? message : truncatedMessage +} + def markdownBlock(message) { return [ type: "section", text: [ type: "mrkdwn", - text: message, + text: shortenMessage(message, 3000), // 3000 is max text length for `section`s only ], ] } @@ -29,7 +52,7 @@ def contextBlock(message) { elements: [ [ type: 'mrkdwn', - text: message, + text: message, // Not sure what the size limit is here, I tried 10000s of characters and it still worked ] ] ] @@ -62,7 +85,7 @@ def getTestFailures() { def messages = [] messages << "*Test Failures*" - def list = failures.collect { + def list = failures.take(10).collect { def name = it .fullDisplayName .split(/\./, 2)[-1] @@ -73,7 +96,9 @@ def getTestFailures() { return "• <${it.url}|${name}>" }.join("\n") - return "*Test Failures*\n${list}" + + def moreText = failures.size() > 10 ? "\n• ...and ${failures.size()-10} more" : "" + return "*Test Failures*\n${list}${moreText}" } def getDefaultDisplayName() { @@ -98,6 +123,10 @@ def getStatusIcon() { return ':broken_heart:' } +def getBackupMessage(config) { + return "${getStatusIcon()} ${config.title}\n\nFirst attempt at sending this notification failed. Please check the build." +} + def sendFailedBuild(Map params = [:]) { def config = [ channel: '#kibana-operations-alerts', @@ -117,7 +146,7 @@ def sendFailedBuild(Map params = [:]) { blocks << dividerBlock() blocks << config.context - slackSend( + def resp = slackSend( channel: config.channel, username: config.username, iconEmoji: config.icon, @@ -125,6 +154,17 @@ def sendFailedBuild(Map params = [:]) { message: message, blocks: blocks ) + + if (!resp) { + slackSend( + channel: config.channel, + username: config.username, + iconEmoji: config.icon, + color: config.color, + message: message, + blocks: [markdownBlock(getBackupMessage(config))] + ) + } } def onFailure(Map options = [:]) { diff --git a/x-pack/README.md b/x-pack/README.md index 03d2e3287c0f0..0449f1fc1bdab 100644 --- a/x-pack/README.md +++ b/x-pack/README.md @@ -44,14 +44,6 @@ If you want to run tests only for a specific plugin (to save some time), you can yarn test --plugins [,]* # where is "reporting", etc. ``` -#### Debugging browser tests -``` -yarn test:karma:debug -``` -Initializes an environment for debugging the browser tests. Includes an dedicated instance of the kibana server for building the test bundle, and a karma server. When running this task the build is optimized for the first time and then a karma-owned instance of the browser is opened. Click the "debug" button to open a new tab that executes the unit tests. - -Run single tests by appending `grep` parameter to the end of the URL. For example `http://localhost:9876/debug.html?grep=ML%20-%20Explorer%20Controller` will only run tests with 'ML - Explorer Controller' in the describe block. - #### Running server unit tests You can run mocha unit tests by running: diff --git a/x-pack/gulpfile.js b/x-pack/gulpfile.js index 7e5ab9b18f019..78ed2bff8cb01 100644 --- a/x-pack/gulpfile.js +++ b/x-pack/gulpfile.js @@ -8,7 +8,6 @@ require('../src/setup_node_env'); const { buildTask } = require('./tasks/build'); const { devTask } = require('./tasks/dev'); -const { testTask, testKarmaTask, testKarmaDebugTask } = require('./tasks/test'); const { downloadChromium } = require('./tasks/download_chromium'); // export the tasks that are runnable from the CLI @@ -16,7 +15,4 @@ module.exports = { build: buildTask, dev: devTask, downloadChromium, - test: testTask, - 'test:karma': testKarmaTask, - 'test:karma:debug': testKarmaDebugTask, }; diff --git a/x-pack/package.json b/x-pack/package.json index 1de009ae1232f..76655f75cadcc 100644 --- a/x-pack/package.json +++ b/x-pack/package.json @@ -11,8 +11,6 @@ "build": "gulp build", "testonly": "echo 'Deprecated, use `yarn test`' && gulp test", "test": "gulp test", - "test:karma:debug": "gulp test:karma:debug", - "test:karma": "gulp test:karma", "test:jest": "node scripts/jest", "test:mocha": "node scripts/mocha" }, @@ -49,7 +47,7 @@ "@testing-library/react-hooks": "^3.2.1", "@testing-library/jest-dom": "^5.8.0", "@types/angular": "^1.6.56", - "@types/archiver": "^3.0.0", + "@types/archiver": "^3.1.0", "@types/base64-js": "^1.2.5", "@types/boom": "^7.2.0", "@types/cheerio": "^0.22.10", @@ -133,7 +131,7 @@ "cheerio": "0.22.0", "commander": "3.0.2", "copy-webpack-plugin": "^6.0.2", - "cypress": "4.5.0", + "cypress": "4.11.0", "cypress-multi-reporters": "^1.2.3", "enzyme": "^3.11.0", "enzyme-adapter-react-16": "^1.15.2", @@ -284,6 +282,7 @@ "json-stable-stringify": "^1.0.1", "jsonwebtoken": "^8.5.1", "jsts": "^1.6.2", + "kea": "^2.0.1", "lodash": "^4.17.15", "lz-string": "^1.4.4", "mapbox-gl": "^1.10.0", @@ -386,4 +385,4 @@ "cypress-multi-reporters" ] } -} \ No newline at end of file +} diff --git a/x-pack/plugins/actions/kibana.json b/x-pack/plugins/actions/kibana.json index 14ddb8257ff37..ef604a9cf6417 100644 --- a/x-pack/plugins/actions/kibana.json +++ b/x-pack/plugins/actions/kibana.json @@ -4,7 +4,7 @@ "version": "8.0.0", "kibanaVersion": "kibana", "configPath": ["xpack", "actions"], - "requiredPlugins": ["licensing", "taskManager", "encryptedSavedObjects", "eventLog"], - "optionalPlugins": ["usageCollection", "spaces"], + "requiredPlugins": ["licensing", "taskManager", "encryptedSavedObjects", "eventLog", "features"], + "optionalPlugins": ["usageCollection", "spaces", "security"], "ui": false } diff --git a/x-pack/plugins/actions/server/actions_client.mock.ts b/x-pack/plugins/actions/server/actions_client.mock.ts index efd044c7e2493..48122a5ce4e0f 100644 --- a/x-pack/plugins/actions/server/actions_client.mock.ts +++ b/x-pack/plugins/actions/server/actions_client.mock.ts @@ -19,6 +19,7 @@ const createActionsClientMock = () => { getBulk: jest.fn(), execute: jest.fn(), enqueueExecution: jest.fn(), + listTypes: jest.fn(), }; return mocked; }; diff --git a/x-pack/plugins/actions/server/actions_client.test.ts b/x-pack/plugins/actions/server/actions_client.test.ts index 807d75cd0d701..90b989ac3b52e 100644 --- a/x-pack/plugins/actions/server/actions_client.test.ts +++ b/x-pack/plugins/actions/server/actions_client.test.ts @@ -22,11 +22,14 @@ import { import { actionExecutorMock } from './lib/action_executor.mock'; import uuid from 'uuid'; import { KibanaRequest } from 'kibana/server'; +import { ActionsAuthorization } from './authorization/actions_authorization'; +import { actionsAuthorizationMock } from './authorization/actions_authorization.mock'; const defaultKibanaIndex = '.kibana'; -const savedObjectsClient = savedObjectsClientMock.create(); +const unsecuredSavedObjectsClient = savedObjectsClientMock.create(); const scopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); const actionExecutor = actionExecutorMock.create(); +const authorization = actionsAuthorizationMock.create(); const executionEnqueuer = jest.fn(); const request = {} as KibanaRequest; @@ -55,17 +58,88 @@ beforeEach(() => { actionTypeRegistry = new ActionTypeRegistry(actionTypeRegistryParams); actionsClient = new ActionsClient({ actionTypeRegistry, - savedObjectsClient, + unsecuredSavedObjectsClient, scopedClusterClient, defaultKibanaIndex, preconfiguredActions: [], actionExecutor, executionEnqueuer, request, + authorization: (authorization as unknown) as ActionsAuthorization, }); }); describe('create()', () => { + describe('authorization', () => { + test('ensures user is authorised to create this type of action', async () => { + const savedObjectCreateResult = { + id: '1', + type: 'action', + attributes: { + name: 'my name', + actionTypeId: 'my-action-type', + config: {}, + }, + references: [], + }; + actionTypeRegistry.register({ + id: 'my-action-type', + name: 'My action type', + minimumLicenseRequired: 'basic', + executor, + }); + unsecuredSavedObjectsClient.create.mockResolvedValueOnce(savedObjectCreateResult); + + await actionsClient.create({ + action: { + name: 'my name', + actionTypeId: 'my-action-type', + config: {}, + secrets: {}, + }, + }); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('create', 'my-action-type'); + }); + + test('throws when user is not authorised to create this type of action', async () => { + const savedObjectCreateResult = { + id: '1', + type: 'action', + attributes: { + name: 'my name', + actionTypeId: 'my-action-type', + config: {}, + }, + references: [], + }; + actionTypeRegistry.register({ + id: 'my-action-type', + name: 'My action type', + minimumLicenseRequired: 'basic', + executor, + }); + unsecuredSavedObjectsClient.create.mockResolvedValueOnce(savedObjectCreateResult); + + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to create a "my-action-type" action`) + ); + + await expect( + actionsClient.create({ + action: { + name: 'my name', + actionTypeId: 'my-action-type', + config: {}, + secrets: {}, + }, + }) + ).rejects.toMatchInlineSnapshot(`[Error: Unauthorized to create a "my-action-type" action]`); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('create', 'my-action-type'); + }); + }); + test('creates an action with all given properties', async () => { const savedObjectCreateResult = { id: '1', @@ -83,7 +157,7 @@ describe('create()', () => { minimumLicenseRequired: 'basic', executor, }); - savedObjectsClient.create.mockResolvedValueOnce(savedObjectCreateResult); + unsecuredSavedObjectsClient.create.mockResolvedValueOnce(savedObjectCreateResult); const result = await actionsClient.create({ action: { name: 'my name', @@ -99,8 +173,8 @@ describe('create()', () => { actionTypeId: 'my-action-type', config: {}, }); - expect(savedObjectsClient.create).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.create.mock.calls[0]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toMatchInlineSnapshot(` Array [ "action", Object { @@ -161,7 +235,7 @@ describe('create()', () => { minimumLicenseRequired: 'basic', executor, }); - savedObjectsClient.create.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', type: 'type', attributes: { @@ -199,8 +273,8 @@ describe('create()', () => { c: true, }, }); - expect(savedObjectsClient.create).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.create.mock.calls[0]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toMatchInlineSnapshot(` Array [ "action", Object { @@ -237,13 +311,14 @@ describe('create()', () => { actionTypeRegistry = new ActionTypeRegistry(localActionTypeRegistryParams); actionsClient = new ActionsClient({ actionTypeRegistry, - savedObjectsClient, + unsecuredSavedObjectsClient, scopedClusterClient, defaultKibanaIndex, preconfiguredActions: [], actionExecutor, executionEnqueuer, request, + authorization: (authorization as unknown) as ActionsAuthorization, }); const savedObjectCreateResult = { @@ -262,7 +337,7 @@ describe('create()', () => { minimumLicenseRequired: 'basic', executor, }); - savedObjectsClient.create.mockResolvedValueOnce(savedObjectCreateResult); + unsecuredSavedObjectsClient.create.mockResolvedValueOnce(savedObjectCreateResult); await expect( actionsClient.create({ @@ -298,7 +373,7 @@ describe('create()', () => { mockedLicenseState.ensureLicenseForActionType.mockImplementation(() => { throw new Error('Fail'); }); - savedObjectsClient.create.mockResolvedValueOnce(savedObjectCreateResult); + unsecuredSavedObjectsClient.create.mockResolvedValueOnce(savedObjectCreateResult); await expect( actionsClient.create({ action: { @@ -313,8 +388,118 @@ describe('create()', () => { }); describe('get()', () => { - test('calls savedObjectsClient with id', async () => { - savedObjectsClient.get.mockResolvedValueOnce({ + describe('authorization', () => { + test('ensures user is authorised to get the type of action', async () => { + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ + id: '1', + type: 'type', + attributes: { + name: 'my name', + actionTypeId: 'my-action-type', + config: {}, + }, + references: [], + }); + + await actionsClient.get({ id: '1' }); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('get'); + }); + + test('ensures user is authorised to get preconfigured type of action', async () => { + actionsClient = new ActionsClient({ + actionTypeRegistry, + unsecuredSavedObjectsClient, + scopedClusterClient, + defaultKibanaIndex, + actionExecutor, + executionEnqueuer, + request, + authorization: (authorization as unknown) as ActionsAuthorization, + preconfiguredActions: [ + { + id: 'testPreconfigured', + actionTypeId: 'my-action-type', + secrets: { + test: 'test1', + }, + isPreconfigured: true, + name: 'test', + config: { + foo: 'bar', + }, + }, + ], + }); + + await actionsClient.get({ id: 'testPreconfigured' }); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('get'); + }); + + test('throws when user is not authorised to create the type of action', async () => { + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ + id: '1', + type: 'type', + attributes: { + name: 'my name', + actionTypeId: 'my-action-type', + config: {}, + }, + references: [], + }); + + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to get a "my-action-type" action`) + ); + + await expect(actionsClient.get({ id: '1' })).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to get a "my-action-type" action]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('get'); + }); + + test('throws when user is not authorised to create preconfigured of action', async () => { + actionsClient = new ActionsClient({ + actionTypeRegistry, + unsecuredSavedObjectsClient, + scopedClusterClient, + defaultKibanaIndex, + actionExecutor, + executionEnqueuer, + request, + authorization: (authorization as unknown) as ActionsAuthorization, + preconfiguredActions: [ + { + id: 'testPreconfigured', + actionTypeId: 'my-action-type', + secrets: { + test: 'test1', + }, + isPreconfigured: true, + name: 'test', + config: { + foo: 'bar', + }, + }, + ], + }); + + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to get a "my-action-type" action`) + ); + + await expect(actionsClient.get({ id: 'testPreconfigured' })).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to get a "my-action-type" action]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('get'); + }); + }); + + test('calls unsecuredSavedObjectsClient with id', async () => { + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'type', attributes: {}, @@ -325,8 +510,8 @@ describe('get()', () => { id: '1', isPreconfigured: false, }); - expect(savedObjectsClient.get).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(` Array [ "action", "1", @@ -337,12 +522,13 @@ describe('get()', () => { test('return predefined action with id', async () => { actionsClient = new ActionsClient({ actionTypeRegistry, - savedObjectsClient, + unsecuredSavedObjectsClient, scopedClusterClient, defaultKibanaIndex, actionExecutor, executionEnqueuer, request, + authorization: (authorization as unknown) as ActionsAuthorization, preconfiguredActions: [ { id: 'testPreconfigured', @@ -366,12 +552,84 @@ describe('get()', () => { isPreconfigured: true, name: 'test', }); - expect(savedObjectsClient.get).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); }); }); describe('getAll()', () => { - test('calls savedObjectsClient with parameters', async () => { + describe('authorization', () => { + function getAllOperation(): ReturnType { + const expectedResult = { + total: 1, + per_page: 10, + page: 1, + saved_objects: [ + { + id: '1', + type: 'type', + attributes: { + name: 'test', + config: { + foo: 'bar', + }, + }, + score: 1, + references: [], + }, + ], + }; + unsecuredSavedObjectsClient.find.mockResolvedValueOnce(expectedResult); + scopedClusterClient.callAsInternalUser.mockResolvedValueOnce({ + aggregations: { + '1': { doc_count: 6 }, + testPreconfigured: { doc_count: 2 }, + }, + }); + + actionsClient = new ActionsClient({ + actionTypeRegistry, + unsecuredSavedObjectsClient, + scopedClusterClient, + defaultKibanaIndex, + actionExecutor, + executionEnqueuer, + request, + authorization: (authorization as unknown) as ActionsAuthorization, + preconfiguredActions: [ + { + id: 'testPreconfigured', + actionTypeId: '.slack', + secrets: {}, + isPreconfigured: true, + name: 'test', + config: { + foo: 'bar', + }, + }, + ], + }); + return actionsClient.getAll(); + } + + test('ensures user is authorised to get the type of action', async () => { + await getAllOperation(); + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('get'); + }); + + test('throws when user is not authorised to create the type of action', async () => { + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to get all actions`) + ); + + await expect(getAllOperation()).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to get all actions]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('get'); + }); + }); + + test('calls unsecuredSavedObjectsClient with parameters', async () => { const expectedResult = { total: 1, per_page: 10, @@ -391,7 +649,7 @@ describe('getAll()', () => { }, ], }; - savedObjectsClient.find.mockResolvedValueOnce(expectedResult); + unsecuredSavedObjectsClient.find.mockResolvedValueOnce(expectedResult); scopedClusterClient.callAsInternalUser.mockResolvedValueOnce({ aggregations: { '1': { doc_count: 6 }, @@ -401,12 +659,13 @@ describe('getAll()', () => { actionsClient = new ActionsClient({ actionTypeRegistry, - savedObjectsClient, + unsecuredSavedObjectsClient, scopedClusterClient, defaultKibanaIndex, actionExecutor, executionEnqueuer, request, + authorization: (authorization as unknown) as ActionsAuthorization, preconfiguredActions: [ { id: 'testPreconfigured', @@ -443,8 +702,76 @@ describe('getAll()', () => { }); describe('getBulk()', () => { - test('calls getBulk savedObjectsClient with parameters', async () => { - savedObjectsClient.bulkGet.mockResolvedValueOnce({ + describe('authorization', () => { + function getBulkOperation(): ReturnType { + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ + saved_objects: [ + { + id: '1', + type: 'action', + attributes: { + actionTypeId: 'test', + name: 'test', + config: { + foo: 'bar', + }, + }, + references: [], + }, + ], + }); + scopedClusterClient.callAsInternalUser.mockResolvedValueOnce({ + aggregations: { + '1': { doc_count: 6 }, + testPreconfigured: { doc_count: 2 }, + }, + }); + + actionsClient = new ActionsClient({ + actionTypeRegistry, + unsecuredSavedObjectsClient, + scopedClusterClient, + defaultKibanaIndex, + actionExecutor, + executionEnqueuer, + request, + authorization: (authorization as unknown) as ActionsAuthorization, + preconfiguredActions: [ + { + id: 'testPreconfigured', + actionTypeId: '.slack', + secrets: {}, + isPreconfigured: true, + name: 'test', + config: { + foo: 'bar', + }, + }, + ], + }); + return actionsClient.getBulk(['1', 'testPreconfigured']); + } + + test('ensures user is authorised to get the type of action', async () => { + await getBulkOperation(); + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('get'); + }); + + test('throws when user is not authorised to create the type of action', async () => { + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to get all actions`) + ); + + await expect(getBulkOperation()).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to get all actions]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('get'); + }); + }); + + test('calls getBulk unsecuredSavedObjectsClient with parameters', async () => { + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { id: '1', @@ -469,12 +796,13 @@ describe('getBulk()', () => { actionsClient = new ActionsClient({ actionTypeRegistry, - savedObjectsClient, + unsecuredSavedObjectsClient, scopedClusterClient, defaultKibanaIndex, actionExecutor, executionEnqueuer, request, + authorization: (authorization as unknown) as ActionsAuthorization, preconfiguredActions: [ { id: 'testPreconfigured', @@ -514,13 +842,32 @@ describe('getBulk()', () => { }); describe('delete()', () => { - test('calls savedObjectsClient with id', async () => { + describe('authorization', () => { + test('ensures user is authorised to delete actions', async () => { + await actionsClient.delete({ id: '1' }); + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('delete'); + }); + + test('throws when user is not authorised to create the type of action', async () => { + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to delete all actions`) + ); + + await expect(actionsClient.delete({ id: '1' })).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to delete all actions]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('delete'); + }); + }); + + test('calls unsecuredSavedObjectsClient with id', async () => { const expectedResult = Symbol(); - savedObjectsClient.delete.mockResolvedValueOnce(expectedResult); + unsecuredSavedObjectsClient.delete.mockResolvedValueOnce(expectedResult); const result = await actionsClient.delete({ id: '1' }); expect(result).toEqual(expectedResult); - expect(savedObjectsClient.delete).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.delete.mock.calls[0]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.delete.mock.calls[0]).toMatchInlineSnapshot(` Array [ "action", "1", @@ -530,6 +877,60 @@ describe('delete()', () => { }); describe('update()', () => { + describe('authorization', () => { + function updateOperation(): ReturnType { + actionTypeRegistry.register({ + id: 'my-action-type', + name: 'My action type', + minimumLicenseRequired: 'basic', + executor, + }); + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ + id: '1', + type: 'action', + attributes: { + actionTypeId: 'my-action-type', + }, + references: [], + }); + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ + id: 'my-action', + type: 'action', + attributes: { + actionTypeId: 'my-action-type', + name: 'my name', + config: {}, + secrets: {}, + }, + references: [], + }); + return actionsClient.update({ + id: 'my-action', + action: { + name: 'my name', + config: {}, + secrets: {}, + }, + }); + } + test('ensures user is authorised to update actions', async () => { + await updateOperation(); + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('update'); + }); + + test('throws when user is not authorised to create the type of action', async () => { + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to update all actions`) + ); + + await expect(updateOperation()).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to update all actions]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('update'); + }); + }); + test('updates an action with all given properties', async () => { actionTypeRegistry.register({ id: 'my-action-type', @@ -537,7 +938,7 @@ describe('update()', () => { minimumLicenseRequired: 'basic', executor, }); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'action', attributes: { @@ -545,7 +946,7 @@ describe('update()', () => { }, references: [], }); - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: 'my-action', type: 'action', attributes: { @@ -571,8 +972,8 @@ describe('update()', () => { name: 'my name', config: {}, }); - expect(savedObjectsClient.update).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.update.mock.calls[0]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.update.mock.calls[0]).toMatchInlineSnapshot(` Array [ "action", "my-action", @@ -584,8 +985,8 @@ describe('update()', () => { }, ] `); - expect(savedObjectsClient.get).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(` Array [ "action", "my-action", @@ -605,7 +1006,7 @@ describe('update()', () => { }, executor, }); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: 'my-action', type: 'action', attributes: { @@ -634,7 +1035,7 @@ describe('update()', () => { minimumLicenseRequired: 'basic', executor, }); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: 'my-action', type: 'action', attributes: { @@ -642,7 +1043,7 @@ describe('update()', () => { }, references: [], }); - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: 'my-action', type: 'action', attributes: { @@ -680,8 +1081,8 @@ describe('update()', () => { c: true, }, }); - expect(savedObjectsClient.update).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.update.mock.calls[0]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.update.mock.calls[0]).toMatchInlineSnapshot(` Array [ "action", "my-action", @@ -709,7 +1110,7 @@ describe('update()', () => { mockedLicenseState.ensureLicenseForActionType.mockImplementation(() => { throw new Error('Fail'); }); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'action', attributes: { @@ -717,7 +1118,7 @@ describe('update()', () => { }, references: [], }); - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: 'my-action', type: 'action', attributes: { @@ -742,6 +1143,35 @@ describe('update()', () => { }); describe('execute()', () => { + describe('authorization', () => { + test('ensures user is authorised to excecute actions', async () => { + await actionsClient.execute({ + actionId: 'action-id', + params: { + name: 'my name', + }, + }); + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('execute'); + }); + + test('throws when user is not authorised to create the type of action', async () => { + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to execute all actions`) + ); + + await expect( + actionsClient.execute({ + actionId: 'action-id', + params: { + name: 'my name', + }, + }) + ).rejects.toMatchInlineSnapshot(`[Error: Unauthorized to execute all actions]`); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('execute'); + }); + }); + test('calls the actionExecutor with the appropriate parameters', async () => { const actionId = uuid.v4(); actionExecutor.execute.mockResolvedValue({ status: 'ok', actionId }); @@ -765,6 +1195,35 @@ describe('execute()', () => { }); describe('enqueueExecution()', () => { + describe('authorization', () => { + test('ensures user is authorised to excecute actions', async () => { + await actionsClient.enqueueExecution({ + id: uuid.v4(), + params: {}, + spaceId: 'default', + apiKey: null, + }); + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('execute'); + }); + + test('throws when user is not authorised to create the type of action', async () => { + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to execute all actions`) + ); + + await expect( + actionsClient.enqueueExecution({ + id: uuid.v4(), + params: {}, + spaceId: 'default', + apiKey: null, + }) + ).rejects.toMatchInlineSnapshot(`[Error: Unauthorized to execute all actions]`); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('execute'); + }); + }); + test('calls the executionEnqueuer with the appropriate parameters', async () => { const opts = { id: uuid.v4(), @@ -774,6 +1233,6 @@ describe('enqueueExecution()', () => { }; await expect(actionsClient.enqueueExecution(opts)).resolves.toMatchInlineSnapshot(`undefined`); - expect(executionEnqueuer).toHaveBeenCalledWith(savedObjectsClient, opts); + expect(executionEnqueuer).toHaveBeenCalledWith(unsecuredSavedObjectsClient, opts); }); }); diff --git a/x-pack/plugins/actions/server/actions_client.ts b/x-pack/plugins/actions/server/actions_client.ts index 44f9cfd5c9e61..6744a8d111623 100644 --- a/x-pack/plugins/actions/server/actions_client.ts +++ b/x-pack/plugins/actions/server/actions_client.ts @@ -28,6 +28,8 @@ import { ExecutionEnqueuer, ExecuteOptions as EnqueueExecutionOptions, } from './create_execute_function'; +import { ActionsAuthorization } from './authorization/actions_authorization'; +import { ActionType } from '../common'; // We are assuming there won't be many actions. This is why we will load // all the actions in advance and assume the total count to not go over 10000. @@ -52,11 +54,12 @@ interface ConstructorOptions { defaultKibanaIndex: string; scopedClusterClient: ILegacyScopedClusterClient; actionTypeRegistry: ActionTypeRegistry; - savedObjectsClient: SavedObjectsClientContract; + unsecuredSavedObjectsClient: SavedObjectsClientContract; preconfiguredActions: PreConfiguredAction[]; actionExecutor: ActionExecutorContract; executionEnqueuer: ExecutionEnqueuer; request: KibanaRequest; + authorization: ActionsAuthorization; } interface UpdateOptions { @@ -67,45 +70,51 @@ interface UpdateOptions { export class ActionsClient { private readonly defaultKibanaIndex: string; private readonly scopedClusterClient: ILegacyScopedClusterClient; - private readonly savedObjectsClient: SavedObjectsClientContract; + private readonly unsecuredSavedObjectsClient: SavedObjectsClientContract; private readonly actionTypeRegistry: ActionTypeRegistry; private readonly preconfiguredActions: PreConfiguredAction[]; private readonly actionExecutor: ActionExecutorContract; private readonly request: KibanaRequest; + private readonly authorization: ActionsAuthorization; private readonly executionEnqueuer: ExecutionEnqueuer; constructor({ actionTypeRegistry, defaultKibanaIndex, scopedClusterClient, - savedObjectsClient, + unsecuredSavedObjectsClient, preconfiguredActions, actionExecutor, executionEnqueuer, request, + authorization, }: ConstructorOptions) { this.actionTypeRegistry = actionTypeRegistry; - this.savedObjectsClient = savedObjectsClient; + this.unsecuredSavedObjectsClient = unsecuredSavedObjectsClient; this.scopedClusterClient = scopedClusterClient; this.defaultKibanaIndex = defaultKibanaIndex; this.preconfiguredActions = preconfiguredActions; this.actionExecutor = actionExecutor; this.executionEnqueuer = executionEnqueuer; this.request = request; + this.authorization = authorization; } /** * Create an action */ - public async create({ action }: CreateOptions): Promise { - const { actionTypeId, name, config, secrets } = action; + public async create({ + action: { actionTypeId, name, config, secrets }, + }: CreateOptions): Promise { + await this.authorization.ensureAuthorized('create', actionTypeId); + const actionType = this.actionTypeRegistry.get(actionTypeId); const validatedActionTypeConfig = validateConfig(actionType, config); const validatedActionTypeSecrets = validateSecrets(actionType, secrets); this.actionTypeRegistry.ensureActionTypeEnabled(actionTypeId); - const result = await this.savedObjectsClient.create('action', { + const result = await this.unsecuredSavedObjectsClient.create('action', { actionTypeId, name, config: validatedActionTypeConfig as SavedObjectAttributes, @@ -125,6 +134,8 @@ export class ActionsClient { * Update action */ public async update({ id, action }: UpdateOptions): Promise { + await this.authorization.ensureAuthorized('update'); + if ( this.preconfiguredActions.find((preconfiguredAction) => preconfiguredAction.id === id) !== undefined @@ -139,7 +150,7 @@ export class ActionsClient { 'update' ); } - const existingObject = await this.savedObjectsClient.get('action', id); + const existingObject = await this.unsecuredSavedObjectsClient.get('action', id); const { actionTypeId } = existingObject.attributes; const { name, config, secrets } = action; const actionType = this.actionTypeRegistry.get(actionTypeId); @@ -148,7 +159,7 @@ export class ActionsClient { this.actionTypeRegistry.ensureActionTypeEnabled(actionTypeId); - const result = await this.savedObjectsClient.update('action', id, { + const result = await this.unsecuredSavedObjectsClient.update('action', id, { actionTypeId, name, config: validatedActionTypeConfig as SavedObjectAttributes, @@ -168,6 +179,8 @@ export class ActionsClient { * Get an action */ public async get({ id }: { id: string }): Promise { + await this.authorization.ensureAuthorized('get'); + const preconfiguredActionsList = this.preconfiguredActions.find( (preconfiguredAction) => preconfiguredAction.id === id ); @@ -179,7 +192,7 @@ export class ActionsClient { isPreconfigured: true, }; } - const result = await this.savedObjectsClient.get('action', id); + const result = await this.unsecuredSavedObjectsClient.get('action', id); return { id, @@ -194,8 +207,10 @@ export class ActionsClient { * Get all actions with preconfigured list */ public async getAll(): Promise { + await this.authorization.ensureAuthorized('get'); + const savedObjectsActions = ( - await this.savedObjectsClient.find({ + await this.unsecuredSavedObjectsClient.find({ perPage: MAX_ACTIONS_RETURNED, type: 'action', }) @@ -221,6 +236,8 @@ export class ActionsClient { * Get bulk actions with preconfigured list */ public async getBulk(ids: string[]): Promise { + await this.authorization.ensureAuthorized('get'); + const actionResults = new Array(); for (const actionId of ids) { const action = this.preconfiguredActions.find( @@ -242,7 +259,7 @@ export class ActionsClient { ]; const bulkGetOpts = actionSavedObjectsIds.map((id) => ({ id, type: 'action' })); - const bulkGetResult = await this.savedObjectsClient.bulkGet(bulkGetOpts); + const bulkGetResult = await this.unsecuredSavedObjectsClient.bulkGet(bulkGetOpts); for (const action of bulkGetResult.saved_objects) { if (action.error) { @@ -259,6 +276,8 @@ export class ActionsClient { * Delete action */ public async delete({ id }: { id: string }) { + await this.authorization.ensureAuthorized('delete'); + if ( this.preconfiguredActions.find((preconfiguredAction) => preconfiguredAction.id === id) !== undefined @@ -273,18 +292,24 @@ export class ActionsClient { 'delete' ); } - return await this.savedObjectsClient.delete('action', id); + return await this.unsecuredSavedObjectsClient.delete('action', id); } public async execute({ actionId, params, }: Omit): Promise { + await this.authorization.ensureAuthorized('execute'); return this.actionExecutor.execute({ actionId, params, request: this.request }); } public async enqueueExecution(options: EnqueueExecutionOptions): Promise { - return this.executionEnqueuer(this.savedObjectsClient, options); + await this.authorization.ensureAuthorized('execute'); + return this.executionEnqueuer(this.unsecuredSavedObjectsClient, options); + } + + public async listTypes(): Promise { + return this.actionTypeRegistry.list(); } } diff --git a/x-pack/plugins/actions/server/authorization/actions_authorization.mock.ts b/x-pack/plugins/actions/server/authorization/actions_authorization.mock.ts new file mode 100644 index 0000000000000..6b55c18241c55 --- /dev/null +++ b/x-pack/plugins/actions/server/authorization/actions_authorization.mock.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ActionsAuthorization } from './actions_authorization'; + +export type ActionsAuthorizationMock = jest.Mocked>; + +const createActionsAuthorizationMock = () => { + const mocked: ActionsAuthorizationMock = { + ensureAuthorized: jest.fn(), + }; + return mocked; +}; + +export const actionsAuthorizationMock: { + create: () => ActionsAuthorizationMock; +} = { + create: createActionsAuthorizationMock, +}; diff --git a/x-pack/plugins/actions/server/authorization/actions_authorization.test.ts b/x-pack/plugins/actions/server/authorization/actions_authorization.test.ts new file mode 100644 index 0000000000000..a48124cdbcb6a --- /dev/null +++ b/x-pack/plugins/actions/server/authorization/actions_authorization.test.ts @@ -0,0 +1,191 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { KibanaRequest } from 'kibana/server'; +import { securityMock } from '../../../../plugins/security/server/mocks'; +import { ActionsAuthorization } from './actions_authorization'; +import { actionsAuthorizationAuditLoggerMock } from './audit_logger.mock'; +import { ActionsAuthorizationAuditLogger, AuthorizationResult } from './audit_logger'; +import { ACTION_SAVED_OBJECT_TYPE, ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE } from '../saved_objects'; + +const request = {} as KibanaRequest; + +const auditLogger = actionsAuthorizationAuditLoggerMock.create(); +const realAuditLogger = new ActionsAuthorizationAuditLogger(); + +const mockAuthorizationAction = (type: string, operation: string) => `${type}/${operation}`; +function mockSecurity() { + const security = securityMock.createSetup(); + const authorization = security.authz; + // typescript is having trouble inferring jest's automocking + (authorization.actions.savedObject.get as jest.MockedFunction< + typeof authorization.actions.savedObject.get + >).mockImplementation(mockAuthorizationAction); + authorization.mode.useRbacForRequest.mockReturnValue(true); + return { authorization }; +} + +beforeEach(() => { + jest.resetAllMocks(); + auditLogger.actionsAuthorizationFailure.mockImplementation((username, ...args) => + realAuditLogger.getAuthorizationMessage(AuthorizationResult.Unauthorized, ...args) + ); + auditLogger.actionsAuthorizationSuccess.mockImplementation((username, ...args) => + realAuditLogger.getAuthorizationMessage(AuthorizationResult.Authorized, ...args) + ); +}); + +describe('ensureAuthorized', () => { + test('is a no-op when there is no authorization api', async () => { + const actionsAuthorization = new ActionsAuthorization({ + request, + auditLogger, + }); + + await actionsAuthorization.ensureAuthorized('create', 'myType'); + }); + + test('is a no-op when the security license is disabled', async () => { + const { authorization } = mockSecurity(); + authorization.mode.useRbacForRequest.mockReturnValue(false); + const actionsAuthorization = new ActionsAuthorization({ + request, + authorization, + auditLogger, + }); + + await actionsAuthorization.ensureAuthorized('create', 'myType'); + }); + + test('ensures the user has privileges to use the operation on the Actions Saved Object type', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + const actionsAuthorization = new ActionsAuthorization({ + request, + authorization, + auditLogger, + }); + + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: true, + privileges: [ + { + privilege: mockAuthorizationAction('myType', 'create'), + authorized: true, + }, + ], + }); + + await actionsAuthorization.ensureAuthorized('create', 'myType'); + + expect(authorization.actions.savedObject.get).toHaveBeenCalledWith('action', 'create'); + expect(checkPrivileges).toHaveBeenCalledWith(mockAuthorizationAction('action', 'create')); + + expect(auditLogger.actionsAuthorizationSuccess).toHaveBeenCalledTimes(1); + expect(auditLogger.actionsAuthorizationFailure).not.toHaveBeenCalled(); + expect(auditLogger.actionsAuthorizationSuccess.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "some-user", + "create", + "myType", + ] + `); + }); + + test('ensures the user has privileges to execute an Actions Saved Object type', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + const actionsAuthorization = new ActionsAuthorization({ + request, + authorization, + auditLogger, + }); + + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: true, + privileges: [ + { + privilege: mockAuthorizationAction('myType', 'execute'), + authorized: true, + }, + ], + }); + + await actionsAuthorization.ensureAuthorized('execute', 'myType'); + + expect(authorization.actions.savedObject.get).toHaveBeenCalledWith( + ACTION_SAVED_OBJECT_TYPE, + 'get' + ); + expect(authorization.actions.savedObject.get).toHaveBeenCalledWith( + ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, + 'create' + ); + expect(checkPrivileges).toHaveBeenCalledWith([ + mockAuthorizationAction(ACTION_SAVED_OBJECT_TYPE, 'get'), + mockAuthorizationAction(ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, 'create'), + ]); + + expect(auditLogger.actionsAuthorizationSuccess).toHaveBeenCalledTimes(1); + expect(auditLogger.actionsAuthorizationFailure).not.toHaveBeenCalled(); + expect(auditLogger.actionsAuthorizationSuccess.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "some-user", + "execute", + "myType", + ] + `); + }); + + test('throws if user lacks the required privieleges', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + const actionsAuthorization = new ActionsAuthorization({ + request, + authorization, + auditLogger, + }); + + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: false, + privileges: [ + { + privilege: mockAuthorizationAction('myType', 'create'), + authorized: false, + }, + { + privilege: mockAuthorizationAction('myOtherType', 'create'), + authorized: true, + }, + ], + }); + + await expect( + actionsAuthorization.ensureAuthorized('create', 'myType') + ).rejects.toThrowErrorMatchingInlineSnapshot(`"Unauthorized to create a \\"myType\\" action"`); + + expect(auditLogger.actionsAuthorizationSuccess).not.toHaveBeenCalled(); + expect(auditLogger.actionsAuthorizationFailure).toHaveBeenCalledTimes(1); + expect(auditLogger.actionsAuthorizationFailure.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "some-user", + "create", + "myType", + ] + `); + }); +}); diff --git a/x-pack/plugins/actions/server/authorization/actions_authorization.ts b/x-pack/plugins/actions/server/authorization/actions_authorization.ts new file mode 100644 index 0000000000000..da5a5a1cdc3eb --- /dev/null +++ b/x-pack/plugins/actions/server/authorization/actions_authorization.ts @@ -0,0 +1,59 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import Boom from 'boom'; +import { KibanaRequest } from 'src/core/server'; +import { SecurityPluginSetup } from '../../../security/server'; +import { ActionsAuthorizationAuditLogger } from './audit_logger'; +import { ACTION_SAVED_OBJECT_TYPE, ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE } from '../saved_objects'; + +export interface ConstructorOptions { + request: KibanaRequest; + auditLogger: ActionsAuthorizationAuditLogger; + authorization?: SecurityPluginSetup['authz']; +} + +const operationAlias: Record< + string, + (authorization: SecurityPluginSetup['authz']) => string | string[] +> = { + execute: (authorization) => [ + authorization.actions.savedObject.get(ACTION_SAVED_OBJECT_TYPE, 'get'), + authorization.actions.savedObject.get(ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, 'create'), + ], + list: (authorization) => authorization.actions.savedObject.get(ACTION_SAVED_OBJECT_TYPE, 'find'), +}; + +export class ActionsAuthorization { + private readonly request: KibanaRequest; + private readonly authorization?: SecurityPluginSetup['authz']; + private readonly auditLogger: ActionsAuthorizationAuditLogger; + + constructor({ request, authorization, auditLogger }: ConstructorOptions) { + this.request = request; + this.authorization = authorization; + this.auditLogger = auditLogger; + } + + public async ensureAuthorized(operation: string, actionTypeId?: string) { + const { authorization } = this; + if (authorization?.mode?.useRbacForRequest(this.request)) { + const checkPrivileges = authorization.checkPrivilegesDynamicallyWithRequest(this.request); + const { hasAllRequested, username } = await checkPrivileges( + operationAlias[operation] + ? operationAlias[operation](authorization) + : authorization.actions.savedObject.get(ACTION_SAVED_OBJECT_TYPE, operation) + ); + if (hasAllRequested) { + this.auditLogger.actionsAuthorizationSuccess(username, operation, actionTypeId); + } else { + throw Boom.forbidden( + this.auditLogger.actionsAuthorizationFailure(username, operation, actionTypeId) + ); + } + } + } +} diff --git a/x-pack/plugins/actions/server/authorization/audit_logger.mock.ts b/x-pack/plugins/actions/server/authorization/audit_logger.mock.ts new file mode 100644 index 0000000000000..95d4f4ebcd3aa --- /dev/null +++ b/x-pack/plugins/actions/server/authorization/audit_logger.mock.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ActionsAuthorizationAuditLogger } from './audit_logger'; + +const createActionsAuthorizationAuditLoggerMock = () => { + const mocked = ({ + getAuthorizationMessage: jest.fn(), + actionsAuthorizationFailure: jest.fn(), + actionsAuthorizationSuccess: jest.fn(), + } as unknown) as jest.Mocked; + return mocked; +}; + +export const actionsAuthorizationAuditLoggerMock: { + create: () => jest.Mocked; +} = { + create: createActionsAuthorizationAuditLoggerMock, +}; diff --git a/x-pack/plugins/actions/server/authorization/audit_logger.test.ts b/x-pack/plugins/actions/server/authorization/audit_logger.test.ts new file mode 100644 index 0000000000000..d700abdaa70ff --- /dev/null +++ b/x-pack/plugins/actions/server/authorization/audit_logger.test.ts @@ -0,0 +1,75 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { ActionsAuthorizationAuditLogger } from './audit_logger'; + +const createMockAuditLogger = () => { + return { + log: jest.fn(), + }; +}; + +describe(`#constructor`, () => { + test('initializes a noop auditLogger if security logger is unavailable', () => { + const actionsAuditLogger = new ActionsAuthorizationAuditLogger(undefined); + + const username = 'foo-user'; + const actionTypeId = 'action-type-id'; + const operation = 'create'; + expect(() => { + actionsAuditLogger.actionsAuthorizationFailure(username, operation, actionTypeId); + actionsAuditLogger.actionsAuthorizationSuccess(username, operation, actionTypeId); + }).not.toThrow(); + }); +}); + +describe(`#actionsAuthorizationFailure`, () => { + test('logs auth failure', () => { + const auditLogger = createMockAuditLogger(); + const actionsAuditLogger = new ActionsAuthorizationAuditLogger(auditLogger); + const username = 'foo-user'; + const actionTypeId = 'action-type-id'; + const operation = 'create'; + + actionsAuditLogger.actionsAuthorizationFailure(username, operation, actionTypeId); + + expect(auditLogger.log.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "actions_authorization_failure", + "foo-user Unauthorized to create a \\"action-type-id\\" action", + Object { + "actionTypeId": "action-type-id", + "operation": "create", + "username": "foo-user", + }, + ] + `); + }); +}); + +describe(`#savedObjectsAuthorizationSuccess`, () => { + test('logs auth success', () => { + const auditLogger = createMockAuditLogger(); + const actionsAuditLogger = new ActionsAuthorizationAuditLogger(auditLogger); + const username = 'foo-user'; + const actionTypeId = 'action-type-id'; + + const operation = 'create'; + + actionsAuditLogger.actionsAuthorizationSuccess(username, operation, actionTypeId); + + expect(auditLogger.log.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "actions_authorization_success", + "foo-user Authorized to create a \\"action-type-id\\" action", + Object { + "actionTypeId": "action-type-id", + "operation": "create", + "username": "foo-user", + }, + ] + `); + }); +}); diff --git a/x-pack/plugins/actions/server/authorization/audit_logger.ts b/x-pack/plugins/actions/server/authorization/audit_logger.ts new file mode 100644 index 0000000000000..7e0adc9206656 --- /dev/null +++ b/x-pack/plugins/actions/server/authorization/audit_logger.ts @@ -0,0 +1,66 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { AuditLogger } from '../../../security/server'; + +export enum AuthorizationResult { + Unauthorized = 'Unauthorized', + Authorized = 'Authorized', +} + +export class ActionsAuthorizationAuditLogger { + private readonly auditLogger: AuditLogger; + + constructor(auditLogger: AuditLogger = { log() {} }) { + this.auditLogger = auditLogger; + } + + public getAuthorizationMessage( + authorizationResult: AuthorizationResult, + operation: string, + actionTypeId?: string + ): string { + return `${authorizationResult} to ${operation} ${ + actionTypeId ? `a "${actionTypeId}" action` : `actions` + }`; + } + + public actionsAuthorizationFailure( + username: string, + operation: string, + actionTypeId?: string + ): string { + const message = this.getAuthorizationMessage( + AuthorizationResult.Unauthorized, + operation, + actionTypeId + ); + this.auditLogger.log('actions_authorization_failure', `${username} ${message}`, { + username, + actionTypeId, + operation, + }); + return message; + } + + public actionsAuthorizationSuccess( + username: string, + operation: string, + actionTypeId?: string + ): string { + const message = this.getAuthorizationMessage( + AuthorizationResult.Authorized, + operation, + actionTypeId + ); + this.auditLogger.log('actions_authorization_success', `${username} ${message}`, { + username, + actionTypeId, + operation, + }); + return message; + } +} diff --git a/x-pack/plugins/actions/server/create_execute_function.ts b/x-pack/plugins/actions/server/create_execute_function.ts index 2bad33d56f228..85052eef93e05 100644 --- a/x-pack/plugins/actions/server/create_execute_function.ts +++ b/x-pack/plugins/actions/server/create_execute_function.ts @@ -7,6 +7,7 @@ import { SavedObjectsClientContract } from '../../../../src/core/server'; import { TaskManagerStartContract } from '../../task_manager/server'; import { RawAction, ActionTypeRegistryContract, PreConfiguredAction } from './types'; +import { ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE } from './saved_objects'; interface CreateExecuteFunctionOptions { taskManager: TaskManagerStartContract; @@ -49,11 +50,14 @@ export function createExecutionEnqueuerFunction({ actionTypeRegistry.ensureActionTypeEnabled(actionTypeId); } - const actionTaskParamsRecord = await savedObjectsClient.create('action_task_params', { - actionId: id, - params, - apiKey, - }); + const actionTaskParamsRecord = await savedObjectsClient.create( + ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, + { + actionId: id, + params, + apiKey, + } + ); await taskManager.schedule({ taskType: `actions:${actionTypeId}`, diff --git a/x-pack/plugins/actions/server/feature.ts b/x-pack/plugins/actions/server/feature.ts new file mode 100644 index 0000000000000..321509a7b9de6 --- /dev/null +++ b/x-pack/plugins/actions/server/feature.ts @@ -0,0 +1,50 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; +import { ACTION_SAVED_OBJECT_TYPE, ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE } from './saved_objects'; + +export const ACTIONS_FEATURE = { + id: 'actions', + name: i18n.translate('xpack.actions.featureRegistry.actionsFeatureName', { + defaultMessage: 'Actions', + }), + icon: 'bell', + navLinkId: 'actions', + app: [], + management: { + insightsAndAlerting: ['triggersActions'], + }, + privileges: { + all: { + app: [], + api: [], + catalogue: [], + management: { + insightsAndAlerting: ['triggersActions'], + }, + savedObject: { + all: [ACTION_SAVED_OBJECT_TYPE, ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE], + read: [], + }, + ui: ['show', 'execute', 'save', 'delete'], + }, + read: { + app: [], + api: [], + catalogue: [], + management: { + insightsAndAlerting: ['triggersActions'], + }, + savedObject: { + // action execution requires 'read' over `actions`, but 'all' over `action_task_params` + all: [ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE], + read: [ACTION_SAVED_OBJECT_TYPE], + }, + ui: ['show', 'execute'], + }, + }, +}; diff --git a/x-pack/plugins/actions/server/index.ts b/x-pack/plugins/actions/server/index.ts index 88553c314112f..fef70c3a48455 100644 --- a/x-pack/plugins/actions/server/index.ts +++ b/x-pack/plugins/actions/server/index.ts @@ -8,8 +8,10 @@ import { PluginInitializerContext } from '../../../../src/core/server'; import { ActionsPlugin } from './plugin'; import { configSchema } from './config'; import { ActionsClient as ActionsClientClass } from './actions_client'; +import { ActionsAuthorization as ActionsAuthorizationClass } from './authorization/actions_authorization'; export type ActionsClient = PublicMethodsOf; +export type ActionsAuthorization = PublicMethodsOf; export { ActionsPlugin, diff --git a/x-pack/plugins/actions/server/lib/action_executor.test.ts b/x-pack/plugins/actions/server/lib/action_executor.test.ts index c8e6669275e11..65fd0646c639e 100644 --- a/x-pack/plugins/actions/server/lib/action_executor.test.ts +++ b/x-pack/plugins/actions/server/lib/action_executor.test.ts @@ -9,15 +9,17 @@ import { schema } from '@kbn/config-schema'; import { ActionExecutor } from './action_executor'; import { actionTypeRegistryMock } from '../action_type_registry.mock'; import { encryptedSavedObjectsMock } from '../../../encrypted_saved_objects/server/mocks'; -import { loggingSystemMock, savedObjectsClientMock } from '../../../../../src/core/server/mocks'; +import { loggingSystemMock } from '../../../../../src/core/server/mocks'; import { eventLoggerMock } from '../../../event_log/server/mocks'; import { spacesServiceMock } from '../../../spaces/server/spaces_service/spaces_service.mock'; import { ActionType } from '../types'; -import { actionsMock } from '../mocks'; +import { actionsMock, actionsClientMock } from '../mocks'; +import { pick } from 'lodash'; const actionExecutor = new ActionExecutor({ isESOUsingEphemeralEncryptionKey: false }); const services = actionsMock.createServices(); -const savedObjectsClientWithHidden = savedObjectsClientMock.create(); + +const actionsClient = actionsClientMock.create(); const encryptedSavedObjectsClient = encryptedSavedObjectsMock.createClient(); const actionTypeRegistry = actionTypeRegistryMock.create(); @@ -30,11 +32,12 @@ const executeParams = { }; const spacesMock = spacesServiceMock.createSetupContract(); +const getActionsClientWithRequest = jest.fn(); actionExecutor.initialize({ logger: loggingSystemMock.create().get(), spaces: spacesMock, getServices: () => services, - getScopedSavedObjectsClient: () => savedObjectsClientWithHidden, + getActionsClientWithRequest, actionTypeRegistry, encryptedSavedObjectsClient, eventLogger: eventLoggerMock.create(), @@ -44,6 +47,7 @@ actionExecutor.initialize({ beforeEach(() => { jest.resetAllMocks(); spacesMock.getSpaceId.mockReturnValue('some-namespace'); + getActionsClientWithRequest.mockResolvedValue(actionsClient); }); test('successfully executes', async () => { @@ -67,7 +71,13 @@ test('successfully executes', async () => { }, references: [], }; - savedObjectsClientWithHidden.get.mockResolvedValueOnce(actionSavedObject); + const actionResult = { + id: actionSavedObject.id, + name: actionSavedObject.id, + ...pick(actionSavedObject.attributes, 'actionTypeId', 'config'), + isPreconfigured: false, + }; + actionsClient.get.mockResolvedValueOnce(actionResult); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce(actionSavedObject); actionTypeRegistry.get.mockReturnValueOnce(actionType); await actionExecutor.execute(executeParams); @@ -108,7 +118,13 @@ test('provides empty config when config and / or secrets is empty', async () => }, references: [], }; - savedObjectsClientWithHidden.get.mockResolvedValueOnce(actionSavedObject); + const actionResult = { + id: actionSavedObject.id, + name: actionSavedObject.id, + actionTypeId: actionSavedObject.attributes.actionTypeId, + isPreconfigured: false, + }; + actionsClient.get.mockResolvedValueOnce(actionResult); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce(actionSavedObject); actionTypeRegistry.get.mockReturnValueOnce(actionType); await actionExecutor.execute(executeParams); @@ -138,7 +154,13 @@ test('throws an error when config is invalid', async () => { }, references: [], }; - savedObjectsClientWithHidden.get.mockResolvedValueOnce(actionSavedObject); + const actionResult = { + id: actionSavedObject.id, + name: actionSavedObject.id, + actionTypeId: actionSavedObject.attributes.actionTypeId, + isPreconfigured: false, + }; + actionsClient.get.mockResolvedValueOnce(actionResult); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce(actionSavedObject); actionTypeRegistry.get.mockReturnValueOnce(actionType); @@ -171,7 +193,13 @@ test('throws an error when params is invalid', async () => { }, references: [], }; - savedObjectsClientWithHidden.get.mockResolvedValueOnce(actionSavedObject); + const actionResult = { + id: actionSavedObject.id, + name: actionSavedObject.id, + actionTypeId: actionSavedObject.attributes.actionTypeId, + isPreconfigured: false, + }; + actionsClient.get.mockResolvedValueOnce(actionResult); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce(actionSavedObject); actionTypeRegistry.get.mockReturnValueOnce(actionType); @@ -185,7 +213,7 @@ test('throws an error when params is invalid', async () => { }); test('throws an error when failing to load action through savedObjectsClient', async () => { - savedObjectsClientWithHidden.get.mockRejectedValueOnce(new Error('No access')); + actionsClient.get.mockRejectedValueOnce(new Error('No access')); await expect(actionExecutor.execute(executeParams)).rejects.toThrowErrorMatchingInlineSnapshot( `"No access"` ); @@ -206,7 +234,13 @@ test('throws an error if actionType is not enabled', async () => { }, references: [], }; - savedObjectsClientWithHidden.get.mockResolvedValueOnce(actionSavedObject); + const actionResult = { + id: actionSavedObject.id, + name: actionSavedObject.id, + actionTypeId: actionSavedObject.attributes.actionTypeId, + isPreconfigured: false, + }; + actionsClient.get.mockResolvedValueOnce(actionResult); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce(actionSavedObject); actionTypeRegistry.get.mockReturnValueOnce(actionType); actionTypeRegistry.ensureActionTypeEnabled.mockImplementationOnce(() => { @@ -240,7 +274,13 @@ test('should not throws an error if actionType is preconfigured', async () => { }, references: [], }; - savedObjectsClientWithHidden.get.mockResolvedValueOnce(actionSavedObject); + const actionResult = { + id: actionSavedObject.id, + name: actionSavedObject.id, + ...pick(actionSavedObject.attributes, 'actionTypeId', 'config', 'secrets'), + isPreconfigured: false, + }; + actionsClient.get.mockResolvedValueOnce(actionResult); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce(actionSavedObject); actionTypeRegistry.get.mockReturnValueOnce(actionType); actionTypeRegistry.ensureActionTypeEnabled.mockImplementationOnce(() => { @@ -268,7 +308,7 @@ test('throws an error when passing isESOUsingEphemeralEncryptionKey with value o customActionExecutor.initialize({ logger: loggingSystemMock.create().get(), spaces: spacesMock, - getScopedSavedObjectsClient: () => savedObjectsClientWithHidden, + getActionsClientWithRequest, getServices: () => services, actionTypeRegistry, encryptedSavedObjectsClient, diff --git a/x-pack/plugins/actions/server/lib/action_executor.ts b/x-pack/plugins/actions/server/lib/action_executor.ts index 250bfc2752f1b..0e63cc8f5956e 100644 --- a/x-pack/plugins/actions/server/lib/action_executor.ts +++ b/x-pack/plugins/actions/server/lib/action_executor.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Logger, KibanaRequest, SavedObjectsClientContract } from '../../../../../src/core/server'; +import { Logger, KibanaRequest } from '../../../../../src/core/server'; import { validateParams, validateConfig, validateSecrets } from './validate_with_schema'; import { ActionTypeExecutorResult, @@ -15,14 +15,15 @@ import { } from '../types'; import { EncryptedSavedObjectsClient } from '../../../encrypted_saved_objects/server'; import { SpacesServiceSetup } from '../../../spaces/server'; -import { EVENT_LOG_ACTIONS } from '../plugin'; +import { EVENT_LOG_ACTIONS, PluginStartContract } from '../plugin'; import { IEvent, IEventLogger, SAVED_OBJECT_REL_PRIMARY } from '../../../event_log/server'; +import { ActionsClient } from '../actions_client'; export interface ActionExecutorContext { logger: Logger; spaces?: SpacesServiceSetup; getServices: GetServicesFunction; - getScopedSavedObjectsClient: (req: KibanaRequest) => SavedObjectsClientContract; + getActionsClientWithRequest: PluginStartContract['getActionsClientWithRequest']; encryptedSavedObjectsClient: EncryptedSavedObjectsClient; actionTypeRegistry: ActionTypeRegistryContract; eventLogger: IEventLogger; @@ -76,7 +77,7 @@ export class ActionExecutor { actionTypeRegistry, eventLogger, preconfiguredActions, - getScopedSavedObjectsClient, + getActionsClientWithRequest, } = this.actionExecutorContext!; const services = getServices(request); @@ -84,7 +85,7 @@ export class ActionExecutor { const namespace = spaceId && spaceId !== 'default' ? { namespace: spaceId } : {}; const { actionTypeId, name, config, secrets } = await getActionInfo( - getScopedSavedObjectsClient(request), + await getActionsClientWithRequest(request), encryptedSavedObjectsClient, preconfiguredActions, actionId, @@ -196,7 +197,7 @@ interface ActionInfo { } async function getActionInfo( - savedObjectsClient: SavedObjectsClientContract, + actionsClient: PublicMethodsOf, encryptedSavedObjectsClient: EncryptedSavedObjectsClient, preconfiguredActions: PreConfiguredAction[], actionId: string, @@ -217,9 +218,7 @@ async function getActionInfo( // if not pre-configured action, should be a saved object // ensure user can read the action before processing - const { - attributes: { actionTypeId, config, name }, - } = await savedObjectsClient.get('action', actionId); + const { actionTypeId, config, name } = await actionsClient.get({ id: actionId }); const { attributes: { secrets }, diff --git a/x-pack/plugins/actions/server/lib/task_runner_factory.test.ts b/x-pack/plugins/actions/server/lib/task_runner_factory.test.ts index 06cb84ad79a89..78522682054e1 100644 --- a/x-pack/plugins/actions/server/lib/task_runner_factory.test.ts +++ b/x-pack/plugins/actions/server/lib/task_runner_factory.test.ts @@ -15,6 +15,7 @@ import { encryptedSavedObjectsMock } from '../../../encrypted_saved_objects/serv import { savedObjectsClientMock, loggingSystemMock } from 'src/core/server/mocks'; import { eventLoggerMock } from '../../../event_log/server/mocks'; import { ActionTypeDisabledError } from './errors'; +import { actionsClientMock } from '../mocks'; const spaceIdToNamespace = jest.fn(); const actionTypeRegistry = actionTypeRegistryMock.create(); @@ -59,7 +60,7 @@ const actionExecutorInitializerParams = { logger: loggingSystemMock.create().get(), getServices: jest.fn().mockReturnValue(services), actionTypeRegistry, - getScopedSavedObjectsClient: () => savedObjectsClientMock.create(), + getActionsClientWithRequest: jest.fn(async () => actionsClientMock.create()), encryptedSavedObjectsClient: mockedEncryptedSavedObjectsClient, eventLogger: eventLoggerMock.create(), preconfiguredActions: [], diff --git a/x-pack/plugins/actions/server/lib/task_runner_factory.ts b/x-pack/plugins/actions/server/lib/task_runner_factory.ts index a962497f906a9..9204c41b9288c 100644 --- a/x-pack/plugins/actions/server/lib/task_runner_factory.ts +++ b/x-pack/plugins/actions/server/lib/task_runner_factory.ts @@ -17,6 +17,7 @@ import { SpaceIdToNamespaceFunction, ActionTypeExecutorResult, } from '../types'; +import { ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE } from '../saved_objects'; export interface TaskRunnerContext { logger: Logger; @@ -66,7 +67,7 @@ export class TaskRunnerFactory { const { attributes: { actionId, params, apiKey }, } = await encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'action_task_params', + ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, actionTaskParamsId, { namespace } ); @@ -121,11 +122,11 @@ export class TaskRunnerFactory { // Cleanup action_task_params object now that we're done with it try { const savedObjectsClient = getScopedSavedObjectsClient(fakeRequest); - await savedObjectsClient.delete('action_task_params', actionTaskParamsId); + await savedObjectsClient.delete(ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, actionTaskParamsId); } catch (e) { // Log error only, we shouldn't fail the task because of an error here (if ever there's retry logic) logger.error( - `Failed to cleanup action_task_params object [id="${actionTaskParamsId}"]: ${e.message}` + `Failed to cleanup ${ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE} object [id="${actionTaskParamsId}"]: ${e.message}` ); } }, diff --git a/x-pack/plugins/actions/server/mocks.ts b/x-pack/plugins/actions/server/mocks.ts index b1e40dce811a0..e2f11abeefff2 100644 --- a/x-pack/plugins/actions/server/mocks.ts +++ b/x-pack/plugins/actions/server/mocks.ts @@ -11,7 +11,9 @@ import { elasticsearchServiceMock, savedObjectsClientMock, } from '../../../../src/core/server/mocks'; +import { actionsAuthorizationMock } from './authorization/actions_authorization.mock'; +export { actionsAuthorizationMock }; export { actionsClientMock }; const createSetupMock = () => { @@ -26,6 +28,9 @@ const createStartMock = () => { isActionTypeEnabled: jest.fn(), isActionExecutable: jest.fn(), getActionsClientWithRequest: jest.fn().mockResolvedValue(actionsClientMock.create()), + getActionsAuthorizationWithRequest: jest + .fn() + .mockReturnValue(actionsAuthorizationMock.create()), preconfiguredActions: [], }; return mock; diff --git a/x-pack/plugins/actions/server/plugin.test.ts b/x-pack/plugins/actions/server/plugin.test.ts index 1602b26559bed..ac4b332e7fd7a 100644 --- a/x-pack/plugins/actions/server/plugin.test.ts +++ b/x-pack/plugins/actions/server/plugin.test.ts @@ -8,6 +8,7 @@ import { PluginInitializerContext, RequestHandlerContext } from '../../../../src import { coreMock, httpServerMock } from '../../../../src/core/server/mocks'; import { usageCollectionPluginMock } from '../../../../src/plugins/usage_collection/server/mocks'; import { licensingMock } from '../../licensing/server/mocks'; +import { featuresPluginMock } from '../../features/server/mocks'; import { encryptedSavedObjectsMock } from '../../encrypted_saved_objects/server/mocks'; import { taskManagerMock } from '../../task_manager/server/mocks'; import { eventLogMock } from '../../event_log/server/mocks'; @@ -43,6 +44,7 @@ describe('Actions Plugin', () => { licensing: licensingMock.createSetup(), eventLog: eventLogMock.createSetup(), usageCollection: usageCollectionPluginMock.createSetupContract(), + features: featuresPluginMock.createSetup(), }; }); @@ -200,6 +202,7 @@ describe('Actions Plugin', () => { licensing: licensingMock.createSetup(), eventLog: eventLogMock.createSetup(), usageCollection: usageCollectionPluginMock.createSetupContract(), + features: featuresPluginMock.createSetup(), }; pluginsStart = { taskManager: taskManagerMock.createStart(), diff --git a/x-pack/plugins/actions/server/plugin.ts b/x-pack/plugins/actions/server/plugin.ts index 114c85ae9f9da..5b8b25d02658b 100644 --- a/x-pack/plugins/actions/server/plugin.ts +++ b/x-pack/plugins/actions/server/plugin.ts @@ -29,6 +29,8 @@ import { TaskManagerSetupContract, TaskManagerStartContract } from '../../task_m import { LicensingPluginSetup } from '../../licensing/server'; import { LICENSE_TYPE } from '../../licensing/common/types'; import { SpacesPluginSetup, SpacesServiceSetup } from '../../spaces/server'; +import { PluginSetupContract as FeaturesPluginSetup } from '../../features/server'; +import { SecurityPluginSetup } from '../../security/server'; import { ActionsConfig } from './config'; import { Services, ActionType, PreConfiguredAction } from './types'; @@ -52,7 +54,14 @@ import { } from './routes'; import { IEventLogger, IEventLogService } from '../../event_log/server'; import { initializeActionsTelemetry, scheduleActionsTelemetry } from './usage/task'; -import { setupSavedObjects } from './saved_objects'; +import { + setupSavedObjects, + ACTION_SAVED_OBJECT_TYPE, + ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, +} from './saved_objects'; +import { ACTIONS_FEATURE } from './feature'; +import { ActionsAuthorization } from './authorization/actions_authorization'; +import { ActionsAuthorizationAuditLogger } from './authorization/audit_logger'; const EVENT_LOG_PROVIDER = 'actions'; export const EVENT_LOG_ACTIONS = { @@ -68,6 +77,7 @@ export interface PluginStartContract { isActionTypeEnabled(id: string): boolean; isActionExecutable(actionId: string, actionTypeId: string): boolean; getActionsClientWithRequest(request: KibanaRequest): Promise>; + getActionsAuthorizationWithRequest(request: KibanaRequest): PublicMethodsOf; preconfiguredActions: PreConfiguredAction[]; } @@ -78,13 +88,15 @@ export interface ActionsPluginsSetup { spaces?: SpacesPluginSetup; eventLog: IEventLogService; usageCollection?: UsageCollectionSetup; + security?: SecurityPluginSetup; + features: FeaturesPluginSetup; } export interface ActionsPluginsStart { encryptedSavedObjects: EncryptedSavedObjectsPluginStart; taskManager: TaskManagerStartContract; } -const includedHiddenTypes = ['action', 'action_task_params']; +const includedHiddenTypes = [ACTION_SAVED_OBJECT_TYPE, ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE]; export class ActionsPlugin implements Plugin, PluginStartContract> { private readonly kibanaIndex: Promise; @@ -97,6 +109,7 @@ export class ActionsPlugin implements Plugin, Plugi private actionExecutor?: ActionExecutor; private licenseState: ILicenseState | null = null; private spaces?: SpacesServiceSetup; + private security?: SecurityPluginSetup; private eventLogger?: IEventLogger; private isESOUsingEphemeralEncryptionKey?: boolean; private readonly telemetryLogger: Logger; @@ -131,6 +144,7 @@ export class ActionsPlugin implements Plugin, Plugi ); } + plugins.features.registerFeature(ACTIONS_FEATURE); setupSavedObjects(core.savedObjects, plugins.encryptedSavedObjects); plugins.eventLog.registerProviderActions(EVENT_LOG_PROVIDER, Object.values(EVENT_LOG_ACTIONS)); @@ -167,6 +181,7 @@ export class ActionsPlugin implements Plugin, Plugi this.serverBasePath = core.http.basePath.serverBasePath; this.actionExecutor = actionExecutor; this.spaces = plugins.spaces?.spacesService; + this.security = plugins.security; registerBuiltInActionTypes({ logger: this.logger, @@ -227,16 +242,39 @@ export class ActionsPlugin implements Plugin, Plugi kibanaIndex, isESOUsingEphemeralEncryptionKey, preconfiguredActions, + instantiateAuthorization, } = this; const encryptedSavedObjectsClient = plugins.encryptedSavedObjects.getClient({ includedHiddenTypes, }); - const getScopedSavedObjectsClient = (request: KibanaRequest) => - core.savedObjects.getScopedClient(request, { - includedHiddenTypes, + const getActionsClientWithRequest = async (request: KibanaRequest) => { + if (isESOUsingEphemeralEncryptionKey === true) { + throw new Error( + `Unable to create actions client due to the Encrypted Saved Objects plugin using an ephemeral encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in kibana.yml` + ); + } + return new ActionsClient({ + unsecuredSavedObjectsClient: core.savedObjects.getScopedClient(request, { + excludedWrappers: ['security'], + includedHiddenTypes, + }), + actionTypeRegistry: actionTypeRegistry!, + defaultKibanaIndex: await kibanaIndex, + scopedClusterClient: core.elasticsearch.legacy.client.asScoped(request), + preconfiguredActions, + request, + authorization: instantiateAuthorization(request), + actionExecutor: actionExecutor!, + executionEnqueuer: createExecutionEnqueuerFunction({ + taskManager: plugins.taskManager, + actionTypeRegistry: actionTypeRegistry!, + isESOUsingEphemeralEncryptionKey: isESOUsingEphemeralEncryptionKey!, + preconfiguredActions, + }), }); + }; const getScopedSavedObjectsClientWithoutAccessToActions = (request: KibanaRequest) => core.savedObjects.getScopedClient(request); @@ -245,7 +283,7 @@ export class ActionsPlugin implements Plugin, Plugi logger, eventLogger: this.eventLogger!, spaces: this.spaces, - getScopedSavedObjectsClient, + getActionsClientWithRequest, getServices: this.getServicesFactory( getScopedSavedObjectsClientWithoutAccessToActions, core.elasticsearch @@ -261,7 +299,10 @@ export class ActionsPlugin implements Plugin, Plugi encryptedSavedObjectsClient, getBasePath: this.getBasePath, spaceIdToNamespace: this.spaceIdToNamespace, - getScopedSavedObjectsClient, + getScopedSavedObjectsClient: (request: KibanaRequest) => + core.savedObjects.getScopedClient(request, { + includedHiddenTypes, + }), }); scheduleActionsTelemetry(this.telemetryLogger, plugins.taskManager); @@ -273,33 +314,24 @@ export class ActionsPlugin implements Plugin, Plugi isActionExecutable: (actionId: string, actionTypeId: string) => { return this.actionTypeRegistry!.isActionExecutable(actionId, actionTypeId); }, - // Ability to get an actions client from legacy code - async getActionsClientWithRequest(request: KibanaRequest) { - if (isESOUsingEphemeralEncryptionKey === true) { - throw new Error( - `Unable to create actions client due to the Encrypted Saved Objects plugin using an ephemeral encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in kibana.yml` - ); - } - return new ActionsClient({ - savedObjectsClient: getScopedSavedObjectsClient(request), - actionTypeRegistry: actionTypeRegistry!, - defaultKibanaIndex: await kibanaIndex, - scopedClusterClient: core.elasticsearch.legacy.client.asScoped(request), - preconfiguredActions, - request, - actionExecutor: actionExecutor!, - executionEnqueuer: createExecutionEnqueuerFunction({ - taskManager: plugins.taskManager, - actionTypeRegistry: actionTypeRegistry!, - isESOUsingEphemeralEncryptionKey: isESOUsingEphemeralEncryptionKey!, - preconfiguredActions, - }), - }); + getActionsAuthorizationWithRequest(request: KibanaRequest) { + return instantiateAuthorization(request); }, + getActionsClientWithRequest, preconfiguredActions, }; } + private instantiateAuthorization = (request: KibanaRequest) => { + return new ActionsAuthorization({ + request, + authorization: this.security?.authz, + auditLogger: new ActionsAuthorizationAuditLogger( + this.security?.audit.getLogger(ACTIONS_FEATURE.id) + ), + }); + }; + private getServicesFactory( getScopedClient: (request: KibanaRequest) => SavedObjectsClientContract, elasticsearch: ElasticsearchServiceStart @@ -322,6 +354,7 @@ export class ActionsPlugin implements Plugin, Plugi isESOUsingEphemeralEncryptionKey, preconfiguredActions, actionExecutor, + instantiateAuthorization, } = this; return async function actionsRouteHandlerContext(context, request) { @@ -334,12 +367,16 @@ export class ActionsPlugin implements Plugin, Plugi ); } return new ActionsClient({ - savedObjectsClient: savedObjects.getScopedClient(request, { includedHiddenTypes }), + unsecuredSavedObjectsClient: savedObjects.getScopedClient(request, { + excludedWrappers: ['security'], + includedHiddenTypes, + }), actionTypeRegistry: actionTypeRegistry!, defaultKibanaIndex, scopedClusterClient: context.core.elasticsearch.legacy.client, preconfiguredActions, request, + authorization: instantiateAuthorization(request), actionExecutor: actionExecutor!, executionEnqueuer: createExecutionEnqueuerFunction({ taskManager, diff --git a/x-pack/plugins/actions/server/routes/create.test.ts b/x-pack/plugins/actions/server/routes/create.test.ts index 940b8ecc61f4e..76f2a79c9f3ee 100644 --- a/x-pack/plugins/actions/server/routes/create.test.ts +++ b/x-pack/plugins/actions/server/routes/create.test.ts @@ -28,13 +28,6 @@ describe('createActionRoute', () => { const [config, handler] = router.post.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/actions/action"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:actions-all", - ], - } - `); const createResult = { id: '1', diff --git a/x-pack/plugins/actions/server/routes/create.ts b/x-pack/plugins/actions/server/routes/create.ts index 8135567157583..462d3f42b506c 100644 --- a/x-pack/plugins/actions/server/routes/create.ts +++ b/x-pack/plugins/actions/server/routes/create.ts @@ -30,9 +30,6 @@ export const createActionRoute = (router: IRouter, licenseState: ILicenseState) validate: { body: bodySchema, }, - options: { - tags: ['access:actions-all'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/actions/server/routes/delete.test.ts b/x-pack/plugins/actions/server/routes/delete.test.ts index 8d759f1a7565e..3bd2d93f255df 100644 --- a/x-pack/plugins/actions/server/routes/delete.test.ts +++ b/x-pack/plugins/actions/server/routes/delete.test.ts @@ -28,13 +28,6 @@ describe('deleteActionRoute', () => { const [config, handler] = router.delete.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/actions/action/{id}"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:actions-all", - ], - } - `); const actionsClient = actionsClientMock.create(); actionsClient.delete.mockResolvedValueOnce({}); diff --git a/x-pack/plugins/actions/server/routes/delete.ts b/x-pack/plugins/actions/server/routes/delete.ts index 9d4fa4019744c..a7303247e95b0 100644 --- a/x-pack/plugins/actions/server/routes/delete.ts +++ b/x-pack/plugins/actions/server/routes/delete.ts @@ -31,9 +31,6 @@ export const deleteActionRoute = (router: IRouter, licenseState: ILicenseState) validate: { params: paramSchema, }, - options: { - tags: ['access:actions-all'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/actions/server/routes/execute.test.ts b/x-pack/plugins/actions/server/routes/execute.test.ts index 6e8ebbf6f91cd..38fca656bef5a 100644 --- a/x-pack/plugins/actions/server/routes/execute.test.ts +++ b/x-pack/plugins/actions/server/routes/execute.test.ts @@ -53,13 +53,6 @@ describe('executeActionRoute', () => { const [config, handler] = router.post.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/actions/action/{id}/_execute"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:actions-read", - ], - } - `); expect(await handler(context, req, res)).toEqual({ body: executeResult }); diff --git a/x-pack/plugins/actions/server/routes/execute.ts b/x-pack/plugins/actions/server/routes/execute.ts index 28e6a54f5e92d..0d49d9a3a256e 100644 --- a/x-pack/plugins/actions/server/routes/execute.ts +++ b/x-pack/plugins/actions/server/routes/execute.ts @@ -32,9 +32,6 @@ export const executeActionRoute = (router: IRouter, licenseState: ILicenseState) body: bodySchema, params: paramSchema, }, - options: { - tags: ['access:actions-read'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/actions/server/routes/get.test.ts b/x-pack/plugins/actions/server/routes/get.test.ts index ee2586851366c..434bd6a9bc224 100644 --- a/x-pack/plugins/actions/server/routes/get.test.ts +++ b/x-pack/plugins/actions/server/routes/get.test.ts @@ -29,13 +29,6 @@ describe('getActionRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/actions/action/{id}"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:actions-read", - ], - } - `); const getResult = { id: '1', diff --git a/x-pack/plugins/actions/server/routes/get.ts b/x-pack/plugins/actions/server/routes/get.ts index 224de241c7374..33577fad87c04 100644 --- a/x-pack/plugins/actions/server/routes/get.ts +++ b/x-pack/plugins/actions/server/routes/get.ts @@ -26,9 +26,6 @@ export const getActionRoute = (router: IRouter, licenseState: ILicenseState) => validate: { params: paramSchema, }, - options: { - tags: ['access:actions-read'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/actions/server/routes/get_all.test.ts b/x-pack/plugins/actions/server/routes/get_all.test.ts index 6550921278aa5..35db22d2da486 100644 --- a/x-pack/plugins/actions/server/routes/get_all.test.ts +++ b/x-pack/plugins/actions/server/routes/get_all.test.ts @@ -29,13 +29,6 @@ describe('getAllActionRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/actions"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:actions-read", - ], - } - `); const actionsClient = actionsClientMock.create(); actionsClient.getAll.mockResolvedValueOnce([]); @@ -64,13 +57,6 @@ describe('getAllActionRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/actions"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:actions-read", - ], - } - `); const actionsClient = actionsClientMock.create(); actionsClient.getAll.mockResolvedValueOnce([]); @@ -95,13 +81,6 @@ describe('getAllActionRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/actions"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:actions-read", - ], - } - `); const actionsClient = actionsClientMock.create(); actionsClient.getAll.mockResolvedValueOnce([]); diff --git a/x-pack/plugins/actions/server/routes/get_all.ts b/x-pack/plugins/actions/server/routes/get_all.ts index 03a4a97855b6b..1b57f31d14a0d 100644 --- a/x-pack/plugins/actions/server/routes/get_all.ts +++ b/x-pack/plugins/actions/server/routes/get_all.ts @@ -19,9 +19,6 @@ export const getAllActionRoute = (router: IRouter, licenseState: ILicenseState) { path: `${BASE_ACTION_API_PATH}`, validate: {}, - options: { - tags: ['access:actions-read'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/actions/server/routes/list_action_types.test.ts b/x-pack/plugins/actions/server/routes/list_action_types.test.ts index f231efe1a07f3..982b64c339a5f 100644 --- a/x-pack/plugins/actions/server/routes/list_action_types.test.ts +++ b/x-pack/plugins/actions/server/routes/list_action_types.test.ts @@ -10,6 +10,7 @@ import { licenseStateMock } from '../lib/license_state.mock'; import { verifyApiAccess } from '../lib'; import { mockHandlerArguments } from './_mock_handler_arguments'; import { LicenseType } from '../../../../plugins/licensing/server'; +import { actionsClientMock } from '../mocks'; jest.mock('../lib/verify_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -29,13 +30,6 @@ describe('listActionTypesRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/actions/list_action_types"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:actions-read", - ], - } - `); const listTypes = [ { @@ -48,7 +42,9 @@ describe('listActionTypesRoute', () => { }, ]; - const [context, req, res] = mockHandlerArguments({ listTypes }, {}, ['ok']); + const actionsClient = actionsClientMock.create(); + actionsClient.listTypes.mockResolvedValueOnce(listTypes); + const [context, req, res] = mockHandlerArguments({ actionsClient }, {}, ['ok']); expect(await handler(context, req, res)).toMatchInlineSnapshot(` Object { @@ -65,8 +61,6 @@ describe('listActionTypesRoute', () => { } `); - expect(context.actions!.listTypes).toHaveBeenCalledTimes(1); - expect(res.ok).toHaveBeenCalledWith({ body: listTypes, }); @@ -81,13 +75,6 @@ describe('listActionTypesRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/actions/list_action_types"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:actions-read", - ], - } - `); const listTypes = [ { @@ -100,8 +87,11 @@ describe('listActionTypesRoute', () => { }, ]; + const actionsClient = actionsClientMock.create(); + actionsClient.listTypes.mockResolvedValueOnce(listTypes); + const [context, req, res] = mockHandlerArguments( - { listTypes }, + { actionsClient }, { params: { id: '1' }, }, @@ -126,13 +116,6 @@ describe('listActionTypesRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/actions/list_action_types"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:actions-read", - ], - } - `); const listTypes = [ { @@ -145,8 +128,11 @@ describe('listActionTypesRoute', () => { }, ]; + const actionsClient = actionsClientMock.create(); + actionsClient.listTypes.mockResolvedValueOnce(listTypes); + const [context, req, res] = mockHandlerArguments( - { listTypes }, + { actionsClient }, { params: { id: '1' }, }, diff --git a/x-pack/plugins/actions/server/routes/list_action_types.ts b/x-pack/plugins/actions/server/routes/list_action_types.ts index bfb5fabe127f3..c960a6bac6de0 100644 --- a/x-pack/plugins/actions/server/routes/list_action_types.ts +++ b/x-pack/plugins/actions/server/routes/list_action_types.ts @@ -19,9 +19,6 @@ export const listActionTypesRoute = (router: IRouter, licenseState: ILicenseStat { path: `${BASE_ACTION_API_PATH}/list_action_types`, validate: {}, - options: { - tags: ['access:actions-read'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, @@ -32,8 +29,9 @@ export const listActionTypesRoute = (router: IRouter, licenseState: ILicenseStat if (!context.actions) { return res.badRequest({ body: 'RouteHandlerContext is not registered for actions' }); } + const actionsClient = context.actions.getActionsClient(); return res.ok({ - body: context.actions.listTypes(), + body: await actionsClient.listTypes(), }); }) ); diff --git a/x-pack/plugins/actions/server/routes/update.test.ts b/x-pack/plugins/actions/server/routes/update.test.ts index 323a52f2fc6e2..6d5b78650ba2a 100644 --- a/x-pack/plugins/actions/server/routes/update.test.ts +++ b/x-pack/plugins/actions/server/routes/update.test.ts @@ -28,13 +28,6 @@ describe('updateActionRoute', () => { const [config, handler] = router.put.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/actions/action/{id}"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:actions-all", - ], - } - `); const updateResult = { id: '1', diff --git a/x-pack/plugins/actions/server/routes/update.ts b/x-pack/plugins/actions/server/routes/update.ts index 1e107a4d6edb4..328ce74ef0b08 100644 --- a/x-pack/plugins/actions/server/routes/update.ts +++ b/x-pack/plugins/actions/server/routes/update.ts @@ -33,9 +33,6 @@ export const updateActionRoute = (router: IRouter, licenseState: ILicenseState) body: bodySchema, params: paramSchema, }, - options: { - tags: ['access:actions-all'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/actions/server/saved_objects/index.ts b/x-pack/plugins/actions/server/saved_objects/index.ts index d68c96a5e9270..54f186acc1ba5 100644 --- a/x-pack/plugins/actions/server/saved_objects/index.ts +++ b/x-pack/plugins/actions/server/saved_objects/index.ts @@ -8,12 +8,15 @@ import { SavedObjectsServiceSetup } from 'kibana/server'; import mappings from './mappings.json'; import { EncryptedSavedObjectsPluginSetup } from '../../../encrypted_saved_objects/server'; +export const ACTION_SAVED_OBJECT_TYPE = 'action'; +export const ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE = 'action_task_params'; + export function setupSavedObjects( savedObjects: SavedObjectsServiceSetup, encryptedSavedObjects: EncryptedSavedObjectsPluginSetup ) { savedObjects.registerType({ - name: 'action', + name: ACTION_SAVED_OBJECT_TYPE, hidden: true, namespaceType: 'single', mappings: mappings.action, @@ -24,19 +27,19 @@ export function setupSavedObjects( // - `config` will be included in AAD // - everything else excluded from AAD encryptedSavedObjects.registerType({ - type: 'action', + type: ACTION_SAVED_OBJECT_TYPE, attributesToEncrypt: new Set(['secrets']), attributesToExcludeFromAAD: new Set(['name']), }); savedObjects.registerType({ - name: 'action_task_params', + name: ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, hidden: true, namespaceType: 'single', mappings: mappings.action_task_params, }); encryptedSavedObjects.registerType({ - type: 'action_task_params', + type: ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, attributesToEncrypt: new Set(['apiKey']), }); } diff --git a/x-pack/plugins/alerting_builtins/common/index.ts b/x-pack/plugins/alerting_builtins/common/index.ts new file mode 100644 index 0000000000000..4f2c166669355 --- /dev/null +++ b/x-pack/plugins/alerting_builtins/common/index.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const BUILT_IN_ALERTS_FEATURE_ID = 'builtInAlerts'; diff --git a/x-pack/plugins/alerting_builtins/kibana.json b/x-pack/plugins/alerting_builtins/kibana.json index cc613d5247ef4..dd70e53604f16 100644 --- a/x-pack/plugins/alerting_builtins/kibana.json +++ b/x-pack/plugins/alerting_builtins/kibana.json @@ -3,7 +3,7 @@ "server": true, "version": "8.0.0", "kibanaVersion": "kibana", - "requiredPlugins": ["alerts"], + "requiredPlugins": ["alerts", "features"], "configPath": ["xpack", "alerting_builtins"], "ui": false } diff --git a/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/action_context.test.ts b/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/action_context.test.ts index a72a7343c5904..3f5addb77cb33 100644 --- a/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/action_context.test.ts +++ b/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/action_context.test.ts @@ -9,11 +9,6 @@ import { ParamsSchema } from './alert_type_params'; describe('ActionContext', () => { it('generates expected properties if aggField is null', async () => { - const base: BaseActionContext = { - date: '2020-01-01T00:00:00.000Z', - group: '[group]', - value: 42, - }; const params = ParamsSchema.validate({ index: '[index]', timeField: '[timeField]', @@ -26,6 +21,11 @@ describe('ActionContext', () => { thresholdComparator: '>', threshold: [4], }); + const base: BaseActionContext = { + date: '2020-01-01T00:00:00.000Z', + group: '[group]', + value: 42, + }; const context = addMessages({ name: '[alert-name]' }, base, params); expect(context.title).toMatchInlineSnapshot( `"alert [alert-name] group [group] exceeded threshold"` @@ -36,11 +36,6 @@ describe('ActionContext', () => { }); it('generates expected properties if aggField is not null', async () => { - const base: BaseActionContext = { - date: '2020-01-01T00:00:00.000Z', - group: '[group]', - value: 42, - }; const params = ParamsSchema.validate({ index: '[index]', timeField: '[timeField]', @@ -54,6 +49,11 @@ describe('ActionContext', () => { thresholdComparator: '>', threshold: [4.2], }); + const base: BaseActionContext = { + date: '2020-01-01T00:00:00.000Z', + group: '[group]', + value: 42, + }; const context = addMessages({ name: '[alert-name]' }, base, params); expect(context.title).toMatchInlineSnapshot( `"alert [alert-name] group [group] exceeded threshold"` @@ -64,11 +64,6 @@ describe('ActionContext', () => { }); it('generates expected properties if comparator is between', async () => { - const base: BaseActionContext = { - date: '2020-01-01T00:00:00.000Z', - group: '[group]', - value: 4, - }; const params = ParamsSchema.validate({ index: '[index]', timeField: '[timeField]', @@ -81,6 +76,11 @@ describe('ActionContext', () => { thresholdComparator: 'between', threshold: [4, 5], }); + const base: BaseActionContext = { + date: '2020-01-01T00:00:00.000Z', + group: '[group]', + value: 4, + }; const context = addMessages({ name: '[alert-name]' }, base, params); expect(context.title).toMatchInlineSnapshot( `"alert [alert-name] group [group] exceeded threshold"` diff --git a/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/alert_type.test.ts b/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/alert_type.test.ts index d3583fd4cdb0b..e33a3e775ca96 100644 --- a/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/alert_type.test.ts +++ b/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/alert_type.test.ts @@ -47,6 +47,52 @@ describe('alertType', () => { "name": "value", }, ], + "params": Array [ + Object { + "description": "An array of values to use as the threshold; 'between' and 'notBetween' require two values, the others require one.", + "name": "threshold", + }, + Object { + "description": "A comparison function to use to determine if the threshold as been met.", + "name": "thresholdComparator", + }, + Object { + "description": "index", + "name": "index", + }, + Object { + "description": "timeField", + "name": "timeField", + }, + Object { + "description": "aggType", + "name": "aggType", + }, + Object { + "description": "aggField", + "name": "aggField", + }, + Object { + "description": "groupBy", + "name": "groupBy", + }, + Object { + "description": "termField", + "name": "termField", + }, + Object { + "description": "termSize", + "name": "termSize", + }, + Object { + "description": "timeWindowSize", + "name": "timeWindowSize", + }, + Object { + "description": "timeWindowUnit", + "name": "timeWindowUnit", + }, + ], } `); }); diff --git a/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/alert_type.ts b/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/alert_type.ts index 1a5da8a422b9e..c0522c08a7b96 100644 --- a/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/alert_type.ts +++ b/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/alert_type.ts @@ -9,11 +9,12 @@ import { AlertType, AlertExecutorOptions } from '../../types'; import { Params, ParamsSchema } from './alert_type_params'; import { BaseActionContext, addMessages } from './action_context'; import { TimeSeriesQuery } from './lib/time_series_query'; +import { Service } from '../../types'; +import { BUILT_IN_ALERTS_FEATURE_ID } from '../../../common'; export const ID = '.index-threshold'; -import { Service } from '../../types'; - +import { CoreQueryParamsSchemaProperties } from './lib/core_query_types'; const ActionGroupId = 'threshold met'; const ComparatorFns = getComparatorFns(); export const ComparatorFnNames = new Set(ComparatorFns.keys()); @@ -67,6 +68,30 @@ export function getAlertType(service: Service): AlertType { } ); + const actionVariableContextThresholdLabel = i18n.translate( + 'xpack.alertingBuiltins.indexThreshold.actionVariableContextThresholdLabel', + { + defaultMessage: + "An array of values to use as the threshold; 'between' and 'notBetween' require two values, the others require one.", + } + ); + + const actionVariableContextThresholdComparatorLabel = i18n.translate( + 'xpack.alertingBuiltins.indexThreshold.actionVariableContextThresholdComparatorLabel', + { + defaultMessage: 'A comparison function to use to determine if the threshold as been met.', + } + ); + + const alertParamsVariables = Object.keys(CoreQueryParamsSchemaProperties).map( + (propKey: string) => { + return { + name: propKey, + description: propKey, + }; + } + ); + return { id: ID, name: alertTypeName, @@ -83,9 +108,14 @@ export function getAlertType(service: Service): AlertType { { name: 'date', description: actionVariableContextDateLabel }, { name: 'value', description: actionVariableContextValueLabel }, ], + params: [ + { name: 'threshold', description: actionVariableContextThresholdLabel }, + { name: 'thresholdComparator', description: actionVariableContextThresholdComparatorLabel }, + ...alertParamsVariables, + ], }, executor, - producer: 'alerting', + producer: BUILT_IN_ALERTS_FEATURE_ID, }; async function executor(options: AlertExecutorOptions) { diff --git a/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/lib/date_range_info.test.ts b/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/lib/date_range_info.test.ts index 32a5845a7e65b..a0b726c2510c0 100644 --- a/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/lib/date_range_info.test.ts +++ b/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/lib/date_range_info.test.ts @@ -132,10 +132,11 @@ describe('getRangeInfo', () => { it('should handle no dateStart, dateEnd or interval specified', async () => { const nowM0 = Date.now(); const nowM5 = nowM0 - 1000 * 60 * 5; + const digitPrecision = 1; const info = getDateRangeInfo(BaseRangeQuery); - expect(sloppyMilliDiff(nowM5, Date.parse(info.dateStart))).toBeCloseTo(0); - expect(sloppyMilliDiff(nowM0, Date.parse(info.dateEnd))).toBeCloseTo(0); + expect(sloppyMilliDiff(nowM5, Date.parse(info.dateStart))).toBeCloseTo(0, digitPrecision); + expect(sloppyMilliDiff(nowM0, Date.parse(info.dateEnd))).toBeCloseTo(0, digitPrecision); expect(info.dateRanges.length).toEqual(1); expect(info.dateRanges[0].from).toEqual(info.dateStart); expect(info.dateRanges[0].to).toEqual(info.dateEnd); diff --git a/x-pack/plugins/alerting_builtins/server/feature.ts b/x-pack/plugins/alerting_builtins/server/feature.ts new file mode 100644 index 0000000000000..316bae98bf8c1 --- /dev/null +++ b/x-pack/plugins/alerting_builtins/server/feature.ts @@ -0,0 +1,58 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; +import { ID as IndexThreshold } from './alert_types/index_threshold/alert_type'; +import { BUILT_IN_ALERTS_FEATURE_ID } from '../common'; + +export const BUILT_IN_ALERTS_FEATURE = { + id: BUILT_IN_ALERTS_FEATURE_ID, + name: i18n.translate('xpack.alertingBuiltins.featureRegistry.actionsFeatureName', { + defaultMessage: 'Built-In Alerts', + }), + icon: 'bell', + app: [], + management: { + insightsAndAlerting: ['triggersActions'], + }, + alerting: [IndexThreshold], + privileges: { + all: { + app: [], + catalogue: [], + management: { + insightsAndAlerting: ['triggersActions'], + }, + alerting: { + all: [IndexThreshold], + read: [], + }, + savedObject: { + all: [], + read: [], + }, + api: [], + ui: [], + }, + read: { + app: [], + catalogue: [], + management: { + insightsAndAlerting: ['triggersActions'], + }, + alerting: { + all: [], + read: [IndexThreshold], + }, + savedObject: { + all: [], + read: [], + }, + api: [], + ui: [], + }, + }, +}; diff --git a/x-pack/plugins/alerting_builtins/server/index.ts b/x-pack/plugins/alerting_builtins/server/index.ts index 00613213d5aed..108393c0d1469 100644 --- a/x-pack/plugins/alerting_builtins/server/index.ts +++ b/x-pack/plugins/alerting_builtins/server/index.ts @@ -7,6 +7,7 @@ import { PluginInitializerContext } from 'src/core/server'; import { AlertingBuiltinsPlugin } from './plugin'; import { configSchema } from './config'; +export { ID as INDEX_THRESHOLD_ID } from './alert_types/index_threshold/alert_type'; export const plugin = (ctx: PluginInitializerContext) => new AlertingBuiltinsPlugin(ctx); diff --git a/x-pack/plugins/alerting_builtins/server/plugin.test.ts b/x-pack/plugins/alerting_builtins/server/plugin.test.ts index 71a904dcbab3d..15ad066523502 100644 --- a/x-pack/plugins/alerting_builtins/server/plugin.test.ts +++ b/x-pack/plugins/alerting_builtins/server/plugin.test.ts @@ -7,6 +7,8 @@ import { AlertingBuiltinsPlugin } from './plugin'; import { coreMock } from '../../../../src/core/server/mocks'; import { alertsMock } from '../../alerts/server/mocks'; +import { featuresPluginMock } from '../../features/server/mocks'; +import { BUILT_IN_ALERTS_FEATURE } from './feature'; describe('AlertingBuiltins Plugin', () => { describe('setup()', () => { @@ -22,7 +24,8 @@ describe('AlertingBuiltins Plugin', () => { it('should register built-in alert types', async () => { const alertingSetup = alertsMock.createSetup(); - await plugin.setup(coreSetup, { alerts: alertingSetup }); + const featuresSetup = featuresPluginMock.createSetup(); + await plugin.setup(coreSetup, { alerts: alertingSetup, features: featuresSetup }); expect(alertingSetup.registerType).toHaveBeenCalledTimes(1); @@ -40,11 +43,16 @@ describe('AlertingBuiltins Plugin', () => { "name": "Index threshold", } `); + expect(featuresSetup.registerFeature).toHaveBeenCalledWith(BUILT_IN_ALERTS_FEATURE); }); it('should return a service in the expected shape', async () => { const alertingSetup = alertsMock.createSetup(); - const service = await plugin.setup(coreSetup, { alerts: alertingSetup }); + const featuresSetup = featuresPluginMock.createSetup(); + const service = await plugin.setup(coreSetup, { + alerts: alertingSetup, + features: featuresSetup, + }); expect(typeof service.indexThreshold.timeSeriesQuery).toBe('function'); }); diff --git a/x-pack/plugins/alerting_builtins/server/plugin.ts b/x-pack/plugins/alerting_builtins/server/plugin.ts index 12d1b080c7c63..41871c01bfb50 100644 --- a/x-pack/plugins/alerting_builtins/server/plugin.ts +++ b/x-pack/plugins/alerting_builtins/server/plugin.ts @@ -9,6 +9,7 @@ import { Plugin, Logger, CoreSetup, CoreStart, PluginInitializerContext } from ' import { Service, IService, AlertingBuiltinsDeps } from './types'; import { getService as getServiceIndexThreshold } from './alert_types/index_threshold'; import { registerBuiltInAlertTypes } from './alert_types'; +import { BUILT_IN_ALERTS_FEATURE } from './feature'; export class AlertingBuiltinsPlugin implements Plugin { private readonly logger: Logger; @@ -22,7 +23,12 @@ export class AlertingBuiltinsPlugin implements Plugin { }; } - public async setup(core: CoreSetup, { alerts }: AlertingBuiltinsDeps): Promise { + public async setup( + core: CoreSetup, + { alerts, features }: AlertingBuiltinsDeps + ): Promise { + features.registerFeature(BUILT_IN_ALERTS_FEATURE); + registerBuiltInAlertTypes({ service: this.service, router: core.http.createRouter(), diff --git a/x-pack/plugins/alerting_builtins/server/types.ts b/x-pack/plugins/alerting_builtins/server/types.ts index 1fb5314ca4fd9..f3abc26be8dab 100644 --- a/x-pack/plugins/alerting_builtins/server/types.ts +++ b/x-pack/plugins/alerting_builtins/server/types.ts @@ -15,10 +15,12 @@ export { AlertType, AlertExecutorOptions, } from '../../alerts/server'; +import { PluginSetupContract as FeaturesPluginSetup } from '../../features/server'; // this plugin's dependendencies export interface AlertingBuiltinsDeps { alerts: AlertingSetup; + features: FeaturesPluginSetup; } // external service exposed through plugin setup/start diff --git a/x-pack/plugins/alerts/README.md b/x-pack/plugins/alerts/README.md index 0464ec78a4e9d..10568abbe3c72 100644 --- a/x-pack/plugins/alerts/README.md +++ b/x-pack/plugins/alerts/README.md @@ -18,6 +18,7 @@ Table of Contents - [Methods](#methods) - [Executor](#executor) - [Example](#example) + - [Role Based Access-Control](#role-based-access-control) - [Alert Navigation](#alert-navigation) - [RESTful API](#restful-api) - [`POST /api/alerts/alert`: Create alert](#post-apialert-create-alert) @@ -58,7 +59,8 @@ A Kibana alert detects a condition and executes one or more actions when that co ## Usage 1. Develop and register an alert type (see alert types -> example). -2. Create an alert using the RESTful API (see alerts -> create). +2. Configure feature level privileges using RBAC +3. Create an alert using the RESTful API (see alerts -> create). ## Limitations @@ -293,6 +295,111 @@ server.newPlatform.setup.plugins.alerts.registerType({ }); ``` +## Role Based Access-Control +Once you have registered your AlertType, you need to grant your users privileges to use it. +When registering a feature in Kibana you can specify multiple types of privileges which are granted to users when they're assigned certain roles. + +Assuming your feature introduces its own AlertTypes, you'll want to control which roles have all/read privileges for these AlertTypes when they're inside the feature. +In addition, when users are inside your feature you might want to grant them access to AlertTypes from other features, such as built-in AlertTypes or AlertTypes provided by other features. + +You can control all of these abilities by assigning privileges to the Alerting Framework from within your own feature, for example: + +```typescript +features.registerFeature({ + id: 'my-application-id', + name: 'My Application', + app: [], + privileges: { + all: { + alerting: { + all: [ + // grant `all` over our own types + 'my-application-id.my-alert-type', + 'my-application-id.my-restricted-alert-type', + // grant `all` over the built-in IndexThreshold + '.index-threshold', + // grant `all` over Uptime's TLS AlertType + 'xpack.uptime.alerts.actionGroups.tls' + ], + }, + }, + read: { + alerting: { + read: [ + // grant `read` over our own type + 'my-application-id.my-alert-type', + // grant `read` over the built-in IndexThreshold + '.index-threshold', + // grant `read` over Uptime's TLS AlertType + 'xpack.uptime.alerts.actionGroups.tls' + ], + }, + }, + }, +}); +``` + +In this example we can see the following: +- Our feature grants any user who's assigned the `all` role in our feature the `all` role in the Alerting framework over every alert of the `my-application-id.my-alert-type` type which is created _inside_ the feature. What that means is that this privilege will allow the user to execute any of the `all` operations (listed below) on these alerts as long as their `consumer` is `my-application-id`. Below that you'll notice we've done the same with the `read` role, which is grants the Alerting Framework's `read` role privileges over these very same alerts. +- In addition, our feature grants the same privileges over any alert of type `my-application-id.my-restricted-alert-type`, which is another hypothetical alertType registered by this feature. It's worth noting though that this type has been omitted from the `read` role. What this means is that only users with the `all` role will be able to interact with alerts of this type. +- Next, lets look at the `.index-threshold` and `xpack.uptime.alerts.actionGroups.tls` types. These have been specified in both `read` and `all`, which means that all the users in the feature will gain privileges over alerts of these types (as long as their `consumer` is `my-application-id`). The difference between these two and the previous two is that they are _produced_ by other features! `.index-threshold` is a built-in type, provided by the _Built-In Alerts_ feature, and `xpack.uptime.alerts.actionGroups.tls` is an AlertType provided by the _Uptime_ feature. Specifying these type here tells the Alerting Framework that as far as the `my-application-id` feature is concerned, the user is privileged to use them (with `all` and `read` applied), but that isn't enough. Using another feature's AlertType is only possible if both the producer of the AlertType, and the consumer of the AlertType, explicitly grant privileges to do so. In this case, the _Built-In Alerts_ & _Uptime_ features would have to explicitly add these privileges to a role and this role would have to be granted to this user. + +It's important to note that any role can be granted a mix of `all` and `read` privileges accross multiple type, for example: + +```typescript +features.registerFeature({ + id: 'my-application-id', + name: 'My Application', + app: [], + privileges: { + all: { + alerting: { + all: [ + 'my-application-id.my-alert-type', + 'my-application-id.my-restricted-alert-type' + ], + }, + }, + read: { + alerting: { + all: [ + 'my-application-id.my-alert-type' + ] + read: [ + 'my-application-id.my-restricted-alert-type' + ], + }, + }, + }, +}); +``` + +In the above example, you note that instead of denying users with the `read` role any access to the `my-application-id.my-restricted-alert-type` type, we've decided that these users _should_ be granted `read` privileges over the _resitricted_ AlertType. +As part of that same change, we also decided that not only should they be allowed to `read` the _restricted_ AlertType, but actually, despite having `read` privileges to the feature as a whole, we do actually want to allow them to create our basic 'my-application-id.my-alert-type' AlertType, as we consider it an extension of _reading_ data in our feature, rather than _writing_ it. + +### `read` privileges vs. `all` privileges +When a user is granted the `read` role in the Alerting Framework, they will be able to execute the following api calls: +- `get` +- `getAlertState` +- `find` + +When a user is granted the `all` role in the Alerting Framework, they will be able to execute all of the `read` privileged api calls, but in addition they'll be granted the following calls: +- `create` +- `delete` +- `update` +- `enable` +- `disable` +- `updateApiKey` +- `muteAll` +- `unmuteAll` +- `muteInstance` +- `unmuteInstance` + +Finally, all users, whether they're granted any role or not, are privileged to call the following: +- `listAlertTypes`, but the output is limited to displaying the AlertTypes the user is perivileged to `get` + +Attempting to execute any operation the user isn't privileged to execute will result in an Authorization error thrown by the AlertsClient. + ## Alert Navigation When registering an Alert Type, you'll likely want to provide a way of viewing alerts of that type within your own plugin, or perhaps you want to provide a view for all alerts created from within your solution within your own UI. diff --git a/x-pack/plugins/alerts/common/index.ts b/x-pack/plugins/alerts/common/index.ts index 88a8da5a3e575..b839c07a9db89 100644 --- a/x-pack/plugins/alerts/common/index.ts +++ b/x-pack/plugins/alerts/common/index.ts @@ -21,3 +21,4 @@ export interface AlertingFrameworkHealth { } export const BASE_ALERT_API_PATH = '/api/alerts'; +export const ALERTS_FEATURE_ID = 'alerts'; diff --git a/x-pack/plugins/alerts/kibana.json b/x-pack/plugins/alerts/kibana.json index eef61ff4b3d53..c0ab242831428 100644 --- a/x-pack/plugins/alerts/kibana.json +++ b/x-pack/plugins/alerts/kibana.json @@ -5,7 +5,7 @@ "version": "8.0.0", "kibanaVersion": "kibana", "configPath": ["xpack", "alerts"], - "requiredPlugins": ["licensing", "taskManager", "encryptedSavedObjects", "actions", "eventLog"], + "requiredPlugins": ["licensing", "taskManager", "encryptedSavedObjects", "actions", "eventLog", "features"], "optionalPlugins": ["usageCollection", "spaces", "security"], "extraPublicDirs": ["common", "common/parse_duration"] } diff --git a/x-pack/plugins/alerts/public/alert_api.test.ts b/x-pack/plugins/alerts/public/alert_api.test.ts index 45b9f5ba8fe2e..3ee67b79b7bda 100644 --- a/x-pack/plugins/alerts/public/alert_api.test.ts +++ b/x-pack/plugins/alerts/public/alert_api.test.ts @@ -22,7 +22,7 @@ describe('loadAlertTypes', () => { actionVariables: ['var1'], actionGroups: [{ id: 'default', name: 'Default' }], defaultActionGroupId: 'default', - producer: 'alerting', + producer: 'alerts', }, ]; http.get.mockResolvedValueOnce(resolvedValue); @@ -45,7 +45,7 @@ describe('loadAlertType', () => { actionVariables: ['var1'], actionGroups: [{ id: 'default', name: 'Default' }], defaultActionGroupId: 'default', - producer: 'alerting', + producer: 'alerts', }; http.get.mockResolvedValueOnce([alertType]); @@ -65,7 +65,7 @@ describe('loadAlertType', () => { actionVariables: [], actionGroups: [{ id: 'default', name: 'Default' }], defaultActionGroupId: 'default', - producer: 'alerting', + producer: 'alerts', }; http.get.mockResolvedValueOnce([alertType]); @@ -80,7 +80,7 @@ describe('loadAlertType', () => { actionVariables: [], actionGroups: [{ id: 'default', name: 'Default' }], defaultActionGroupId: 'default', - producer: 'alerting', + producer: 'alerts', }, ]); diff --git a/x-pack/plugins/alerts/public/alert_navigation_registry/alert_navigation_registry.test.ts b/x-pack/plugins/alerts/public/alert_navigation_registry/alert_navigation_registry.test.ts index ff8a3a1c311c1..72c955923a0cc 100644 --- a/x-pack/plugins/alerts/public/alert_navigation_registry/alert_navigation_registry.test.ts +++ b/x-pack/plugins/alerts/public/alert_navigation_registry/alert_navigation_registry.test.ts @@ -16,7 +16,7 @@ const mockAlertType = (id: string): AlertType => ({ actionGroups: [], actionVariables: [], defaultActionGroupId: 'default', - producer: 'alerting', + producer: 'alerts', }); describe('AlertNavigationRegistry', () => { diff --git a/x-pack/plugins/alerts/server/alert_type_registry.test.ts b/x-pack/plugins/alerts/server/alert_type_registry.test.ts index 6d7cf621ab0ca..229847bda1836 100644 --- a/x-pack/plugins/alerts/server/alert_type_registry.test.ts +++ b/x-pack/plugins/alerts/server/alert_type_registry.test.ts @@ -36,13 +36,67 @@ describe('has()', () => { ], defaultActionGroupId: 'default', executor: jest.fn(), - producer: 'alerting', + producer: 'alerts', }); expect(registry.has('foo')).toEqual(true); }); }); describe('register()', () => { + test('throws if AlertType Id contains invalid characters', () => { + const alertType = { + id: 'test', + name: 'Test', + actionGroups: [ + { + id: 'default', + name: 'Default', + }, + ], + defaultActionGroupId: 'default', + executor: jest.fn(), + producer: 'alerts', + }; + // eslint-disable-next-line @typescript-eslint/no-var-requires + const registry = new AlertTypeRegistry(alertTypeRegistryParams); + + const invalidCharacters = [' ', ':', '*', '*', '/']; + for (const char of invalidCharacters) { + expect(() => registry.register({ ...alertType, id: `${alertType.id}${char}` })).toThrowError( + new Error(`expected AlertType Id not to include invalid character: ${char}`) + ); + } + + const [first, second] = invalidCharacters; + expect(() => + registry.register({ ...alertType, id: `${first}${alertType.id}${second}` }) + ).toThrowError( + new Error(`expected AlertType Id not to include invalid characters: ${first}, ${second}`) + ); + }); + + test('throws if AlertType Id isnt a string', () => { + const alertType = { + id: (123 as unknown) as string, + name: 'Test', + actionGroups: [ + { + id: 'default', + name: 'Default', + }, + ], + defaultActionGroupId: 'default', + executor: jest.fn(), + producer: 'alerts', + }; + // eslint-disable-next-line @typescript-eslint/no-var-requires + const registry = new AlertTypeRegistry(alertTypeRegistryParams); + + expect(() => registry.register(alertType)).toThrowError( + new Error(`expected value of type [string] but got [number]`) + ); + }); + test('registers the executor with the task manager', () => { const alertType = { id: 'test', @@ -55,7 +109,7 @@ describe('register()', () => { ], defaultActionGroupId: 'default', executor: jest.fn(), - producer: 'alerting', + producer: 'alerts', }; // eslint-disable-next-line @typescript-eslint/no-var-requires const registry = new AlertTypeRegistry(alertTypeRegistryParams); @@ -86,7 +140,7 @@ describe('register()', () => { ], defaultActionGroupId: 'default', executor: jest.fn(), - producer: 'alerting', + producer: 'alerts', }; const registry = new AlertTypeRegistry(alertTypeRegistryParams); registry.register(alertType); @@ -107,7 +161,7 @@ describe('register()', () => { ], defaultActionGroupId: 'default', executor: jest.fn(), - producer: 'alerting', + producer: 'alerts', }); expect(() => registry.register({ @@ -121,7 +175,7 @@ describe('register()', () => { ], defaultActionGroupId: 'default', executor: jest.fn(), - producer: 'alerting', + producer: 'alerts', }) ).toThrowErrorMatchingInlineSnapshot(`"Alert type \\"test\\" is already registered."`); }); @@ -141,7 +195,7 @@ describe('get()', () => { ], defaultActionGroupId: 'default', executor: jest.fn(), - producer: 'alerting', + producer: 'alerts', }); const alertType = registry.get('test'); expect(alertType).toMatchInlineSnapshot(` @@ -154,13 +208,14 @@ describe('get()', () => { ], "actionVariables": Object { "context": Array [], + "params": Array [], "state": Array [], }, "defaultActionGroupId": "default", "executor": [MockFunction], "id": "test", "name": "Test", - "producer": "alerting", + "producer": "alerts", } `); }); @@ -177,7 +232,7 @@ describe('list()', () => { test('should return empty when nothing is registered', () => { const registry = new AlertTypeRegistry(alertTypeRegistryParams); const result = registry.list(); - expect(result).toMatchInlineSnapshot(`Array []`); + expect(result).toMatchInlineSnapshot(`Set {}`); }); test('should return registered types', () => { @@ -193,11 +248,11 @@ describe('list()', () => { ], defaultActionGroupId: 'testActionGroup', executor: jest.fn(), - producer: 'alerting', + producer: 'alerts', }); const result = registry.list(); expect(result).toMatchInlineSnapshot(` - Array [ + Set { Object { "actionGroups": Array [ Object { @@ -207,14 +262,15 @@ describe('list()', () => { ], "actionVariables": Object { "context": Array [], + "params": Array [], "state": Array [], }, "defaultActionGroupId": "testActionGroup", "id": "test", "name": "Test", - "producer": "alerting", + "producer": "alerts", }, - ] + } `); }); @@ -260,7 +316,7 @@ function alertTypeWithVariables(id: string, context: string, state: string): Ale actionGroups: [], defaultActionGroupId: id, async executor() {}, - producer: 'alerting', + producer: 'alerts', }; if (!context && !state) { diff --git a/x-pack/plugins/alerts/server/alert_type_registry.ts b/x-pack/plugins/alerts/server/alert_type_registry.ts index 8f36afe062aa5..19d3bf13bd66d 100644 --- a/x-pack/plugins/alerts/server/alert_type_registry.ts +++ b/x-pack/plugins/alerts/server/alert_type_registry.ts @@ -6,6 +6,8 @@ import Boom from 'boom'; import { i18n } from '@kbn/i18n'; +import { schema } from '@kbn/config-schema'; +import typeDetect from 'type-detect'; import { RunContext, TaskManagerSetupContract } from '../../task_manager/server'; import { TaskRunnerFactory } from './task_runner'; import { AlertType } from './types'; @@ -15,6 +17,34 @@ interface ConstructorOptions { taskRunnerFactory: TaskRunnerFactory; } +export interface RegistryAlertType + extends Pick< + AlertType, + 'name' | 'actionGroups' | 'defaultActionGroupId' | 'actionVariables' | 'producer' + > { + id: string; +} + +/** + * AlertType IDs are used as part of the authorization strings used to + * grant users privileged operations. There is a limited range of characters + * we can use in these auth strings, so we apply these same limitations to + * the AlertType Ids. + * If you wish to change this, please confer with the Kibana security team. + */ +const alertIdSchema = schema.string({ + validate(value: string): string | void { + if (typeof value !== 'string') { + return `expected AlertType Id of type [string] but got [${typeDetect(value)}]`; + } else if (!value.match(/^[a-zA-Z0-9_\-\.]*$/)) { + const invalid = value.match(/[^a-zA-Z0-9_\-\.]+/g)!; + return `expected AlertType Id not to include invalid character${ + invalid.length > 1 ? `s` : `` + }: ${invalid?.join(`, `)}`; + } + }, +}); + export class AlertTypeRegistry { private readonly taskManager: TaskManagerSetupContract; private readonly alertTypes: Map = new Map(); @@ -41,7 +71,7 @@ export class AlertTypeRegistry { ); } alertType.actionVariables = normalizedActionVariables(alertType.actionVariables); - this.alertTypes.set(alertType.id, { ...alertType }); + this.alertTypes.set(alertIdSchema.validate(alertType.id), { ...alertType }); this.taskManager.registerTaskDefinitions({ [`alerting:${alertType.id}`]: { title: alertType.name, @@ -66,15 +96,22 @@ export class AlertTypeRegistry { return this.alertTypes.get(id)!; } - public list() { - return Array.from(this.alertTypes).map(([alertTypeId, alertType]) => ({ - id: alertTypeId, - name: alertType.name, - actionGroups: alertType.actionGroups, - defaultActionGroupId: alertType.defaultActionGroupId, - actionVariables: alertType.actionVariables, - producer: alertType.producer, - })); + public list(): Set { + return new Set( + Array.from(this.alertTypes).map( + ([id, { name, actionGroups, defaultActionGroupId, actionVariables, producer }]: [ + string, + AlertType + ]) => ({ + id, + name, + actionGroups, + defaultActionGroupId, + actionVariables, + producer, + }) + ) + ); } } @@ -82,5 +119,6 @@ function normalizedActionVariables(actionVariables: AlertType['actionVariables'] return { context: actionVariables?.context ?? [], state: actionVariables?.state ?? [], + params: actionVariables?.params ?? [], }; } diff --git a/x-pack/plugins/alerts/server/alerts_client.mock.ts b/x-pack/plugins/alerts/server/alerts_client.mock.ts index 1848b3432ae5a..be70e441b6fc5 100644 --- a/x-pack/plugins/alerts/server/alerts_client.mock.ts +++ b/x-pack/plugins/alerts/server/alerts_client.mock.ts @@ -24,6 +24,7 @@ const createAlertsClientMock = () => { unmuteAll: jest.fn(), muteInstance: jest.fn(), unmuteInstance: jest.fn(), + listAlertTypes: jest.fn(), }; return mocked; }; diff --git a/x-pack/plugins/alerts/server/alerts_client.test.ts b/x-pack/plugins/alerts/server/alerts_client.test.ts index d69d04f71ce9e..c25e040ad09ce 100644 --- a/x-pack/plugins/alerts/server/alerts_client.test.ts +++ b/x-pack/plugins/alerts/server/alerts_client.test.ts @@ -5,25 +5,32 @@ */ import uuid from 'uuid'; import { schema } from '@kbn/config-schema'; -import { AlertsClient, CreateOptions } from './alerts_client'; +import { AlertsClient, CreateOptions, ConstructorOptions } from './alerts_client'; import { savedObjectsClientMock, loggingSystemMock } from '../../../../src/core/server/mocks'; import { taskManagerMock } from '../../task_manager/server/task_manager.mock'; import { alertTypeRegistryMock } from './alert_type_registry.mock'; +import { alertsAuthorizationMock } from './authorization/alerts_authorization.mock'; import { TaskStatus } from '../../task_manager/server'; import { IntervalSchedule } from './types'; import { resolvable } from './test_utils'; import { encryptedSavedObjectsMock } from '../../encrypted_saved_objects/server/mocks'; -import { actionsClientMock } from '../../actions/server/mocks'; +import { actionsClientMock, actionsAuthorizationMock } from '../../actions/server/mocks'; +import { AlertsAuthorization } from './authorization/alerts_authorization'; +import { ActionsAuthorization } from '../../actions/server'; const taskManager = taskManagerMock.start(); const alertTypeRegistry = alertTypeRegistryMock.create(); -const savedObjectsClient = savedObjectsClientMock.create(); +const unsecuredSavedObjectsClient = savedObjectsClientMock.create(); const encryptedSavedObjects = encryptedSavedObjectsMock.createClient(); +const authorization = alertsAuthorizationMock.create(); +const actionsAuthorization = actionsAuthorizationMock.create(); -const alertsClientParams = { +const alertsClientParams: jest.Mocked = { taskManager, alertTypeRegistry, - savedObjectsClient, + unsecuredSavedObjectsClient, + authorization: (authorization as unknown) as AlertsAuthorization, + actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), @@ -39,7 +46,11 @@ beforeEach(() => { alertsClientParams.createAPIKey.mockResolvedValue({ apiKeysEnabled: false }); alertsClientParams.invalidateAPIKey.mockResolvedValue({ apiKeysEnabled: true, - result: { error_count: 0 }, + result: { + invalidated_api_keys: [], + previously_invalidated_api_keys: [], + error_count: 0, + }, }); alertsClientParams.getUserName.mockResolvedValue('elastic'); taskManager.runNow.mockResolvedValue({ id: '' }); @@ -71,6 +82,15 @@ beforeEach(() => { }, ]); alertsClientParams.getActionsClient.mockResolvedValue(actionsClient); + + alertTypeRegistry.get.mockImplementation((id) => ({ + id: '123', + name: 'Test', + actionGroups: [{ id: 'default', name: 'Default' }], + defaultActionGroupId: 'default', + async executor() {}, + producer: 'alerts', + })); }); const mockedDate = new Date('2019-02-12T21:01:22.479Z'); @@ -114,19 +134,116 @@ describe('create()', () => { beforeEach(() => { alertsClient = new AlertsClient(alertsClientParams); - alertTypeRegistry.get.mockReturnValue({ - id: '123', - name: 'Test', - actionGroups: [{ id: 'default', name: 'Default' }], - defaultActionGroupId: 'default', - async executor() {}, - producer: 'alerting', + }); + + describe('authorization', () => { + function tryToExecuteOperation(options: CreateOptions): Promise { + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ + saved_objects: [ + { + id: '1', + type: 'action', + attributes: { + actions: [], + actionTypeId: 'test', + }, + references: [], + }, + ], + }); + unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ + id: '1', + type: 'alert', + attributes: { + alertTypeId: '123', + schedule: { interval: '10s' }, + params: { + bar: true, + }, + createdAt: '2019-02-12T21:01:22.479Z', + actions: [ + { + group: 'default', + actionRef: 'action_0', + actionTypeId: 'test', + params: { + foo: true, + }, + }, + ], + }, + references: [ + { + name: 'action_0', + type: 'action', + id: '1', + }, + ], + }); + taskManager.schedule.mockResolvedValueOnce({ + id: 'task-123', + taskType: 'alerting:123', + scheduledAt: new Date(), + attempts: 1, + status: TaskStatus.Idle, + runAt: new Date(), + startedAt: null, + retryAt: null, + state: {}, + params: {}, + ownerId: null, + }); + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ + id: '1', + type: 'alert', + attributes: { + actions: [], + scheduledTaskId: 'task-123', + }, + references: [ + { + id: '1', + name: 'action_0', + type: 'action', + }, + ], + }); + + return alertsClient.create(options); + } + + test('ensures user is authorised to create this type of alert under the consumer', async () => { + const data = getMockData({ + alertTypeId: 'myType', + consumer: 'myApp', + }); + + await tryToExecuteOperation({ data }); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'create'); + }); + + test('throws when user is not authorised to create this type of alert', async () => { + const data = getMockData({ + alertTypeId: 'myType', + consumer: 'myApp', + }); + + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to create a "myType" alert for "myApp"`) + ); + + await expect(tryToExecuteOperation({ data })).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to create a "myType" alert for "myApp"]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'create'); }); }); test('creates an alert', async () => { const data = getMockData(); - savedObjectsClient.create.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -168,10 +285,11 @@ describe('create()', () => { params: {}, ownerId: null, }); - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + actions: [], scheduledTaskId: 'task-123', }, references: [ @@ -183,6 +301,7 @@ describe('create()', () => { ], }); const result = await alertsClient.create({ data }); + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('123', 'bar', 'create'); expect(result).toMatchInlineSnapshot(` Object { "actions": Array [ @@ -208,10 +327,10 @@ describe('create()', () => { "updatedAt": 2019-02-12T21:01:22.479Z, } `); - expect(savedObjectsClient.create).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.create.mock.calls[0]).toHaveLength(3); - expect(savedObjectsClient.create.mock.calls[0][0]).toEqual('alert'); - expect(savedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.create.mock.calls[0]).toHaveLength(3); + expect(unsecuredSavedObjectsClient.create.mock.calls[0][0]).toEqual('alert'); + expect(unsecuredSavedObjectsClient.create.mock.calls[0][1]).toMatchInlineSnapshot(` Object { "actions": Array [ Object { @@ -246,7 +365,7 @@ describe('create()', () => { "updatedBy": "elastic", } `); - expect(savedObjectsClient.create.mock.calls[0][2]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.create.mock.calls[0][2]).toMatchInlineSnapshot(` Object { "references": Array [ Object { @@ -277,11 +396,11 @@ describe('create()', () => { }, ] `); - expect(savedObjectsClient.update).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.update.mock.calls[0]).toHaveLength(3); - expect(savedObjectsClient.update.mock.calls[0][0]).toEqual('alert'); - expect(savedObjectsClient.update.mock.calls[0][1]).toEqual('1'); - expect(savedObjectsClient.update.mock.calls[0][2]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.update.mock.calls[0]).toHaveLength(3); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][0]).toEqual('alert'); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][1]).toEqual('1'); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][2]).toMatchInlineSnapshot(` Object { "scheduledTaskId": "task-123", } @@ -314,7 +433,7 @@ describe('create()', () => { }, ], }); - savedObjectsClient.create.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -382,10 +501,11 @@ describe('create()', () => { params: {}, ownerId: null, }); - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + actions: [], scheduledTaskId: 'task-123', }, references: [], @@ -436,19 +556,20 @@ describe('create()', () => { test('creates a disabled alert', async () => { const data = getMockData({ enabled: false }); - savedObjectsClient.bulkGet.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { id: '1', type: 'action', attributes: { + actions: [], actionTypeId: 'test', }, references: [], }, ], }); - savedObjectsClient.create.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -504,7 +625,7 @@ describe('create()', () => { "updatedAt": 2019-02-12T21:01:22.479Z, } `); - expect(savedObjectsClient.create).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(1); expect(taskManager.schedule).toHaveBeenCalledTimes(0); }); @@ -527,7 +648,7 @@ describe('create()', () => { }), }, async executor() {}, - producer: 'alerting', + producer: 'alerts', }); await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"params invalid: [param1]: expected value of type [string] but got [undefined]"` @@ -542,25 +663,26 @@ describe('create()', () => { await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"Test Error"` ); - expect(savedObjectsClient.create).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.create).not.toHaveBeenCalled(); expect(taskManager.schedule).not.toHaveBeenCalled(); }); test('throws error if create saved object fails', async () => { const data = getMockData(); - savedObjectsClient.bulkGet.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { id: '1', type: 'action', attributes: { + actions: [], actionTypeId: 'test', }, references: [], }, ], }); - savedObjectsClient.create.mockRejectedValueOnce(new Error('Test failure')); + unsecuredSavedObjectsClient.create.mockRejectedValueOnce(new Error('Test failure')); await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"Test failure"` ); @@ -569,19 +691,20 @@ describe('create()', () => { test('attempts to remove saved object if scheduling failed', async () => { const data = getMockData(); - savedObjectsClient.bulkGet.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { id: '1', type: 'action', attributes: { + actions: [], actionTypeId: 'test', }, references: [], }, ], }); - savedObjectsClient.create.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -610,12 +733,12 @@ describe('create()', () => { ], }); taskManager.schedule.mockRejectedValueOnce(new Error('Test failure')); - savedObjectsClient.delete.mockResolvedValueOnce({}); + unsecuredSavedObjectsClient.delete.mockResolvedValueOnce({}); await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"Test failure"` ); - expect(savedObjectsClient.delete).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.delete.mock.calls[0]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.delete.mock.calls[0]).toMatchInlineSnapshot(` Array [ "alert", "1", @@ -625,19 +748,20 @@ describe('create()', () => { test('returns task manager error if cleanup fails, logs to console', async () => { const data = getMockData(); - savedObjectsClient.bulkGet.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { id: '1', type: 'action', attributes: { + actions: [], actionTypeId: 'test', }, references: [], }, ], }); - savedObjectsClient.create.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -666,7 +790,9 @@ describe('create()', () => { ], }); taskManager.schedule.mockRejectedValueOnce(new Error('Task manager error')); - savedObjectsClient.delete.mockRejectedValueOnce(new Error('Saved object delete error')); + unsecuredSavedObjectsClient.delete.mockRejectedValueOnce( + new Error('Saved object delete error') + ); await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"Task manager error"` ); @@ -689,21 +815,22 @@ describe('create()', () => { const data = getMockData(); alertsClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, - result: { id: '123', api_key: 'abc' }, + result: { id: '123', name: '123', api_key: 'abc' }, }); - savedObjectsClient.bulkGet.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { id: '1', type: 'action', attributes: { + actions: [], actionTypeId: 'test', }, references: [], }, ], }); - savedObjectsClient.create.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -744,10 +871,11 @@ describe('create()', () => { params: {}, ownerId: null, }); - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + actions: [], scheduledTaskId: 'task-123', }, references: [ @@ -761,7 +889,7 @@ describe('create()', () => { await alertsClient.create({ data }); expect(alertsClientParams.createAPIKey).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.create).toHaveBeenCalledWith( + expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( 'alert', { actions: [ @@ -802,19 +930,20 @@ describe('create()', () => { test(`doesn't create API key for disabled alerts`, async () => { const data = getMockData({ enabled: false }); - savedObjectsClient.bulkGet.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { id: '1', type: 'action', attributes: { + actions: [], actionTypeId: 'test', }, references: [], }, ], }); - savedObjectsClient.create.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -855,10 +984,11 @@ describe('create()', () => { params: {}, ownerId: null, }); - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + actions: [], scheduledTaskId: 'task-123', }, references: [ @@ -872,7 +1002,7 @@ describe('create()', () => { await alertsClient.create({ data }); expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled(); - expect(savedObjectsClient.create).toHaveBeenCalledWith( + expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledWith( 'alert', { actions: [ @@ -918,9 +1048,21 @@ describe('enable()', () => { id: '1', type: 'alert', attributes: { + consumer: 'myApp', schedule: { interval: '10s' }, - alertTypeId: '2', + alertTypeId: 'myType', enabled: false, + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], }, version: '123', references: [], @@ -929,7 +1071,7 @@ describe('enable()', () => { beforeEach(() => { alertsClient = new AlertsClient(alertsClientParams); encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingAlert); - savedObjectsClient.get.mockResolvedValue(existingAlert); + unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert); alertsClientParams.createAPIKey.mockResolvedValue({ apiKeysEnabled: false, }); @@ -948,31 +1090,85 @@ describe('enable()', () => { }); }); + describe('authorization', () => { + beforeEach(() => { + encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingAlert); + unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert); + alertsClientParams.createAPIKey.mockResolvedValue({ + apiKeysEnabled: false, + }); + taskManager.schedule.mockResolvedValue({ + id: 'task-123', + scheduledAt: new Date(), + attempts: 0, + status: TaskStatus.Idle, + runAt: new Date(), + state: {}, + params: {}, + taskType: '', + startedAt: null, + retryAt: null, + ownerId: null, + }); + }); + + test('ensures user is authorised to enable this type of alert under the consumer', async () => { + await alertsClient.enable({ id: '1' }); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'enable'); + expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute'); + }); + + test('throws when user is not authorised to enable this type of alert', async () => { + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to enable a "myType" alert for "myApp"`) + ); + + await expect(alertsClient.enable({ id: '1' })).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to enable a "myType" alert for "myApp"]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'enable'); + }); + }); + test('enables an alert', async () => { await alertsClient.enable({ id: '1' }); - expect(savedObjectsClient.get).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', }); expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled(); expect(alertsClientParams.createAPIKey).toHaveBeenCalled(); - expect(savedObjectsClient.update).toHaveBeenCalledWith( + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', { schedule: { interval: '10s' }, - alertTypeId: '2', + alertTypeId: 'myType', + consumer: 'myApp', enabled: true, updatedBy: 'elastic', apiKey: null, apiKeyOwner: null, + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], }, { version: '123', } ); expect(taskManager.schedule).toHaveBeenCalledWith({ - taskType: `alerting:2`, + taskType: `alerting:myType`, params: { alertId: '1', spaceId: 'default', @@ -984,7 +1180,7 @@ describe('enable()', () => { }, scope: ['alerting'], }); - expect(savedObjectsClient.update).toHaveBeenCalledWith('alert', '1', { + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith('alert', '1', { scheduledTaskId: 'task-123', }); }); @@ -999,7 +1195,7 @@ describe('enable()', () => { }); await alertsClient.enable({ id: '1' }); - expect(savedObjectsClient.get).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', }); @@ -1018,27 +1214,39 @@ describe('enable()', () => { await alertsClient.enable({ id: '1' }); expect(alertsClientParams.getUserName).not.toHaveBeenCalled(); expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled(); - expect(savedObjectsClient.update).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled(); expect(taskManager.schedule).not.toHaveBeenCalled(); }); test('sets API key when createAPIKey returns one', async () => { alertsClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, - result: { id: '123', api_key: 'abc' }, + result: { id: '123', name: '123', api_key: 'abc' }, }); await alertsClient.enable({ id: '1' }); - expect(savedObjectsClient.update).toHaveBeenCalledWith( + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', { schedule: { interval: '10s' }, - alertTypeId: '2', + alertTypeId: 'myType', + consumer: 'myApp', enabled: true, apiKey: Buffer.from('123:abc').toString('base64'), apiKeyOwner: 'elastic', updatedBy: 'elastic', + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], }, { version: '123', @@ -1050,7 +1258,7 @@ describe('enable()', () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail')); await alertsClient.enable({ id: '1' }); - expect(savedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); expect(alertsClientParams.logger.error).toHaveBeenCalledWith( 'enable(): Failed to load API key to invalidate on alert 1: Fail' ); @@ -1058,45 +1266,47 @@ describe('enable()', () => { test('throws error when failing to load the saved object using SOC', async () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail')); - savedObjectsClient.get.mockRejectedValueOnce(new Error('Fail to get')); + unsecuredSavedObjectsClient.get.mockRejectedValueOnce(new Error('Fail to get')); await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Fail to get"` ); expect(alertsClientParams.getUserName).not.toHaveBeenCalled(); expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled(); - expect(savedObjectsClient.update).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled(); expect(taskManager.schedule).not.toHaveBeenCalled(); }); test('throws error when failing to update the first time', async () => { - savedObjectsClient.update.mockRejectedValueOnce(new Error('Fail to update')); + unsecuredSavedObjectsClient.update.mockRejectedValueOnce(new Error('Fail to update')); await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Fail to update"` ); expect(alertsClientParams.getUserName).toHaveBeenCalled(); expect(alertsClientParams.createAPIKey).toHaveBeenCalled(); - expect(savedObjectsClient.update).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1); expect(taskManager.schedule).not.toHaveBeenCalled(); }); test('throws error when failing to update the second time', async () => { - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ ...existingAlert, attributes: { ...existingAlert.attributes, enabled: true, }, }); - savedObjectsClient.update.mockRejectedValueOnce(new Error('Fail to update second time')); + unsecuredSavedObjectsClient.update.mockRejectedValueOnce( + new Error('Fail to update second time') + ); await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Fail to update second time"` ); expect(alertsClientParams.getUserName).toHaveBeenCalled(); expect(alertsClientParams.createAPIKey).toHaveBeenCalled(); - expect(savedObjectsClient.update).toHaveBeenCalledTimes(2); + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(2); expect(taskManager.schedule).toHaveBeenCalled(); }); @@ -1108,7 +1318,7 @@ describe('enable()', () => { ); expect(alertsClientParams.getUserName).toHaveBeenCalled(); expect(alertsClientParams.createAPIKey).toHaveBeenCalled(); - expect(savedObjectsClient.update).toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled(); }); }); @@ -1118,10 +1328,22 @@ describe('disable()', () => { id: '1', type: 'alert', attributes: { + consumer: 'myApp', schedule: { interval: '10s' }, - alertTypeId: '2', + alertTypeId: 'myType', enabled: true, scheduledTaskId: 'task-123', + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], }, version: '123', references: [], @@ -1136,27 +1358,59 @@ describe('disable()', () => { beforeEach(() => { alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValue(existingAlert); + unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert); encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingDecryptedAlert); }); + describe('authorization', () => { + test('ensures user is authorised to disable this type of alert under the consumer', async () => { + await alertsClient.disable({ id: '1' }); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'disable'); + }); + + test('throws when user is not authorised to disable this type of alert', async () => { + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to disable a "myType" alert for "myApp"`) + ); + + await expect(alertsClient.disable({ id: '1' })).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to disable a "myType" alert for "myApp"]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'disable'); + }); + }); + test('disables an alert', async () => { await alertsClient.disable({ id: '1' }); - expect(savedObjectsClient.get).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', }); - expect(savedObjectsClient.update).toHaveBeenCalledWith( + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', { + consumer: 'myApp', schedule: { interval: '10s' }, - alertTypeId: '2', + alertTypeId: 'myType', apiKey: null, apiKeyOwner: null, enabled: false, scheduledTaskId: null, updatedBy: 'elastic', + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], }, { version: '123', @@ -1170,21 +1424,33 @@ describe('disable()', () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail')); await alertsClient.disable({ id: '1' }); - expect(savedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', }); - expect(savedObjectsClient.update).toHaveBeenCalledWith( + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', { + consumer: 'myApp', schedule: { interval: '10s' }, - alertTypeId: '2', + alertTypeId: 'myType', apiKey: null, apiKeyOwner: null, enabled: false, scheduledTaskId: null, updatedBy: 'elastic', + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], }, { version: '123', @@ -1199,12 +1465,13 @@ describe('disable()', () => { ...existingDecryptedAlert, attributes: { ...existingDecryptedAlert.attributes, + actions: [], enabled: false, }, }); await alertsClient.disable({ id: '1' }); - expect(savedObjectsClient.update).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled(); expect(taskManager.remove).not.toHaveBeenCalled(); expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled(); }); @@ -1220,7 +1487,7 @@ describe('disable()', () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail')); await alertsClient.disable({ id: '1' }); - expect(savedObjectsClient.update).toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled(); expect(taskManager.remove).toHaveBeenCalled(); expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled(); expect(alertsClientParams.logger.error).toHaveBeenCalledWith( @@ -1228,8 +1495,8 @@ describe('disable()', () => { ); }); - test('throws when savedObjectsClient update fails', async () => { - savedObjectsClient.update.mockRejectedValueOnce(new Error('Failed to update')); + test('throws when unsecuredSavedObjectsClient update fails', async () => { + unsecuredSavedObjectsClient.update.mockRejectedValueOnce(new Error('Failed to update')); await expect(alertsClient.disable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Failed to update"` @@ -1257,52 +1524,181 @@ describe('disable()', () => { describe('muteAll()', () => { test('mutes an alert', async () => { const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], muteAll: false, }, references: [], }); await alertsClient.muteAll({ id: '1' }); - expect(savedObjectsClient.update).toHaveBeenCalledWith('alert', '1', { + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith('alert', '1', { muteAll: true, mutedInstanceIds: [], updatedBy: 'elastic', }); }); + + describe('authorization', () => { + beforeEach(() => { + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ + id: '1', + type: 'alert', + attributes: { + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], + consumer: 'myApp', + schedule: { interval: '10s' }, + alertTypeId: 'myType', + apiKey: null, + apiKeyOwner: null, + enabled: false, + scheduledTaskId: null, + updatedBy: 'elastic', + muteAll: false, + }, + references: [], + }); + }); + + test('ensures user is authorised to muteAll this type of alert under the consumer', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + await alertsClient.muteAll({ id: '1' }); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'muteAll'); + expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute'); + }); + + test('throws when user is not authorised to muteAll this type of alert', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to muteAll a "myType" alert for "myApp"`) + ); + + await expect(alertsClient.muteAll({ id: '1' })).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to muteAll a "myType" alert for "myApp"]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'muteAll'); + }); + }); }); describe('unmuteAll()', () => { test('unmutes an alert', async () => { const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], muteAll: true, }, references: [], }); await alertsClient.unmuteAll({ id: '1' }); - expect(savedObjectsClient.update).toHaveBeenCalledWith('alert', '1', { + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith('alert', '1', { muteAll: false, mutedInstanceIds: [], updatedBy: 'elastic', }); }); + + describe('authorization', () => { + beforeEach(() => { + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ + id: '1', + type: 'alert', + attributes: { + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], + consumer: 'myApp', + schedule: { interval: '10s' }, + alertTypeId: 'myType', + apiKey: null, + apiKeyOwner: null, + enabled: false, + scheduledTaskId: null, + updatedBy: 'elastic', + muteAll: false, + }, + references: [], + }); + }); + + test('ensures user is authorised to unmuteAll this type of alert under the consumer', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + await alertsClient.unmuteAll({ id: '1' }); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'unmuteAll'); + expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute'); + }); + + test('throws when user is not authorised to unmuteAll this type of alert', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to unmuteAll a "myType" alert for "myApp"`) + ); + + await expect(alertsClient.unmuteAll({ id: '1' })).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to unmuteAll a "myType" alert for "myApp"]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'unmuteAll'); + }); + }); }); describe('muteInstance()', () => { test('mutes an alert instance', async () => { const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + actions: [], schedule: { interval: '10s' }, alertTypeId: '2', enabled: true, @@ -1314,7 +1710,7 @@ describe('muteInstance()', () => { }); await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); - expect(savedObjectsClient.update).toHaveBeenCalledWith( + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', { @@ -1327,10 +1723,11 @@ describe('muteInstance()', () => { test('skips muting when alert instance already muted', async () => { const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + actions: [], schedule: { interval: '10s' }, alertTypeId: '2', enabled: true, @@ -1341,15 +1738,16 @@ describe('muteInstance()', () => { }); await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); - expect(savedObjectsClient.update).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled(); }); test('skips muting when alert is muted', async () => { const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + actions: [], schedule: { interval: '10s' }, alertTypeId: '2', enabled: true, @@ -1361,17 +1759,79 @@ describe('muteInstance()', () => { }); await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); - expect(savedObjectsClient.update).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled(); + }); + + describe('authorization', () => { + beforeEach(() => { + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ + id: '1', + type: 'alert', + attributes: { + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], + schedule: { interval: '10s' }, + alertTypeId: 'myType', + consumer: 'myApp', + enabled: true, + scheduledTaskId: 'task-123', + mutedInstanceIds: [], + }, + version: '123', + references: [], + }); + }); + + test('ensures user is authorised to muteInstance this type of alert under the consumer', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + await alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' }); + + expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute'); + expect(authorization.ensureAuthorized).toHaveBeenCalledWith( + 'myType', + 'myApp', + 'muteInstance' + ); + }); + + test('throws when user is not authorised to muteInstance this type of alert', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to muteInstance a "myType" alert for "myApp"`) + ); + + await expect( + alertsClient.muteInstance({ alertId: '1', alertInstanceId: '2' }) + ).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to muteInstance a "myType" alert for "myApp"]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith( + 'myType', + 'myApp', + 'muteInstance' + ); + }); }); }); describe('unmuteInstance()', () => { test('unmutes an alert instance', async () => { const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + actions: [], schedule: { interval: '10s' }, alertTypeId: '2', enabled: true, @@ -1383,7 +1843,7 @@ describe('unmuteInstance()', () => { }); await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); - expect(savedObjectsClient.update).toHaveBeenCalledWith( + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', { @@ -1396,10 +1856,11 @@ describe('unmuteInstance()', () => { test('skips unmuting when alert instance not muted', async () => { const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + actions: [], schedule: { interval: '10s' }, alertTypeId: '2', enabled: true, @@ -1410,15 +1871,16 @@ describe('unmuteInstance()', () => { }); await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); - expect(savedObjectsClient.update).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled(); }); test('skips unmuting when alert is muted', async () => { const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + actions: [], schedule: { interval: '10s' }, alertTypeId: '2', enabled: true, @@ -1430,14 +1892,75 @@ describe('unmuteInstance()', () => { }); await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); - expect(savedObjectsClient.update).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.update).not.toHaveBeenCalled(); + }); + + describe('authorization', () => { + beforeEach(() => { + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ + id: '1', + type: 'alert', + attributes: { + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], + alertTypeId: 'myType', + consumer: 'myApp', + schedule: { interval: '10s' }, + enabled: true, + scheduledTaskId: 'task-123', + mutedInstanceIds: ['2'], + }, + version: '123', + references: [], + }); + }); + + test('ensures user is authorised to unmuteInstance this type of alert under the consumer', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + await alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }); + + expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute'); + expect(authorization.ensureAuthorized).toHaveBeenCalledWith( + 'myType', + 'myApp', + 'unmuteInstance' + ); + }); + + test('throws when user is not authorised to unmuteInstance this type of alert', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to unmuteInstance a "myType" alert for "myApp"`) + ); + + await expect( + alertsClient.unmuteInstance({ alertId: '1', alertInstanceId: '2' }) + ).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to unmuteInstance a "myType" alert for "myApp"]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith( + 'myType', + 'myApp', + 'unmuteInstance' + ); + }); }); }); describe('get()', () => { test('calls saved objects client with given params', async () => { const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -1446,6 +1969,7 @@ describe('get()', () => { params: { bar: true, }, + createdAt: new Date().toISOString(), actions: [ { group: 'default', @@ -1488,8 +2012,8 @@ describe('get()', () => { "updatedAt": 2019-02-12T21:01:22.479Z, } `); - expect(savedObjectsClient.get).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(` Array [ "alert", "1", @@ -1499,7 +2023,7 @@ describe('get()', () => { test(`throws an error when references aren't found`, async () => { const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -1517,19 +2041,72 @@ describe('get()', () => { }, }, ], - }, - references: [], + }, + references: [], + }); + await expect(alertsClient.get({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + `"Action reference \\"action_0\\" not found in alert id: 1"` + ); + }); + + describe('authorization', () => { + beforeEach(() => { + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ + id: '1', + type: 'alert', + attributes: { + alertTypeId: 'myType', + consumer: 'myApp', + schedule: { interval: '10s' }, + params: { + bar: true, + }, + actions: [ + { + group: 'default', + actionRef: 'action_0', + params: { + foo: true, + }, + }, + ], + }, + references: [ + { + name: 'action_0', + type: 'action', + id: '1', + }, + ], + }); + }); + + test('ensures user is authorised to get this type of alert under the consumer', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + await alertsClient.get({ id: '1' }); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'get'); + }); + + test('throws when user is not authorised to get this type of alert', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to get a "myType" alert for "myApp"`) + ); + + await expect(alertsClient.get({ id: '1' })).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to get a "myType" alert for "myApp"]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'get'); }); - await expect(alertsClient.get({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( - `"Reference action_0 not found"` - ); }); }); describe('getAlertState()', () => { test('calls saved objects client with given params', async () => { const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -1572,8 +2149,8 @@ describe('getAlertState()', () => { }); await alertsClient.getAlertState({ id: '1' }); - expect(savedObjectsClient.get).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.get.mock.calls[0]).toMatchInlineSnapshot(` Array [ "alert", "1", @@ -1586,7 +2163,7 @@ describe('getAlertState()', () => { const scheduledTaskId = 'task-123'; - savedObjectsClient.get.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -1638,12 +2215,103 @@ describe('getAlertState()', () => { expect(taskManager.get).toHaveBeenCalledTimes(1); expect(taskManager.get).toHaveBeenCalledWith(scheduledTaskId); }); + + describe('authorization', () => { + beforeEach(() => { + unsecuredSavedObjectsClient.get.mockResolvedValueOnce({ + id: '1', + type: 'alert', + attributes: { + alertTypeId: 'myType', + consumer: 'myApp', + schedule: { interval: '10s' }, + params: { + bar: true, + }, + actions: [ + { + group: 'default', + actionRef: 'action_0', + params: { + foo: true, + }, + }, + ], + }, + references: [ + { + name: 'action_0', + type: 'action', + id: '1', + }, + ], + }); + + taskManager.get.mockResolvedValueOnce({ + id: '1', + taskType: 'alerting:123', + scheduledAt: new Date(), + attempts: 1, + status: TaskStatus.Idle, + runAt: new Date(), + startedAt: null, + retryAt: null, + state: {}, + params: {}, + ownerId: null, + }); + }); + + test('ensures user is authorised to get this type of alert under the consumer', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + await alertsClient.getAlertState({ id: '1' }); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith( + 'myType', + 'myApp', + 'getAlertState' + ); + }); + + test('throws when user is not authorised to getAlertState this type of alert', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + // `get` check + authorization.ensureAuthorized.mockResolvedValueOnce(); + // `getAlertState` check + authorization.ensureAuthorized.mockRejectedValueOnce( + new Error(`Unauthorized to getAlertState a "myType" alert for "myApp"`) + ); + + await expect(alertsClient.getAlertState({ id: '1' })).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to getAlertState a "myType" alert for "myApp"]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith( + 'myType', + 'myApp', + 'getAlertState' + ); + }); + }); }); describe('find()', () => { - test('calls saved objects client with given params', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.find.mockResolvedValueOnce({ + const listedTypes = new Set([ + { + actionGroups: [], + actionVariables: undefined, + defaultActionGroupId: 'default', + id: 'myType', + name: 'myType', + producer: 'myApp', + }, + ]); + beforeEach(() => { + authorization.getFindAuthorizationFilter.mockResolvedValue({ + ensureAlertTypeIsAuthorized() {}, + logSuccessfulAuthorization() {}, + }); + unsecuredSavedObjectsClient.find.mockResolvedValueOnce({ total: 1, per_page: 10, page: 1, @@ -1652,11 +2320,12 @@ describe('find()', () => { id: '1', type: 'alert', attributes: { - alertTypeId: '123', + alertTypeId: 'myType', schedule: { interval: '10s' }, params: { bar: true, }, + createdAt: new Date().toISOString(), actions: [ { group: 'default', @@ -1678,6 +2347,25 @@ describe('find()', () => { }, ], }); + alertTypeRegistry.list.mockReturnValue(listedTypes); + authorization.filterByAlertTypeAuthorization.mockResolvedValue( + new Set([ + { + id: 'myType', + name: 'Test', + actionGroups: [{ id: 'default', name: 'Default' }], + defaultActionGroupId: 'default', + producer: 'alerts', + authorizedConsumers: { + myApp: { read: true, all: true }, + }, + }, + ]) + ); + }); + + test('calls saved objects client with given params', async () => { + const alertsClient = new AlertsClient(alertsClientParams); const result = await alertsClient.find({ options: {} }); expect(result).toMatchInlineSnapshot(` Object { @@ -1692,7 +2380,7 @@ describe('find()', () => { }, }, ], - "alertTypeId": "123", + "alertTypeId": "myType", "createdAt": 2019-02-12T21:01:22.479Z, "id": "1", "params": Object { @@ -1709,14 +2397,100 @@ describe('find()', () => { "total": 1, } `); - expect(savedObjectsClient.find).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.find.mock.calls[0]).toMatchInlineSnapshot(` - Array [ - Object { - "type": "alert", - }, - ] - `); + expect(unsecuredSavedObjectsClient.find).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.find.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + Object { + "fields": undefined, + "type": "alert", + }, + ] + `); + }); + + describe('authorization', () => { + test('ensures user is query filter types down to those the user is authorized to find', async () => { + authorization.getFindAuthorizationFilter.mockResolvedValue({ + filter: + '((alert.attributes.alertTypeId:myType and alert.attributes.consumer:myApp) or (alert.attributes.alertTypeId:myOtherType and alert.attributes.consumer:myApp) or (alert.attributes.alertTypeId:myOtherType and alert.attributes.consumer:myOtherApp))', + ensureAlertTypeIsAuthorized() {}, + logSuccessfulAuthorization() {}, + }); + + const alertsClient = new AlertsClient(alertsClientParams); + await alertsClient.find({ options: { filter: 'someTerm' } }); + + const [options] = unsecuredSavedObjectsClient.find.mock.calls[0]; + expect(options.filter).toMatchInlineSnapshot( + `"someTerm and ((alert.attributes.alertTypeId:myType and alert.attributes.consumer:myApp) or (alert.attributes.alertTypeId:myOtherType and alert.attributes.consumer:myApp) or (alert.attributes.alertTypeId:myOtherType and alert.attributes.consumer:myOtherApp))"` + ); + expect(authorization.getFindAuthorizationFilter).toHaveBeenCalledTimes(1); + }); + + test('throws if user is not authorized to find any types', async () => { + const alertsClient = new AlertsClient(alertsClientParams); + authorization.getFindAuthorizationFilter.mockRejectedValue(new Error('not authorized')); + await expect(alertsClient.find({ options: {} })).rejects.toThrowErrorMatchingInlineSnapshot( + `"not authorized"` + ); + }); + + test('ensures authorization even when the fields required to authorize are omitted from the find', async () => { + const ensureAlertTypeIsAuthorized = jest.fn(); + const logSuccessfulAuthorization = jest.fn(); + authorization.getFindAuthorizationFilter.mockResolvedValue({ + filter: '', + ensureAlertTypeIsAuthorized, + logSuccessfulAuthorization, + }); + + unsecuredSavedObjectsClient.find.mockReset(); + unsecuredSavedObjectsClient.find.mockResolvedValue({ + total: 1, + per_page: 10, + page: 1, + saved_objects: [ + { + id: '1', + type: 'alert', + attributes: { + actions: [], + alertTypeId: 'myType', + consumer: 'myApp', + tags: ['myTag'], + }, + score: 1, + references: [], + }, + ], + }); + + const alertsClient = new AlertsClient(alertsClientParams); + expect(await alertsClient.find({ options: { fields: ['tags'] } })).toMatchInlineSnapshot(` + Object { + "data": Array [ + Object { + "actions": Array [], + "id": "1", + "schedule": undefined, + "tags": Array [ + "myTag", + ], + }, + ], + "page": 1, + "perPage": 10, + "total": 1, + } + `); + + expect(unsecuredSavedObjectsClient.find).toHaveBeenCalledWith({ + fields: ['tags', 'alertTypeId', 'consumer'], + type: 'alert', + }); + expect(ensureAlertTypeIsAuthorized).toHaveBeenCalledWith('myType', 'myApp'); + expect(logSuccessfulAuthorization).toHaveBeenCalled(); + }); }); }); @@ -1726,7 +2500,8 @@ describe('delete()', () => { id: '1', type: 'alert', attributes: { - alertTypeId: '123', + alertTypeId: 'myType', + consumer: 'myApp', schedule: { interval: '10s' }, params: { bar: true, @@ -1735,6 +2510,7 @@ describe('delete()', () => { actions: [ { group: 'default', + actionTypeId: '.no-op', actionRef: 'action_0', params: { foo: true, @@ -1760,8 +2536,8 @@ describe('delete()', () => { beforeEach(() => { alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValue(existingAlert); - savedObjectsClient.delete.mockResolvedValue({ + unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert); + unsecuredSavedObjectsClient.delete.mockResolvedValue({ success: true, }); encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingDecryptedAlert); @@ -1770,13 +2546,13 @@ describe('delete()', () => { test('successfully removes an alert', async () => { const result = await alertsClient.delete({ id: '1' }); expect(result).toEqual({ success: true }); - expect(savedObjectsClient.delete).toHaveBeenCalledWith('alert', '1'); + expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledWith('alert', '1'); expect(taskManager.remove).toHaveBeenCalledWith('task-123'); expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' }); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', }); - expect(savedObjectsClient.get).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); }); test('falls back to SOC.get when getDecryptedAsInternalUser throws an error', async () => { @@ -1784,10 +2560,10 @@ describe('delete()', () => { const result = await alertsClient.delete({ id: '1' }); expect(result).toEqual({ success: true }); - expect(savedObjectsClient.delete).toHaveBeenCalledWith('alert', '1'); + expect(unsecuredSavedObjectsClient.delete).toHaveBeenCalledWith('alert', '1'); expect(taskManager.remove).toHaveBeenCalledWith('task-123'); expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled(); - expect(savedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); expect(alertsClientParams.logger.error).toHaveBeenCalledWith( 'delete(): Failed to load API key to invalidate on alert 1: Fail' ); @@ -1839,9 +2615,9 @@ describe('delete()', () => { ); }); - test('throws error when savedObjectsClient.get throws an error', async () => { + test('throws error when unsecuredSavedObjectsClient.get throws an error', async () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail')); - savedObjectsClient.get.mockRejectedValue(new Error('SOC Fail')); + unsecuredSavedObjectsClient.get.mockRejectedValue(new Error('SOC Fail')); await expect(alertsClient.delete({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"SOC Fail"` @@ -1855,6 +2631,26 @@ describe('delete()', () => { `"TM Fail"` ); }); + + describe('authorization', () => { + test('ensures user is authorised to delete this type of alert under the consumer', async () => { + await alertsClient.delete({ id: '1' }); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'delete'); + }); + + test('throws when user is not authorised to delete this type of alert', async () => { + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to delete a "myType" alert for "myApp"`) + ); + + await expect(alertsClient.delete({ id: '1' })).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to delete a "myType" alert for "myApp"]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'delete'); + }); + }); }); describe('update()', () => { @@ -1864,8 +2660,20 @@ describe('update()', () => { type: 'alert', attributes: { enabled: true, - alertTypeId: '123', + alertTypeId: 'myType', + consumer: 'myApp', scheduledTaskId: 'task-123', + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], }, references: [], version: '123', @@ -1880,7 +2688,7 @@ describe('update()', () => { beforeEach(() => { alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValue(existingAlert); + unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert); encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingDecryptedAlert); alertTypeRegistry.get.mockReturnValue({ id: '123', @@ -1888,12 +2696,12 @@ describe('update()', () => { actionGroups: [{ id: 'default', name: 'Default' }], defaultActionGroupId: 'default', async executor() {}, - producer: 'alerting', + producer: 'alerts', }); }); test('updates given parameters', async () => { - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -2029,12 +2837,12 @@ describe('update()', () => { expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', }); - expect(savedObjectsClient.get).not.toHaveBeenCalled(); - expect(savedObjectsClient.update).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.update.mock.calls[0]).toHaveLength(4); - expect(savedObjectsClient.update.mock.calls[0][0]).toEqual('alert'); - expect(savedObjectsClient.update.mock.calls[0][1]).toEqual('1'); - expect(savedObjectsClient.update.mock.calls[0][2]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.update.mock.calls[0]).toHaveLength(4); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][0]).toEqual('alert'); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][1]).toEqual('1'); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][2]).toMatchInlineSnapshot(` Object { "actions": Array [ Object { @@ -2062,9 +2870,10 @@ describe('update()', () => { }, }, ], - "alertTypeId": "123", + "alertTypeId": "myType", "apiKey": null, "apiKeyOwner": null, + "consumer": "myApp", "enabled": true, "name": "abc", "params": Object { @@ -2081,7 +2890,7 @@ describe('update()', () => { "updatedBy": "elastic", } `); - expect(savedObjectsClient.update.mock.calls[0][3]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.update.mock.calls[0][3]).toMatchInlineSnapshot(` Object { "references": Array [ Object { @@ -2106,12 +2915,13 @@ describe('update()', () => { }); it('calls the createApiKey function', async () => { - savedObjectsClient.bulkGet.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { id: '1', type: 'action', attributes: { + actions: [], actionTypeId: 'test', }, references: [], @@ -2120,9 +2930,9 @@ describe('update()', () => { }); alertsClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, - result: { id: '123', api_key: 'abc' }, + result: { id: '123', name: '123', api_key: 'abc' }, }); - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -2201,11 +3011,11 @@ describe('update()', () => { "updatedAt": 2019-02-12T21:01:22.479Z, } `); - expect(savedObjectsClient.update).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.update.mock.calls[0]).toHaveLength(4); - expect(savedObjectsClient.update.mock.calls[0][0]).toEqual('alert'); - expect(savedObjectsClient.update.mock.calls[0][1]).toEqual('1'); - expect(savedObjectsClient.update.mock.calls[0][2]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.update.mock.calls[0]).toHaveLength(4); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][0]).toEqual('alert'); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][1]).toEqual('1'); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][2]).toMatchInlineSnapshot(` Object { "actions": Array [ Object { @@ -2217,9 +3027,10 @@ describe('update()', () => { }, }, ], - "alertTypeId": "123", + "alertTypeId": "myType", "apiKey": "MTIzOmFiYw==", "apiKeyOwner": "elastic", + "consumer": "myApp", "enabled": true, "name": "abc", "params": Object { @@ -2236,7 +3047,7 @@ describe('update()', () => { "updatedBy": "elastic", } `); - expect(savedObjectsClient.update.mock.calls[0][3]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.update.mock.calls[0][3]).toMatchInlineSnapshot(` Object { "references": Array [ Object { @@ -2258,19 +3069,20 @@ describe('update()', () => { enabled: false, }, }); - savedObjectsClient.bulkGet.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { id: '1', type: 'action', attributes: { + actions: [], actionTypeId: 'test', }, references: [], }, ], }); - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -2350,11 +3162,11 @@ describe('update()', () => { "updatedAt": 2019-02-12T21:01:22.479Z, } `); - expect(savedObjectsClient.update).toHaveBeenCalledTimes(1); - expect(savedObjectsClient.update.mock.calls[0]).toHaveLength(4); - expect(savedObjectsClient.update.mock.calls[0][0]).toEqual('alert'); - expect(savedObjectsClient.update.mock.calls[0][1]).toEqual('1'); - expect(savedObjectsClient.update.mock.calls[0][2]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.update.mock.calls[0]).toHaveLength(4); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][0]).toEqual('alert'); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][1]).toEqual('1'); + expect(unsecuredSavedObjectsClient.update.mock.calls[0][2]).toMatchInlineSnapshot(` Object { "actions": Array [ Object { @@ -2366,9 +3178,10 @@ describe('update()', () => { }, }, ], - "alertTypeId": "123", + "alertTypeId": "myType", "apiKey": null, "apiKeyOwner": null, + "consumer": "myApp", "enabled": false, "name": "abc", "params": Object { @@ -2385,7 +3198,7 @@ describe('update()', () => { "updatedBy": "elastic", } `); - expect(savedObjectsClient.update.mock.calls[0][3]).toMatchInlineSnapshot(` + expect(unsecuredSavedObjectsClient.update.mock.calls[0][3]).toMatchInlineSnapshot(` Object { "references": Array [ Object { @@ -2411,7 +3224,7 @@ describe('update()', () => { }), }, async executor() {}, - producer: 'alerting', + producer: 'alerts', }); await expect( alertsClient.update({ @@ -2442,19 +3255,20 @@ describe('update()', () => { it('swallows error when invalidate API key throws', async () => { alertsClientParams.invalidateAPIKey.mockRejectedValueOnce(new Error('Fail')); - savedObjectsClient.bulkGet.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { id: '1', type: 'action', attributes: { + actions: [], actionTypeId: 'test', }, references: [], }, ], }); - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -2511,12 +3325,13 @@ describe('update()', () => { it('swallows error when getDecryptedAsInternalUser throws', async () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail')); - savedObjectsClient.bulkGet.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { id: '1', type: 'action', attributes: { + actions: [], actionTypeId: 'test', }, references: [], @@ -2525,13 +3340,14 @@ describe('update()', () => { id: '2', type: 'action', attributes: { + actions: [], actionTypeId: 'test2', }, references: [], }, ], }); - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { @@ -2623,7 +3439,7 @@ describe('update()', () => { ], }, }); - expect(savedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); expect(alertsClientParams.logger.error).toHaveBeenCalledWith( 'update(): Failed to load API key to invalidate on alert 1: Fail' ); @@ -2643,14 +3459,15 @@ describe('update()', () => { actionGroups: [{ id: 'default', name: 'Default' }], defaultActionGroupId: 'default', async executor() {}, - producer: 'alerting', + producer: 'alerts', }); - savedObjectsClient.bulkGet.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { id: '1', type: 'action', attributes: { + actions: [], actionTypeId: 'test', }, references: [], @@ -2661,6 +3478,7 @@ describe('update()', () => { id: alertId, type: 'alert', attributes: { + actions: [], enabled: true, alertTypeId: '123', schedule: currentSchedule, @@ -2683,7 +3501,7 @@ describe('update()', () => { params: {}, ownerId: null, }); - savedObjectsClient.update.mockResolvedValueOnce({ + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ id: alertId, type: 'alert', attributes: { @@ -2852,6 +3670,73 @@ describe('update()', () => { ); }); }); + + describe('authorization', () => { + beforeEach(() => { + unsecuredSavedObjectsClient.update.mockResolvedValueOnce({ + id: '1', + type: 'alert', + attributes: { + alertTypeId: 'myType', + consumer: 'myApp', + enabled: true, + schedule: { interval: '10s' }, + params: { + bar: true, + }, + actions: [], + scheduledTaskId: 'task-123', + createdAt: new Date().toISOString(), + }, + updated_at: new Date().toISOString(), + references: [], + }); + }); + + test('ensures user is authorised to update this type of alert under the consumer', async () => { + await alertsClient.update({ + id: '1', + data: { + schedule: { interval: '10s' }, + name: 'abc', + tags: ['foo'], + params: { + bar: true, + }, + throttle: null, + actions: [], + }, + }); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'update'); + }); + + test('throws when user is not authorised to update this type of alert', async () => { + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to update a "myType" alert for "myApp"`) + ); + + await expect( + alertsClient.update({ + id: '1', + data: { + schedule: { interval: '10s' }, + name: 'abc', + tags: ['foo'], + params: { + bar: true, + }, + throttle: null, + actions: [], + }, + }) + ).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to update a "myType" alert for "myApp"]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith('myType', 'myApp', 'update'); + }); + }); }); describe('updateApiKey()', () => { @@ -2861,8 +3746,20 @@ describe('updateApiKey()', () => { type: 'alert', attributes: { schedule: { interval: '10s' }, - alertTypeId: '2', + alertTypeId: 'myType', + consumer: 'myApp', enabled: true, + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], }, version: '123', references: [], @@ -2877,30 +3774,42 @@ describe('updateApiKey()', () => { beforeEach(() => { alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValue(existingAlert); + unsecuredSavedObjectsClient.get.mockResolvedValue(existingAlert); encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingEncryptedAlert); alertsClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, - result: { id: '234', api_key: 'abc' }, + result: { id: '234', name: '123', api_key: 'abc' }, }); }); test('updates the API key for the alert', async () => { await alertsClient.updateApiKey({ id: '1' }); - expect(savedObjectsClient.get).not.toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', }); - expect(savedObjectsClient.update).toHaveBeenCalledWith( + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', { schedule: { interval: '10s' }, - alertTypeId: '2', + alertTypeId: 'myType', + consumer: 'myApp', enabled: true, apiKey: Buffer.from('234:abc').toString('base64'), apiKeyOwner: 'elastic', updatedBy: 'elastic', + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], }, { version: '123' } ); @@ -2911,20 +3820,32 @@ describe('updateApiKey()', () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail')); await alertsClient.updateApiKey({ id: '1' }); - expect(savedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); + expect(unsecuredSavedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { namespace: 'default', }); - expect(savedObjectsClient.update).toHaveBeenCalledWith( + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', { schedule: { interval: '10s' }, - alertTypeId: '2', + alertTypeId: 'myType', + consumer: 'myApp', enabled: true, apiKey: Buffer.from('234:abc').toString('base64'), apiKeyOwner: 'elastic', updatedBy: 'elastic', + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], }, { version: '123' } ); @@ -2938,7 +3859,7 @@ describe('updateApiKey()', () => { expect(alertsClientParams.logger.error).toHaveBeenCalledWith( 'Failed to invalidate API Key: Fail' ); - expect(savedObjectsClient.update).toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled(); }); test('swallows error when getting decrypted object throws', async () => { @@ -2948,16 +3869,133 @@ describe('updateApiKey()', () => { expect(alertsClientParams.logger.error).toHaveBeenCalledWith( 'updateApiKey(): Failed to load API key to invalidate on alert 1: Fail' ); - expect(savedObjectsClient.update).toHaveBeenCalled(); + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalled(); expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled(); }); - test('throws when savedObjectsClient update fails', async () => { - savedObjectsClient.update.mockRejectedValueOnce(new Error('Fail')); + test('throws when unsecuredSavedObjectsClient update fails', async () => { + unsecuredSavedObjectsClient.update.mockRejectedValueOnce(new Error('Fail')); await expect(alertsClient.updateApiKey({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( `"Fail"` ); expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled(); }); + + describe('authorization', () => { + test('ensures user is authorised to updateApiKey this type of alert under the consumer', async () => { + await alertsClient.updateApiKey({ id: '1' }); + + expect(actionsAuthorization.ensureAuthorized).toHaveBeenCalledWith('execute'); + expect(authorization.ensureAuthorized).toHaveBeenCalledWith( + 'myType', + 'myApp', + 'updateApiKey' + ); + }); + + test('throws when user is not authorised to updateApiKey this type of alert', async () => { + authorization.ensureAuthorized.mockRejectedValue( + new Error(`Unauthorized to updateApiKey a "myType" alert for "myApp"`) + ); + + await expect(alertsClient.updateApiKey({ id: '1' })).rejects.toMatchInlineSnapshot( + `[Error: Unauthorized to updateApiKey a "myType" alert for "myApp"]` + ); + + expect(authorization.ensureAuthorized).toHaveBeenCalledWith( + 'myType', + 'myApp', + 'updateApiKey' + ); + }); + }); +}); + +describe('listAlertTypes', () => { + let alertsClient: AlertsClient; + const alertingAlertType = { + actionGroups: [], + actionVariables: undefined, + defaultActionGroupId: 'default', + id: 'alertingAlertType', + name: 'alertingAlertType', + producer: 'alerts', + }; + const myAppAlertType = { + actionGroups: [], + actionVariables: undefined, + defaultActionGroupId: 'default', + id: 'myAppAlertType', + name: 'myAppAlertType', + producer: 'myApp', + }; + const setOfAlertTypes = new Set([myAppAlertType, alertingAlertType]); + + const authorizedConsumers = { + alerts: { read: true, all: true }, + myApp: { read: true, all: true }, + myOtherApp: { read: true, all: true }, + }; + + beforeEach(() => { + alertsClient = new AlertsClient(alertsClientParams); + }); + + test('should return a list of AlertTypes that exist in the registry', async () => { + alertTypeRegistry.list.mockReturnValue(setOfAlertTypes); + authorization.filterByAlertTypeAuthorization.mockResolvedValue( + new Set([ + { ...myAppAlertType, authorizedConsumers }, + { ...alertingAlertType, authorizedConsumers }, + ]) + ); + expect(await alertsClient.listAlertTypes()).toEqual( + new Set([ + { ...myAppAlertType, authorizedConsumers }, + { ...alertingAlertType, authorizedConsumers }, + ]) + ); + }); + + describe('authorization', () => { + const listedTypes = new Set([ + { + actionGroups: [], + actionVariables: undefined, + defaultActionGroupId: 'default', + id: 'myType', + name: 'myType', + producer: 'myApp', + }, + { + id: 'myOtherType', + name: 'Test', + actionGroups: [{ id: 'default', name: 'Default' }], + defaultActionGroupId: 'default', + producer: 'alerts', + }, + ]); + beforeEach(() => { + alertTypeRegistry.list.mockReturnValue(listedTypes); + }); + + test('should return a list of AlertTypes that exist in the registry only if the user is authorised to get them', async () => { + const authorizedTypes = new Set([ + { + id: 'myType', + name: 'Test', + actionGroups: [{ id: 'default', name: 'Default' }], + defaultActionGroupId: 'default', + producer: 'alerts', + authorizedConsumers: { + myApp: { read: true, all: true }, + }, + }, + ]); + authorization.filterByAlertTypeAuthorization.mockResolvedValue(authorizedTypes); + + expect(await alertsClient.listAlertTypes()).toEqual(authorizedTypes); + }); + }); }); diff --git a/x-pack/plugins/alerts/server/alerts_client.ts b/x-pack/plugins/alerts/server/alerts_client.ts index e49745b186bb3..eec60f924bf38 100644 --- a/x-pack/plugins/alerts/server/alerts_client.ts +++ b/x-pack/plugins/alerts/server/alerts_client.ts @@ -5,7 +5,7 @@ */ import Boom from 'boom'; -import { omit, isEqual, map, truncate } from 'lodash'; +import { omit, isEqual, map, uniq, pick, truncate } from 'lodash'; import { i18n } from '@kbn/i18n'; import { Logger, @@ -13,7 +13,7 @@ import { SavedObjectReference, SavedObject, } from 'src/core/server'; -import { ActionsClient } from '../../actions/server'; +import { ActionsClient, ActionsAuthorization } from '../../actions/server'; import { Alert, PartialAlert, @@ -35,7 +35,16 @@ import { EncryptedSavedObjectsClient } from '../../encrypted_saved_objects/serve import { TaskManagerStartContract } from '../../task_manager/server'; import { taskInstanceToAlertTaskInstance } from './task_runner/alert_task_instance'; import { deleteTaskIfItExists } from './lib/delete_task_if_it_exists'; +import { RegistryAlertType } from './alert_type_registry'; +import { + AlertsAuthorization, + WriteOperations, + ReadOperations, +} from './authorization/alerts_authorization'; +export interface RegistryAlertTypeWithAuth extends RegistryAlertType { + authorizedConsumers: string[]; +} type NormalizedAlertAction = Omit; export type CreateAPIKeyResult = | { apiKeysEnabled: false } @@ -44,10 +53,12 @@ export type InvalidateAPIKeyResult = | { apiKeysEnabled: false } | { apiKeysEnabled: true; result: SecurityPluginInvalidateAPIKeyResult }; -interface ConstructorOptions { +export interface ConstructorOptions { logger: Logger; taskManager: TaskManagerStartContract; - savedObjectsClient: SavedObjectsClientContract; + unsecuredSavedObjectsClient: SavedObjectsClientContract; + authorization: AlertsAuthorization; + actionsAuthorization: ActionsAuthorization; alertTypeRegistry: AlertTypeRegistry; encryptedSavedObjectsClient: EncryptedSavedObjectsClient; spaceId?: string; @@ -127,18 +138,21 @@ export class AlertsClient { private readonly spaceId?: string; private readonly namespace?: string; private readonly taskManager: TaskManagerStartContract; - private readonly savedObjectsClient: SavedObjectsClientContract; + private readonly unsecuredSavedObjectsClient: SavedObjectsClientContract; + private readonly authorization: AlertsAuthorization; private readonly alertTypeRegistry: AlertTypeRegistry; private readonly createAPIKey: (name: string) => Promise; private readonly invalidateAPIKey: ( params: InvalidateAPIKeyParams ) => Promise; private readonly getActionsClient: () => Promise; + private readonly actionsAuthorization: ActionsAuthorization; encryptedSavedObjectsClient: EncryptedSavedObjectsClient; constructor({ alertTypeRegistry, - savedObjectsClient, + unsecuredSavedObjectsClient, + authorization, taskManager, logger, spaceId, @@ -148,6 +162,7 @@ export class AlertsClient { invalidateAPIKey, encryptedSavedObjectsClient, getActionsClient, + actionsAuthorization, }: ConstructorOptions) { this.logger = logger; this.getUserName = getUserName; @@ -155,16 +170,25 @@ export class AlertsClient { this.namespace = namespace; this.taskManager = taskManager; this.alertTypeRegistry = alertTypeRegistry; - this.savedObjectsClient = savedObjectsClient; + this.unsecuredSavedObjectsClient = unsecuredSavedObjectsClient; + this.authorization = authorization; this.createAPIKey = createAPIKey; this.invalidateAPIKey = invalidateAPIKey; this.encryptedSavedObjectsClient = encryptedSavedObjectsClient; this.getActionsClient = getActionsClient; + this.actionsAuthorization = actionsAuthorization; } public async create({ data, options }: CreateOptions): Promise { + await this.authorization.ensureAuthorized( + data.alertTypeId, + data.consumer, + WriteOperations.Create + ); + // Throws an error if alert type isn't registered const alertType = this.alertTypeRegistry.get(data.alertTypeId); + const validatedAlertTypeParams = validateAlertTypeParams(alertType, data.params); const username = await this.getUserName(); @@ -186,7 +210,7 @@ export class AlertsClient { muteAll: false, mutedInstanceIds: [], }; - const createdAlert = await this.savedObjectsClient.create('alert', rawAlert, { + const createdAlert = await this.unsecuredSavedObjectsClient.create('alert', rawAlert, { ...options, references, }); @@ -197,7 +221,7 @@ export class AlertsClient { } catch (e) { // Cleanup data, something went wrong scheduling the task try { - await this.savedObjectsClient.delete('alert', createdAlert.id); + await this.unsecuredSavedObjectsClient.delete('alert', createdAlert.id); } catch (err) { // Skip the cleanup error and throw the task manager error to avoid confusion this.logger.error( @@ -206,7 +230,7 @@ export class AlertsClient { } throw e; } - await this.savedObjectsClient.update('alert', createdAlert.id, { + await this.unsecuredSavedObjectsClient.update('alert', createdAlert.id, { scheduledTaskId: scheduledTask.id, }); createdAlert.attributes.scheduledTaskId = scheduledTask.id; @@ -220,12 +244,22 @@ export class AlertsClient { } public async get({ id }: { id: string }): Promise { - const result = await this.savedObjectsClient.get('alert', id); + const result = await this.unsecuredSavedObjectsClient.get('alert', id); + await this.authorization.ensureAuthorized( + result.attributes.alertTypeId, + result.attributes.consumer, + ReadOperations.Get + ); return this.getAlertFromRaw(result.id, result.attributes, result.updated_at, result.references); } public async getAlertState({ id }: { id: string }): Promise { const alert = await this.get({ id }); + await this.authorization.ensureAuthorized( + alert.alertTypeId, + alert.consumer, + ReadOperations.GetAlertState + ); if (alert.scheduledTaskId) { const { state } = taskInstanceToAlertTaskInstance( await this.taskManager.get(alert.scheduledTaskId), @@ -235,30 +269,56 @@ export class AlertsClient { } } - public async find({ options = {} }: { options: FindOptions }): Promise { + public async find({ + options: { fields, ...options } = {}, + }: { options?: FindOptions } = {}): Promise { + const { + filter: authorizationFilter, + ensureAlertTypeIsAuthorized, + logSuccessfulAuthorization, + } = await this.authorization.getFindAuthorizationFilter(); + + if (authorizationFilter) { + options.filter = options.filter + ? `${options.filter} and ${authorizationFilter}` + : authorizationFilter; + } + const { page, per_page: perPage, total, saved_objects: data, - } = await this.savedObjectsClient.find({ + } = await this.unsecuredSavedObjectsClient.find({ ...options, + fields: fields ? this.includeFieldsRequiredForAuthentication(fields) : fields, type: 'alert', }); + const authorizedData = data.map(({ id, attributes, updated_at, references }) => { + ensureAlertTypeIsAuthorized(attributes.alertTypeId, attributes.consumer); + return this.getAlertFromRaw( + id, + fields ? (pick(attributes, fields) as RawAlert) : attributes, + updated_at, + references + ); + }); + + logSuccessfulAuthorization(); + return { page, perPage, total, - data: data.map(({ id, attributes, updated_at, references }) => - this.getAlertFromRaw(id, attributes, updated_at, references) - ), + data: authorizedData, }; } public async delete({ id }: { id: string }) { let taskIdToRemove: string | undefined; let apiKeyToInvalidate: string | null = null; + let attributes: RawAlert; try { const decryptedAlert = await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser< @@ -266,17 +326,25 @@ export class AlertsClient { >('alert', id, { namespace: this.namespace }); apiKeyToInvalidate = decryptedAlert.attributes.apiKey; taskIdToRemove = decryptedAlert.attributes.scheduledTaskId; + attributes = decryptedAlert.attributes; } catch (e) { // We'll skip invalidating the API key since we failed to load the decrypted saved object this.logger.error( `delete(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the scheduledTaskId using SOC - const alert = await this.savedObjectsClient.get('alert', id); + const alert = await this.unsecuredSavedObjectsClient.get('alert', id); taskIdToRemove = alert.attributes.scheduledTaskId; + attributes = alert.attributes; } - const removeResult = await this.savedObjectsClient.delete('alert', id); + await this.authorization.ensureAuthorized( + attributes.alertTypeId, + attributes.consumer, + WriteOperations.Delete + ); + + const removeResult = await this.unsecuredSavedObjectsClient.delete('alert', id); await Promise.all([ taskIdToRemove ? deleteTaskIfItExists(this.taskManager, taskIdToRemove) : null, @@ -299,8 +367,13 @@ export class AlertsClient { `update(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the object using SOC - alertSavedObject = await this.savedObjectsClient.get('alert', id); + alertSavedObject = await this.unsecuredSavedObjectsClient.get('alert', id); } + await this.authorization.ensureAuthorized( + alertSavedObject.attributes.alertTypeId, + alertSavedObject.attributes.consumer, + WriteOperations.Update + ); const updateResult = await this.updateAlert({ id, data }, alertSavedObject); @@ -342,7 +415,7 @@ export class AlertsClient { : null; const apiKeyAttributes = this.apiKeyAsAlertAttributes(createdAPIKey, username); - const updatedObject = await this.savedObjectsClient.update( + const updatedObject = await this.unsecuredSavedObjectsClient.update( 'alert', id, { @@ -400,13 +473,22 @@ export class AlertsClient { `updateApiKey(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the attributes and version using SOC - const alert = await this.savedObjectsClient.get('alert', id); + const alert = await this.unsecuredSavedObjectsClient.get('alert', id); attributes = alert.attributes; version = alert.version; } + await this.authorization.ensureAuthorized( + attributes.alertTypeId, + attributes.consumer, + WriteOperations.UpdateApiKey + ); + + if (attributes.actions.length) { + await this.actionsAuthorization.ensureAuthorized('execute'); + } const username = await this.getUserName(); - await this.savedObjectsClient.update( + await this.unsecuredSavedObjectsClient.update( 'alert', id, { @@ -459,14 +541,24 @@ export class AlertsClient { `enable(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the attributes and version using SOC - const alert = await this.savedObjectsClient.get('alert', id); + const alert = await this.unsecuredSavedObjectsClient.get('alert', id); attributes = alert.attributes; version = alert.version; } + await this.authorization.ensureAuthorized( + attributes.alertTypeId, + attributes.consumer, + WriteOperations.Enable + ); + + if (attributes.actions.length) { + await this.actionsAuthorization.ensureAuthorized('execute'); + } + if (attributes.enabled === false) { const username = await this.getUserName(); - await this.savedObjectsClient.update( + await this.unsecuredSavedObjectsClient.update( 'alert', id, { @@ -483,7 +575,9 @@ export class AlertsClient { { version } ); const scheduledTask = await this.scheduleAlert(id, attributes.alertTypeId); - await this.savedObjectsClient.update('alert', id, { scheduledTaskId: scheduledTask.id }); + await this.unsecuredSavedObjectsClient.update('alert', id, { + scheduledTaskId: scheduledTask.id, + }); if (apiKeyToInvalidate) { await this.invalidateApiKey({ apiKey: apiKeyToInvalidate }); } @@ -508,13 +602,19 @@ export class AlertsClient { `disable(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the attributes and version using SOC - const alert = await this.savedObjectsClient.get('alert', id); + const alert = await this.unsecuredSavedObjectsClient.get('alert', id); attributes = alert.attributes; version = alert.version; } + await this.authorization.ensureAuthorized( + attributes.alertTypeId, + attributes.consumer, + WriteOperations.Disable + ); + if (attributes.enabled === true) { - await this.savedObjectsClient.update( + await this.unsecuredSavedObjectsClient.update( 'alert', id, { @@ -538,7 +638,18 @@ export class AlertsClient { } public async muteAll({ id }: { id: string }) { - await this.savedObjectsClient.update('alert', id, { + const { attributes } = await this.unsecuredSavedObjectsClient.get('alert', id); + await this.authorization.ensureAuthorized( + attributes.alertTypeId, + attributes.consumer, + WriteOperations.MuteAll + ); + + if (attributes.actions.length) { + await this.actionsAuthorization.ensureAuthorized('execute'); + } + + await this.unsecuredSavedObjectsClient.update('alert', id, { muteAll: true, mutedInstanceIds: [], updatedBy: await this.getUserName(), @@ -546,7 +657,18 @@ export class AlertsClient { } public async unmuteAll({ id }: { id: string }) { - await this.savedObjectsClient.update('alert', id, { + const { attributes } = await this.unsecuredSavedObjectsClient.get('alert', id); + await this.authorization.ensureAuthorized( + attributes.alertTypeId, + attributes.consumer, + WriteOperations.UnmuteAll + ); + + if (attributes.actions.length) { + await this.actionsAuthorization.ensureAuthorized('execute'); + } + + await this.unsecuredSavedObjectsClient.update('alert', id, { muteAll: false, mutedInstanceIds: [], updatedBy: await this.getUserName(), @@ -554,11 +676,25 @@ export class AlertsClient { } public async muteInstance({ alertId, alertInstanceId }: MuteOptions) { - const { attributes, version } = await this.savedObjectsClient.get('alert', alertId); + const { attributes, version } = await this.unsecuredSavedObjectsClient.get( + 'alert', + alertId + ); + + await this.authorization.ensureAuthorized( + attributes.alertTypeId, + attributes.consumer, + WriteOperations.MuteInstance + ); + + if (attributes.actions.length) { + await this.actionsAuthorization.ensureAuthorized('execute'); + } + const mutedInstanceIds = attributes.mutedInstanceIds || []; if (!attributes.muteAll && !mutedInstanceIds.includes(alertInstanceId)) { mutedInstanceIds.push(alertInstanceId); - await this.savedObjectsClient.update( + await this.unsecuredSavedObjectsClient.update( 'alert', alertId, { @@ -577,10 +713,22 @@ export class AlertsClient { alertId: string; alertInstanceId: string; }) { - const { attributes, version } = await this.savedObjectsClient.get('alert', alertId); + const { attributes, version } = await this.unsecuredSavedObjectsClient.get( + 'alert', + alertId + ); + await this.authorization.ensureAuthorized( + attributes.alertTypeId, + attributes.consumer, + WriteOperations.UnmuteInstance + ); + if (attributes.actions.length) { + await this.actionsAuthorization.ensureAuthorized('execute'); + } + const mutedInstanceIds = attributes.mutedInstanceIds || []; if (!attributes.muteAll && mutedInstanceIds.includes(alertInstanceId)) { - await this.savedObjectsClient.update( + await this.unsecuredSavedObjectsClient.update( 'alert', alertId, { @@ -593,6 +741,13 @@ export class AlertsClient { } } + public async listAlertTypes() { + return await this.authorization.filterByAlertTypeAuthorization(this.alertTypeRegistry.list(), [ + ReadOperations.Get, + WriteOperations.Create, + ]); + } + private async scheduleAlert(id: string, alertTypeId: string) { return await this.taskManager.schedule({ taskType: `alerting:${alertTypeId}`, @@ -610,13 +765,14 @@ export class AlertsClient { } private injectReferencesIntoActions( + alertId: string, actions: RawAlert['actions'], references: SavedObjectReference[] ) { return actions.map((action) => { const reference = references.find((ref) => ref.name === action.actionRef); if (!reference) { - throw new Error(`Reference ${action.actionRef} not found`); + throw new Error(`Action reference "${action.actionRef}" not found in alert id: ${alertId}`); } return { ...omit(action, 'actionRef'), @@ -639,8 +795,8 @@ export class AlertsClient { private getPartialAlertFromRaw( id: string, - rawAlert: Partial, - updatedAt: SavedObject['updated_at'], + { createdAt, ...rawAlert }: Partial, + updatedAt: SavedObject['updated_at'] = createdAt, references: SavedObjectReference[] | undefined ): PartialAlert { return { @@ -649,11 +805,11 @@ export class AlertsClient { // we currently only support the Interval Schedule type // Once we support additional types, this type signature will likely change schedule: rawAlert.schedule as IntervalSchedule, - updatedAt: updatedAt ? new Date(updatedAt) : new Date(rawAlert.createdAt!), - createdAt: new Date(rawAlert.createdAt!), actions: rawAlert.actions - ? this.injectReferencesIntoActions(rawAlert.actions, references || []) + ? this.injectReferencesIntoActions(id, rawAlert.actions, references || []) : [], + ...(updatedAt ? { updatedAt: new Date(updatedAt) } : {}), + ...(createdAt ? { createdAt: new Date(createdAt) } : {}), }; } @@ -679,38 +835,45 @@ export class AlertsClient { private async denormalizeActions( alertActions: NormalizedAlertAction[] ): Promise<{ actions: RawAlert['actions']; references: SavedObjectReference[] }> { - const actionsClient = await this.getActionsClient(); - const actionIds = [...new Set(alertActions.map((alertAction) => alertAction.id))]; - const actionResults = await actionsClient.getBulk(actionIds); const references: SavedObjectReference[] = []; - const actions = alertActions.map(({ id, ...alertAction }, i) => { - const actionResultValue = actionResults.find((action) => action.id === id); - if (actionResultValue) { - const actionRef = `action_${i}`; - references.push({ - id, - name: actionRef, - type: 'action', - }); - return { - ...alertAction, - actionRef, - actionTypeId: actionResultValue.actionTypeId, - }; - } else { - return { - ...alertAction, - actionRef: '', - actionTypeId: '', - }; - } - }); + const actions: RawAlert['actions'] = []; + if (alertActions.length) { + const actionsClient = await this.getActionsClient(); + const actionIds = [...new Set(alertActions.map((alertAction) => alertAction.id))]; + const actionResults = await actionsClient.getBulk(actionIds); + alertActions.forEach(({ id, ...alertAction }, i) => { + const actionResultValue = actionResults.find((action) => action.id === id); + if (actionResultValue) { + const actionRef = `action_${i}`; + references.push({ + id, + name: actionRef, + type: 'action', + }); + actions.push({ + ...alertAction, + actionRef, + actionTypeId: actionResultValue.actionTypeId, + }); + } else { + actions.push({ + ...alertAction, + actionRef: '', + actionTypeId: '', + }); + } + }); + } return { actions, references, }; } + private includeFieldsRequiredForAuthentication(fields: string[]): string[] { + return uniq([...fields, 'alertTypeId', 'consumer']); + } + private generateAPIKeyName(alertTypeId: string, alertName: string) { return truncate(`Alerting: ${alertTypeId}/${alertName}`, { length: 256 }); } 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 128d54c10b66a..16b5af499bb90 100644 --- a/x-pack/plugins/alerts/server/alerts_client_factory.test.ts +++ b/x-pack/plugins/alerts/server/alerts_client_factory.test.ts @@ -9,24 +9,39 @@ import { AlertsClientFactory, AlertsClientFactoryOpts } from './alerts_client_fa import { alertTypeRegistryMock } from './alert_type_registry.mock'; import { taskManagerMock } from '../../task_manager/server/task_manager.mock'; import { KibanaRequest } from '../../../../src/core/server'; -import { loggingSystemMock, savedObjectsClientMock } from '../../../../src/core/server/mocks'; +import { + savedObjectsClientMock, + savedObjectsServiceMock, + loggingSystemMock, +} from '../../../../src/core/server/mocks'; import { encryptedSavedObjectsMock } from '../../encrypted_saved_objects/server/mocks'; import { AuthenticatedUser } from '../../../plugins/security/common/model'; import { securityMock } from '../../security/server/mocks'; -import { actionsMock } from '../../actions/server/mocks'; +import { PluginStartContract as ActionsStartContract } from '../../actions/server'; +import { actionsMock, actionsAuthorizationMock } from '../../actions/server/mocks'; +import { featuresPluginMock } from '../../features/server/mocks'; +import { AuditLogger } from '../../security/server'; +import { ALERTS_FEATURE_ID } from '../common'; jest.mock('./alerts_client'); +jest.mock('./authorization/alerts_authorization'); +jest.mock('./authorization/audit_logger'); const savedObjectsClient = savedObjectsClientMock.create(); +const savedObjectsService = savedObjectsServiceMock.createInternalStartContract(); +const features = featuresPluginMock.createStart(); + const securityPluginSetup = securityMock.createSetup(); const alertsClientFactoryParams: jest.Mocked = { logger: loggingSystemMock.create().get(), taskManager: taskManagerMock.start(), alertTypeRegistry: alertTypeRegistryMock.create(), getSpaceId: jest.fn(), + getSpace: jest.fn(), spaceIdToNamespace: jest.fn(), encryptedSavedObjectsClient: encryptedSavedObjectsMock.createClient(), actions: actionsMock.createStart(), + features, }; const fakeRequest = ({ headers: {}, @@ -44,19 +59,101 @@ const fakeRequest = ({ getSavedObjectsClient: () => savedObjectsClient, } as unknown) as Request; +const actionsAuthorization = actionsAuthorizationMock.create(); + beforeEach(() => { jest.resetAllMocks(); + alertsClientFactoryParams.actions = actionsMock.createStart(); + (alertsClientFactoryParams.actions as jest.Mocked< + ActionsStartContract + >).getActionsAuthorizationWithRequest.mockReturnValue(actionsAuthorization); alertsClientFactoryParams.getSpaceId.mockReturnValue('default'); alertsClientFactoryParams.spaceIdToNamespace.mockReturnValue('default'); }); +test('creates an alerts client with proper constructor arguments when security is enabled', async () => { + const factory = new AlertsClientFactory(); + factory.initialize({ securityPluginSetup, ...alertsClientFactoryParams }); + const request = KibanaRequest.from(fakeRequest); + + const { AlertsAuthorizationAuditLogger } = jest.requireMock('./authorization/audit_logger'); + savedObjectsService.getScopedClient.mockReturnValue(savedObjectsClient); + + const logger = { + log: jest.fn(), + } as jest.Mocked; + securityPluginSetup.audit.getLogger.mockReturnValue(logger); + + factory.create(request, savedObjectsService); + + expect(savedObjectsService.getScopedClient).toHaveBeenCalledWith(request, { + excludedWrappers: ['security'], + includedHiddenTypes: ['alert'], + }); + + const { AlertsAuthorization } = jest.requireMock('./authorization/alerts_authorization'); + expect(AlertsAuthorization).toHaveBeenCalledWith({ + request, + authorization: securityPluginSetup.authz, + alertTypeRegistry: alertsClientFactoryParams.alertTypeRegistry, + features: alertsClientFactoryParams.features, + auditLogger: expect.any(AlertsAuthorizationAuditLogger), + getSpace: expect.any(Function), + }); + + expect(AlertsAuthorizationAuditLogger).toHaveBeenCalledWith(logger); + expect(securityPluginSetup.audit.getLogger).toHaveBeenCalledWith(ALERTS_FEATURE_ID); + + expect(alertsClientFactoryParams.actions.getActionsAuthorizationWithRequest).toHaveBeenCalledWith( + request + ); + + expect(jest.requireMock('./alerts_client').AlertsClient).toHaveBeenCalledWith({ + unsecuredSavedObjectsClient: savedObjectsClient, + authorization: expect.any(AlertsAuthorization), + actionsAuthorization, + logger: alertsClientFactoryParams.logger, + taskManager: alertsClientFactoryParams.taskManager, + alertTypeRegistry: alertsClientFactoryParams.alertTypeRegistry, + spaceId: 'default', + namespace: 'default', + getUserName: expect.any(Function), + getActionsClient: expect.any(Function), + createAPIKey: expect.any(Function), + invalidateAPIKey: expect.any(Function), + encryptedSavedObjectsClient: alertsClientFactoryParams.encryptedSavedObjectsClient, + }); +}); + test('creates an alerts client with proper constructor arguments', async () => { const factory = new AlertsClientFactory(); factory.initialize(alertsClientFactoryParams); - factory.create(KibanaRequest.from(fakeRequest), savedObjectsClient); + const request = KibanaRequest.from(fakeRequest); + + savedObjectsService.getScopedClient.mockReturnValue(savedObjectsClient); + + factory.create(request, savedObjectsService); + + expect(savedObjectsService.getScopedClient).toHaveBeenCalledWith(request, { + excludedWrappers: ['security'], + includedHiddenTypes: ['alert'], + }); + + const { AlertsAuthorization } = jest.requireMock('./authorization/alerts_authorization'); + const { AlertsAuthorizationAuditLogger } = jest.requireMock('./authorization/audit_logger'); + expect(AlertsAuthorization).toHaveBeenCalledWith({ + request, + authorization: undefined, + alertTypeRegistry: alertsClientFactoryParams.alertTypeRegistry, + features: alertsClientFactoryParams.features, + auditLogger: expect.any(AlertsAuthorizationAuditLogger), + getSpace: expect.any(Function), + }); expect(jest.requireMock('./alerts_client').AlertsClient).toHaveBeenCalledWith({ - savedObjectsClient, + unsecuredSavedObjectsClient: savedObjectsClient, + authorization: expect.any(AlertsAuthorization), + actionsAuthorization, logger: alertsClientFactoryParams.logger, taskManager: alertsClientFactoryParams.taskManager, alertTypeRegistry: alertsClientFactoryParams.alertTypeRegistry, @@ -73,7 +170,7 @@ test('creates an alerts client with proper constructor arguments', async () => { test('getUserName() returns null when security is disabled', async () => { const factory = new AlertsClientFactory(); factory.initialize(alertsClientFactoryParams); - factory.create(KibanaRequest.from(fakeRequest), savedObjectsClient); + factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; const userNameResult = await constructorCall.getUserName(); @@ -86,7 +183,7 @@ test('getUserName() returns a name when security is enabled', async () => { ...alertsClientFactoryParams, securityPluginSetup, }); - factory.create(KibanaRequest.from(fakeRequest), savedObjectsClient); + factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; securityPluginSetup.authc.getCurrentUser.mockReturnValueOnce(({ @@ -99,7 +196,7 @@ test('getUserName() returns a name when security is enabled', async () => { test('getActionsClient() returns ActionsClient', async () => { const factory = new AlertsClientFactory(); factory.initialize(alertsClientFactoryParams); - factory.create(KibanaRequest.from(fakeRequest), savedObjectsClient); + factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; const actionsClient = await constructorCall.getActionsClient(); @@ -109,7 +206,7 @@ test('getActionsClient() returns ActionsClient', async () => { test('createAPIKey() returns { apiKeysEnabled: false } when security is disabled', async () => { const factory = new AlertsClientFactory(); factory.initialize(alertsClientFactoryParams); - factory.create(KibanaRequest.from(fakeRequest), savedObjectsClient); + factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; const createAPIKeyResult = await constructorCall.createAPIKey(); @@ -119,7 +216,7 @@ test('createAPIKey() returns { apiKeysEnabled: false } when security is disabled test('createAPIKey() returns { apiKeysEnabled: false } when security is enabled but ES security is disabled', async () => { const factory = new AlertsClientFactory(); factory.initialize(alertsClientFactoryParams); - factory.create(KibanaRequest.from(fakeRequest), savedObjectsClient); + factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; securityPluginSetup.authc.grantAPIKeyAsInternalUser.mockResolvedValueOnce(null); @@ -133,7 +230,7 @@ test('createAPIKey() returns an API key when security is enabled', async () => { ...alertsClientFactoryParams, securityPluginSetup, }); - factory.create(KibanaRequest.from(fakeRequest), savedObjectsClient); + factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; securityPluginSetup.authc.grantAPIKeyAsInternalUser.mockResolvedValueOnce({ @@ -154,7 +251,7 @@ test('createAPIKey() throws when security plugin createAPIKey throws an error', ...alertsClientFactoryParams, securityPluginSetup, }); - factory.create(KibanaRequest.from(fakeRequest), savedObjectsClient); + factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); const constructorCall = jest.requireMock('./alerts_client').AlertsClient.mock.calls[0][0]; securityPluginSetup.authc.grantAPIKeyAsInternalUser.mockRejectedValueOnce( diff --git a/x-pack/plugins/alerts/server/alerts_client_factory.ts b/x-pack/plugins/alerts/server/alerts_client_factory.ts index 30fcd1b949f2b..79b0ccaf1f0bc 100644 --- a/x-pack/plugins/alerts/server/alerts_client_factory.ts +++ b/x-pack/plugins/alerts/server/alerts_client_factory.ts @@ -6,11 +6,16 @@ import { PluginStartContract as ActionsPluginStartContract } from '../../actions/server'; import { AlertsClient } from './alerts_client'; +import { ALERTS_FEATURE_ID } from '../common'; import { AlertTypeRegistry, SpaceIdToNamespaceFunction } from './types'; -import { KibanaRequest, Logger, SavedObjectsClientContract } from '../../../../src/core/server'; +import { KibanaRequest, Logger, SavedObjectsServiceStart } from '../../../../src/core/server'; import { InvalidateAPIKeyParams, SecurityPluginSetup } from '../../security/server'; import { EncryptedSavedObjectsClient } from '../../encrypted_saved_objects/server'; import { TaskManagerStartContract } from '../../task_manager/server'; +import { PluginStartContract as FeaturesPluginStart } from '../../features/server'; +import { AlertsAuthorization } from './authorization/alerts_authorization'; +import { AlertsAuthorizationAuditLogger } from './authorization/audit_logger'; +import { Space } from '../../spaces/server'; export interface AlertsClientFactoryOpts { logger: Logger; @@ -18,9 +23,11 @@ export interface AlertsClientFactoryOpts { alertTypeRegistry: AlertTypeRegistry; securityPluginSetup?: SecurityPluginSetup; getSpaceId: (request: KibanaRequest) => string | undefined; + getSpace: (request: KibanaRequest) => Promise; spaceIdToNamespace: SpaceIdToNamespaceFunction; encryptedSavedObjectsClient: EncryptedSavedObjectsClient; actions: ActionsPluginStartContract; + features: FeaturesPluginStart; } export class AlertsClientFactory { @@ -30,9 +37,11 @@ export class AlertsClientFactory { private alertTypeRegistry!: AlertTypeRegistry; private securityPluginSetup?: SecurityPluginSetup; private getSpaceId!: (request: KibanaRequest) => string | undefined; + private getSpace!: (request: KibanaRequest) => Promise; private spaceIdToNamespace!: SpaceIdToNamespaceFunction; private encryptedSavedObjectsClient!: EncryptedSavedObjectsClient; private actions!: ActionsPluginStartContract; + private features!: FeaturesPluginStart; public initialize(options: AlertsClientFactoryOpts) { if (this.isInitialized) { @@ -41,26 +50,41 @@ export class AlertsClientFactory { this.isInitialized = true; this.logger = options.logger; this.getSpaceId = options.getSpaceId; + this.getSpace = options.getSpace; this.taskManager = options.taskManager; this.alertTypeRegistry = options.alertTypeRegistry; this.securityPluginSetup = options.securityPluginSetup; this.spaceIdToNamespace = options.spaceIdToNamespace; this.encryptedSavedObjectsClient = options.encryptedSavedObjectsClient; this.actions = options.actions; + this.features = options.features; } - public create( - request: KibanaRequest, - savedObjectsClient: SavedObjectsClientContract - ): AlertsClient { - const { securityPluginSetup, actions } = this; + public create(request: KibanaRequest, savedObjects: SavedObjectsServiceStart): AlertsClient { + const { securityPluginSetup, actions, features } = this; const spaceId = this.getSpaceId(request); + const authorization = new AlertsAuthorization({ + authorization: securityPluginSetup?.authz, + request, + getSpace: this.getSpace, + alertTypeRegistry: this.alertTypeRegistry, + features: features!, + auditLogger: new AlertsAuthorizationAuditLogger( + securityPluginSetup?.audit.getLogger(ALERTS_FEATURE_ID) + ), + }); + return new AlertsClient({ spaceId, logger: this.logger, taskManager: this.taskManager, alertTypeRegistry: this.alertTypeRegistry, - savedObjectsClient, + unsecuredSavedObjectsClient: savedObjects.getScopedClient(request, { + excludedWrappers: ['security'], + includedHiddenTypes: ['alert'], + }), + authorization, + actionsAuthorization: actions.getActionsAuthorizationWithRequest(request), namespace: this.spaceIdToNamespace(spaceId), encryptedSavedObjectsClient: this.encryptedSavedObjectsClient, async getUserName() { diff --git a/x-pack/plugins/alerts/server/authorization/alerts_authorization.mock.ts b/x-pack/plugins/alerts/server/authorization/alerts_authorization.mock.ts new file mode 100644 index 0000000000000..d7705f834ad41 --- /dev/null +++ b/x-pack/plugins/alerts/server/authorization/alerts_authorization.mock.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { AlertsAuthorization } from './alerts_authorization'; + +type Schema = PublicMethodsOf; +export type AlertsAuthorizationMock = jest.Mocked; + +const createAlertsAuthorizationMock = () => { + const mocked: AlertsAuthorizationMock = { + ensureAuthorized: jest.fn(), + filterByAlertTypeAuthorization: jest.fn(), + getFindAuthorizationFilter: jest.fn(), + }; + return mocked; +}; + +export const alertsAuthorizationMock: { + create: () => AlertsAuthorizationMock; +} = { + create: createAlertsAuthorizationMock, +}; diff --git a/x-pack/plugins/alerts/server/authorization/alerts_authorization.test.ts b/x-pack/plugins/alerts/server/authorization/alerts_authorization.test.ts new file mode 100644 index 0000000000000..b164d27ded648 --- /dev/null +++ b/x-pack/plugins/alerts/server/authorization/alerts_authorization.test.ts @@ -0,0 +1,1256 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { KibanaRequest } from 'kibana/server'; +import { alertTypeRegistryMock } from '../alert_type_registry.mock'; +import { securityMock } from '../../../../plugins/security/server/mocks'; +import { PluginStartContract as FeaturesStartContract, Feature } from '../../../features/server'; +import { featuresPluginMock } from '../../../features/server/mocks'; +import { + AlertsAuthorization, + ensureFieldIsSafeForQuery, + WriteOperations, + ReadOperations, +} from './alerts_authorization'; +import { alertsAuthorizationAuditLoggerMock } from './audit_logger.mock'; +import { AlertsAuthorizationAuditLogger, AuthorizationResult } from './audit_logger'; +import uuid from 'uuid'; + +const alertTypeRegistry = alertTypeRegistryMock.create(); +const features: jest.Mocked = featuresPluginMock.createStart(); +const request = {} as KibanaRequest; + +const auditLogger = alertsAuthorizationAuditLoggerMock.create(); +const realAuditLogger = new AlertsAuthorizationAuditLogger(); + +const getSpace = jest.fn(); + +const mockAuthorizationAction = (type: string, app: string, operation: string) => + `${type}/${app}/${operation}`; +function mockSecurity() { + const security = securityMock.createSetup(); + const authorization = security.authz; + // typescript is having trouble inferring jest's automocking + (authorization.actions.alerting.get as jest.MockedFunction< + typeof authorization.actions.alerting.get + >).mockImplementation(mockAuthorizationAction); + authorization.mode.useRbacForRequest.mockReturnValue(true); + return { authorization }; +} + +function mockFeature(appName: string, typeName?: string) { + return new Feature({ + id: appName, + name: appName, + app: [], + ...(typeName + ? { + alerting: [typeName], + } + : {}), + privileges: { + all: { + ...(typeName + ? { + alerting: { + all: [typeName], + }, + } + : {}), + savedObject: { + all: [], + read: [], + }, + ui: [], + }, + read: { + ...(typeName + ? { + alerting: { + read: [typeName], + }, + } + : {}), + savedObject: { + all: [], + read: [], + }, + ui: [], + }, + }, + }); +} + +function mockFeatureWithSubFeature(appName: string, typeName: string) { + return new Feature({ + id: appName, + name: appName, + app: [], + ...(typeName + ? { + alerting: [typeName], + } + : {}), + privileges: { + all: { + savedObject: { + all: [], + read: [], + }, + ui: [], + }, + read: { + savedObject: { + all: [], + read: [], + }, + ui: [], + }, + }, + subFeatures: [ + { + name: appName, + privilegeGroups: [ + { + groupType: 'independent', + privileges: [ + { + id: 'doSomethingAlertRelated', + name: 'sub feature alert', + includeIn: 'all', + alerting: { + all: [typeName], + }, + savedObject: { + all: [], + read: [], + }, + ui: ['doSomethingAlertRelated'], + }, + { + id: 'doSomethingAlertRelated', + name: 'sub feature alert', + includeIn: 'read', + alerting: { + read: [typeName], + }, + savedObject: { + all: [], + read: [], + }, + ui: ['doSomethingAlertRelated'], + }, + ], + }, + ], + }, + ], + }); +} + +const myAppFeature = mockFeature('myApp', 'myType'); +const myOtherAppFeature = mockFeature('myOtherApp', 'myType'); +const myAppWithSubFeature = mockFeatureWithSubFeature('myAppWithSubFeature', 'myType'); +const myFeatureWithoutAlerting = mockFeature('myOtherApp'); + +beforeEach(() => { + jest.resetAllMocks(); + auditLogger.alertsAuthorizationFailure.mockImplementation((username, ...args) => + realAuditLogger.getAuthorizationMessage(AuthorizationResult.Unauthorized, ...args) + ); + auditLogger.alertsAuthorizationSuccess.mockImplementation((username, ...args) => + realAuditLogger.getAuthorizationMessage(AuthorizationResult.Authorized, ...args) + ); + auditLogger.alertsUnscopedAuthorizationFailure.mockImplementation( + (username, operation) => `Unauthorized ${username}/${operation}` + ); + alertTypeRegistry.get.mockImplementation((id) => ({ + id, + name: 'My Alert Type', + actionGroups: [{ id: 'default', name: 'Default' }], + defaultActionGroupId: 'default', + async executor() {}, + producer: 'myApp', + })); + features.getFeatures.mockReturnValue([ + myAppFeature, + myOtherAppFeature, + myAppWithSubFeature, + myFeatureWithoutAlerting, + ]); + getSpace.mockResolvedValue(undefined); +}); + +describe('AlertsAuthorization', () => { + describe('constructor', () => { + test(`fetches the user's current space`, async () => { + const space = { + id: uuid.v4(), + name: uuid.v4(), + disabledFeatures: [], + }; + getSpace.mockResolvedValue(space); + + new AlertsAuthorization({ + request, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + + expect(getSpace).toHaveBeenCalledWith(request); + }); + }); + + describe('ensureAuthorized', () => { + test('is a no-op when there is no authorization api', async () => { + const alertAuthorization = new AlertsAuthorization({ + request, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + + await alertAuthorization.ensureAuthorized('myType', 'myApp', WriteOperations.Create); + + expect(alertTypeRegistry.get).toHaveBeenCalledTimes(0); + }); + + test('is a no-op when the security license is disabled', async () => { + const { authorization } = mockSecurity(); + authorization.mode.useRbacForRequest.mockReturnValue(false); + const alertAuthorization = new AlertsAuthorization({ + request, + alertTypeRegistry, + authorization, + features, + auditLogger, + getSpace, + }); + + await alertAuthorization.ensureAuthorized('myType', 'myApp', WriteOperations.Create); + + expect(alertTypeRegistry.get).toHaveBeenCalledTimes(0); + }); + + test('ensures the user has privileges to execute the specified type, operation and consumer', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: true, + privileges: [], + }); + + await alertAuthorization.ensureAuthorized('myType', 'myApp', WriteOperations.Create); + + expect(alertTypeRegistry.get).toHaveBeenCalledWith('myType'); + + expect(authorization.actions.alerting.get).toHaveBeenCalledWith('myType', 'myApp', 'create'); + expect(checkPrivileges).toHaveBeenCalledWith([ + mockAuthorizationAction('myType', 'myApp', 'create'), + ]); + + expect(auditLogger.alertsAuthorizationSuccess).toHaveBeenCalledTimes(1); + expect(auditLogger.alertsAuthorizationFailure).not.toHaveBeenCalled(); + expect(auditLogger.alertsAuthorizationSuccess.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "some-user", + "myType", + 0, + "myApp", + "create", + ] + `); + }); + + test('ensures the user has privileges to execute the specified type and operation without consumer when consumer is alerts', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: true, + privileges: [], + }); + + await alertAuthorization.ensureAuthorized('myType', 'alerts', WriteOperations.Create); + + expect(alertTypeRegistry.get).toHaveBeenCalledWith('myType'); + + expect(authorization.actions.alerting.get).toHaveBeenCalledWith('myType', 'myApp', 'create'); + expect(checkPrivileges).toHaveBeenCalledWith([ + mockAuthorizationAction('myType', 'myApp', 'create'), + ]); + + expect(auditLogger.alertsAuthorizationSuccess).toHaveBeenCalledTimes(1); + expect(auditLogger.alertsAuthorizationFailure).not.toHaveBeenCalled(); + expect(auditLogger.alertsAuthorizationSuccess.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "some-user", + "myType", + 0, + "alerts", + "create", + ] + `); + }); + + test('ensures the user has privileges to execute the specified type, operation and producer when producer is different from consumer', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: true, + privileges: [], + }); + + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + + await alertAuthorization.ensureAuthorized('myType', 'myOtherApp', WriteOperations.Create); + + expect(alertTypeRegistry.get).toHaveBeenCalledWith('myType'); + + expect(authorization.actions.alerting.get).toHaveBeenCalledWith('myType', 'myApp', 'create'); + expect(authorization.actions.alerting.get).toHaveBeenCalledWith( + 'myType', + 'myOtherApp', + 'create' + ); + expect(checkPrivileges).toHaveBeenCalledWith([ + mockAuthorizationAction('myType', 'myOtherApp', 'create'), + mockAuthorizationAction('myType', 'myApp', 'create'), + ]); + + expect(auditLogger.alertsAuthorizationSuccess).toHaveBeenCalledTimes(1); + expect(auditLogger.alertsAuthorizationFailure).not.toHaveBeenCalled(); + expect(auditLogger.alertsAuthorizationSuccess.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "some-user", + "myType", + 0, + "myOtherApp", + "create", + ] + `); + }); + + test('throws if user lacks the required privieleges for the consumer', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: false, + privileges: [ + { + privilege: mockAuthorizationAction('myType', 'myOtherApp', 'create'), + authorized: false, + }, + { + privilege: mockAuthorizationAction('myType', 'myApp', 'create'), + authorized: true, + }, + ], + }); + + await expect( + alertAuthorization.ensureAuthorized('myType', 'myOtherApp', WriteOperations.Create) + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Unauthorized to create a \\"myType\\" alert for \\"myOtherApp\\""` + ); + + expect(auditLogger.alertsAuthorizationSuccess).not.toHaveBeenCalled(); + expect(auditLogger.alertsAuthorizationFailure).toHaveBeenCalledTimes(1); + expect(auditLogger.alertsAuthorizationFailure.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "some-user", + "myType", + 0, + "myOtherApp", + "create", + ] + `); + }); + + test('throws if user lacks the required privieleges for the producer', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: false, + privileges: [ + { + privilege: mockAuthorizationAction('myType', 'myOtherApp', 'create'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myType', 'myApp', 'create'), + authorized: false, + }, + ], + }); + + await expect( + alertAuthorization.ensureAuthorized('myType', 'myOtherApp', WriteOperations.Create) + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Unauthorized to create a \\"myType\\" alert by \\"myApp\\""` + ); + + expect(auditLogger.alertsAuthorizationSuccess).not.toHaveBeenCalled(); + expect(auditLogger.alertsAuthorizationFailure).toHaveBeenCalledTimes(1); + expect(auditLogger.alertsAuthorizationFailure.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "some-user", + "myType", + 1, + "myApp", + "create", + ] + `); + }); + + test('throws if user lacks the required privieleges for both consumer and producer', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: false, + privileges: [ + { + privilege: mockAuthorizationAction('myType', 'myOtherApp', 'create'), + authorized: false, + }, + { + privilege: mockAuthorizationAction('myType', 'myApp', 'create'), + authorized: false, + }, + ], + }); + + await expect( + alertAuthorization.ensureAuthorized('myType', 'myOtherApp', WriteOperations.Create) + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Unauthorized to create a \\"myType\\" alert for \\"myOtherApp\\""` + ); + + expect(auditLogger.alertsAuthorizationSuccess).not.toHaveBeenCalled(); + expect(auditLogger.alertsAuthorizationFailure).toHaveBeenCalledTimes(1); + expect(auditLogger.alertsAuthorizationFailure.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "some-user", + "myType", + 0, + "myOtherApp", + "create", + ] + `); + }); + }); + + describe('getFindAuthorizationFilter', () => { + const myOtherAppAlertType = { + actionGroups: [], + actionVariables: undefined, + defaultActionGroupId: 'default', + id: 'myOtherAppAlertType', + name: 'myOtherAppAlertType', + producer: 'alerts', + }; + const myAppAlertType = { + actionGroups: [], + actionVariables: undefined, + defaultActionGroupId: 'default', + id: 'myAppAlertType', + name: 'myAppAlertType', + producer: 'myApp', + }; + const mySecondAppAlertType = { + actionGroups: [], + actionVariables: undefined, + defaultActionGroupId: 'default', + id: 'mySecondAppAlertType', + name: 'mySecondAppAlertType', + producer: 'myApp', + }; + const setOfAlertTypes = new Set([myAppAlertType, myOtherAppAlertType, mySecondAppAlertType]); + + test('omits filter when there is no authorization api', async () => { + const alertAuthorization = new AlertsAuthorization({ + request, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + + const { + filter, + ensureAlertTypeIsAuthorized, + } = await alertAuthorization.getFindAuthorizationFilter(); + + expect(() => ensureAlertTypeIsAuthorized('someMadeUpType', 'myApp')).not.toThrow(); + + expect(filter).toEqual(undefined); + }); + + test('ensureAlertTypeIsAuthorized is no-op when there is no authorization api', async () => { + const alertAuthorization = new AlertsAuthorization({ + request, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + + const { ensureAlertTypeIsAuthorized } = await alertAuthorization.getFindAuthorizationFilter(); + + ensureAlertTypeIsAuthorized('someMadeUpType', 'myApp'); + + expect(auditLogger.alertsAuthorizationSuccess).not.toHaveBeenCalled(); + expect(auditLogger.alertsAuthorizationFailure).not.toHaveBeenCalled(); + }); + + test('creates a filter based on the privileged types', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: true, + privileges: [], + }); + + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + alertTypeRegistry.list.mockReturnValue(setOfAlertTypes); + + expect((await alertAuthorization.getFindAuthorizationFilter()).filter).toMatchInlineSnapshot( + `"((alert.attributes.alertTypeId:myAppAlertType and alert.attributes.consumer:(alerts or myApp or myOtherApp or myAppWithSubFeature)) or (alert.attributes.alertTypeId:myOtherAppAlertType and alert.attributes.consumer:(alerts or myApp or myOtherApp or myAppWithSubFeature)) or (alert.attributes.alertTypeId:mySecondAppAlertType and alert.attributes.consumer:(alerts or myApp or myOtherApp or myAppWithSubFeature)))"` + ); + + expect(auditLogger.alertsAuthorizationSuccess).not.toHaveBeenCalled(); + }); + + test('creates an `ensureAlertTypeIsAuthorized` function which throws if type is unauthorized', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: false, + privileges: [ + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myApp', 'find'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myOtherApp', 'find'), + authorized: false, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myApp', 'find'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myOtherApp', 'find'), + authorized: false, + }, + ], + }); + + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + alertTypeRegistry.list.mockReturnValue(setOfAlertTypes); + + const { ensureAlertTypeIsAuthorized } = await alertAuthorization.getFindAuthorizationFilter(); + expect(() => { + ensureAlertTypeIsAuthorized('myAppAlertType', 'myOtherApp'); + }).toThrowErrorMatchingInlineSnapshot( + `"Unauthorized to find a \\"myAppAlertType\\" alert for \\"myOtherApp\\""` + ); + + expect(auditLogger.alertsAuthorizationSuccess).not.toHaveBeenCalled(); + expect(auditLogger.alertsAuthorizationFailure).toHaveBeenCalledTimes(1); + expect(auditLogger.alertsAuthorizationFailure.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "some-user", + "myAppAlertType", + 0, + "myOtherApp", + "find", + ] + `); + }); + + test('creates an `ensureAlertTypeIsAuthorized` function which is no-op if type is authorized', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: false, + privileges: [ + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myApp', 'find'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myOtherApp', 'find'), + authorized: false, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myApp', 'find'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myOtherApp', 'find'), + authorized: true, + }, + ], + }); + + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + alertTypeRegistry.list.mockReturnValue(setOfAlertTypes); + + const { ensureAlertTypeIsAuthorized } = await alertAuthorization.getFindAuthorizationFilter(); + expect(() => { + ensureAlertTypeIsAuthorized('myAppAlertType', 'myOtherApp'); + }).not.toThrow(); + + expect(auditLogger.alertsAuthorizationSuccess).not.toHaveBeenCalled(); + expect(auditLogger.alertsAuthorizationFailure).not.toHaveBeenCalled(); + }); + + test('creates an `logSuccessfulAuthorization` function which logs every authorized type', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: false, + privileges: [ + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myApp', 'find'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myOtherApp', 'find'), + authorized: false, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myApp', 'find'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myOtherApp', 'find'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('mySecondAppAlertType', 'myApp', 'find'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('mySecondAppAlertType', 'myOtherApp', 'find'), + authorized: true, + }, + ], + }); + + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + alertTypeRegistry.list.mockReturnValue(setOfAlertTypes); + + const { + ensureAlertTypeIsAuthorized, + logSuccessfulAuthorization, + } = await alertAuthorization.getFindAuthorizationFilter(); + expect(() => { + ensureAlertTypeIsAuthorized('myAppAlertType', 'myOtherApp'); + ensureAlertTypeIsAuthorized('mySecondAppAlertType', 'myOtherApp'); + ensureAlertTypeIsAuthorized('myAppAlertType', 'myOtherApp'); + }).not.toThrow(); + + expect(auditLogger.alertsAuthorizationSuccess).not.toHaveBeenCalled(); + expect(auditLogger.alertsAuthorizationFailure).not.toHaveBeenCalled(); + + logSuccessfulAuthorization(); + + expect(auditLogger.alertsBulkAuthorizationSuccess).toHaveBeenCalledTimes(1); + expect(auditLogger.alertsBulkAuthorizationSuccess.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "some-user", + Array [ + Array [ + "myAppAlertType", + "myOtherApp", + ], + Array [ + "mySecondAppAlertType", + "myOtherApp", + ], + ], + 0, + "find", + ] + `); + }); + }); + + describe('filterByAlertTypeAuthorization', () => { + const myOtherAppAlertType = { + actionGroups: [], + actionVariables: undefined, + defaultActionGroupId: 'default', + id: 'myOtherAppAlertType', + name: 'myOtherAppAlertType', + producer: 'myOtherApp', + }; + const myAppAlertType = { + actionGroups: [], + actionVariables: undefined, + defaultActionGroupId: 'default', + id: 'myAppAlertType', + name: 'myAppAlertType', + producer: 'myApp', + }; + const setOfAlertTypes = new Set([myAppAlertType, myOtherAppAlertType]); + + test('augments a list of types with all features when there is no authorization api', async () => { + const alertAuthorization = new AlertsAuthorization({ + request, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + alertTypeRegistry.list.mockReturnValue(setOfAlertTypes); + + await expect( + alertAuthorization.filterByAlertTypeAuthorization( + new Set([myAppAlertType, myOtherAppAlertType]), + [WriteOperations.Create] + ) + ).resolves.toMatchInlineSnapshot(` + Set { + Object { + "actionGroups": Array [], + "actionVariables": undefined, + "authorizedConsumers": Object { + "alerts": Object { + "all": true, + "read": true, + }, + "myApp": Object { + "all": true, + "read": true, + }, + "myAppWithSubFeature": Object { + "all": true, + "read": true, + }, + "myOtherApp": Object { + "all": true, + "read": true, + }, + }, + "defaultActionGroupId": "default", + "id": "myAppAlertType", + "name": "myAppAlertType", + "producer": "myApp", + }, + Object { + "actionGroups": Array [], + "actionVariables": undefined, + "authorizedConsumers": Object { + "alerts": Object { + "all": true, + "read": true, + }, + "myApp": Object { + "all": true, + "read": true, + }, + "myAppWithSubFeature": Object { + "all": true, + "read": true, + }, + "myOtherApp": Object { + "all": true, + "read": true, + }, + }, + "defaultActionGroupId": "default", + "id": "myOtherAppAlertType", + "name": "myOtherAppAlertType", + "producer": "myOtherApp", + }, + } + `); + }); + + test('augments a list of types with consumers under which the operation is authorized', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: false, + privileges: [ + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myApp', 'create'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myOtherApp', 'create'), + authorized: false, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myApp', 'create'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myOtherApp', 'create'), + authorized: true, + }, + ], + }); + + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + alertTypeRegistry.list.mockReturnValue(setOfAlertTypes); + + await expect( + alertAuthorization.filterByAlertTypeAuthorization( + new Set([myAppAlertType, myOtherAppAlertType]), + [WriteOperations.Create] + ) + ).resolves.toMatchInlineSnapshot(` + Set { + Object { + "actionGroups": Array [], + "actionVariables": undefined, + "authorizedConsumers": Object { + "myApp": Object { + "all": true, + "read": true, + }, + }, + "defaultActionGroupId": "default", + "id": "myOtherAppAlertType", + "name": "myOtherAppAlertType", + "producer": "myOtherApp", + }, + Object { + "actionGroups": Array [], + "actionVariables": undefined, + "authorizedConsumers": Object { + "alerts": Object { + "all": true, + "read": true, + }, + "myApp": Object { + "all": true, + "read": true, + }, + "myOtherApp": Object { + "all": true, + "read": true, + }, + }, + "defaultActionGroupId": "default", + "id": "myAppAlertType", + "name": "myAppAlertType", + "producer": "myApp", + }, + } + `); + }); + + test('authorizes user under the Alerts consumer when they are authorized by the producer', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: false, + privileges: [ + { + privilege: mockAuthorizationAction('myAppAlertType', 'myApp', 'create'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myOtherApp', 'create'), + authorized: false, + }, + ], + }); + + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + alertTypeRegistry.list.mockReturnValue(setOfAlertTypes); + + await expect( + alertAuthorization.filterByAlertTypeAuthorization(new Set([myAppAlertType]), [ + WriteOperations.Create, + ]) + ).resolves.toMatchInlineSnapshot(` + Set { + Object { + "actionGroups": Array [], + "actionVariables": undefined, + "authorizedConsumers": Object { + "alerts": Object { + "all": true, + "read": true, + }, + "myApp": Object { + "all": true, + "read": true, + }, + }, + "defaultActionGroupId": "default", + "id": "myAppAlertType", + "name": "myAppAlertType", + "producer": "myApp", + }, + } + `); + }); + + test('augments a list of types with consumers under which multiple operations are authorized', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: false, + privileges: [ + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myApp', 'create'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myOtherApp', 'create'), + authorized: false, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myApp', 'create'), + authorized: false, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myOtherApp', 'create'), + authorized: false, + }, + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myApp', 'get'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myOtherApp', 'get'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myApp', 'get'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myOtherApp', 'get'), + authorized: true, + }, + ], + }); + + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + alertTypeRegistry.list.mockReturnValue(setOfAlertTypes); + + await expect( + alertAuthorization.filterByAlertTypeAuthorization( + new Set([myAppAlertType, myOtherAppAlertType]), + [WriteOperations.Create, ReadOperations.Get] + ) + ).resolves.toMatchInlineSnapshot(` + Set { + Object { + "actionGroups": Array [], + "actionVariables": undefined, + "authorizedConsumers": Object { + "alerts": Object { + "all": false, + "read": true, + }, + "myApp": Object { + "all": true, + "read": true, + }, + "myOtherApp": Object { + "all": false, + "read": true, + }, + }, + "defaultActionGroupId": "default", + "id": "myOtherAppAlertType", + "name": "myOtherAppAlertType", + "producer": "myOtherApp", + }, + Object { + "actionGroups": Array [], + "actionVariables": undefined, + "authorizedConsumers": Object { + "alerts": Object { + "all": false, + "read": true, + }, + "myApp": Object { + "all": false, + "read": true, + }, + "myOtherApp": Object { + "all": false, + "read": true, + }, + }, + "defaultActionGroupId": "default", + "id": "myAppAlertType", + "name": "myAppAlertType", + "producer": "myApp", + }, + } + `); + }); + + test('omits types which have no consumers under which the operation is authorized', async () => { + const { authorization } = mockSecurity(); + const checkPrivileges: jest.MockedFunction> = jest.fn(); + authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges); + checkPrivileges.mockResolvedValueOnce({ + username: 'some-user', + hasAllRequested: false, + privileges: [ + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myApp', 'create'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myOtherAppAlertType', 'myOtherApp', 'create'), + authorized: true, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myApp', 'create'), + authorized: false, + }, + { + privilege: mockAuthorizationAction('myAppAlertType', 'myOtherApp', 'create'), + authorized: false, + }, + ], + }); + + const alertAuthorization = new AlertsAuthorization({ + request, + authorization, + alertTypeRegistry, + features, + auditLogger, + getSpace, + }); + alertTypeRegistry.list.mockReturnValue(setOfAlertTypes); + + await expect( + alertAuthorization.filterByAlertTypeAuthorization( + new Set([myAppAlertType, myOtherAppAlertType]), + [WriteOperations.Create] + ) + ).resolves.toMatchInlineSnapshot(` + Set { + Object { + "actionGroups": Array [], + "actionVariables": undefined, + "authorizedConsumers": Object { + "alerts": Object { + "all": true, + "read": true, + }, + "myApp": Object { + "all": true, + "read": true, + }, + "myOtherApp": Object { + "all": true, + "read": true, + }, + }, + "defaultActionGroupId": "default", + "id": "myOtherAppAlertType", + "name": "myOtherAppAlertType", + "producer": "myOtherApp", + }, + } + `); + }); + }); + + describe('ensureFieldIsSafeForQuery', () => { + test('throws if field contains character that isnt safe in a KQL query', () => { + expect(() => ensureFieldIsSafeForQuery('id', 'alert-*')).toThrowError( + `expected id not to include invalid character: *` + ); + + expect(() => ensureFieldIsSafeForQuery('id', '<=""')).toThrowError( + `expected id not to include invalid character: <=` + ); + + expect(() => ensureFieldIsSafeForQuery('id', '>=""')).toThrowError( + `expected id not to include invalid character: >=` + ); + + expect(() => ensureFieldIsSafeForQuery('id', '1 or alertid:123')).toThrowError( + `expected id not to include whitespace and invalid character: :` + ); + + expect(() => ensureFieldIsSafeForQuery('id', ') or alertid:123')).toThrowError( + `expected id not to include whitespace and invalid characters: ), :` + ); + + expect(() => ensureFieldIsSafeForQuery('id', 'some space')).toThrowError( + `expected id not to include whitespace` + ); + }); + + test('doesnt throws if field is safe as part of a KQL query', () => { + expect(() => ensureFieldIsSafeForQuery('id', '123-0456-678')).not.toThrow(); + }); + }); +}); diff --git a/x-pack/plugins/alerts/server/authorization/alerts_authorization.ts b/x-pack/plugins/alerts/server/authorization/alerts_authorization.ts new file mode 100644 index 0000000000000..33a9a0bf0396e --- /dev/null +++ b/x-pack/plugins/alerts/server/authorization/alerts_authorization.ts @@ -0,0 +1,457 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 Boom from 'boom'; +import { map, mapValues, remove, fromPairs, has } from 'lodash'; +import { KibanaRequest } from 'src/core/server'; +import { ALERTS_FEATURE_ID } from '../../common'; +import { AlertTypeRegistry } from '../types'; +import { SecurityPluginSetup } from '../../../security/server'; +import { RegistryAlertType } from '../alert_type_registry'; +import { PluginStartContract as FeaturesPluginStart } from '../../../features/server'; +import { AlertsAuthorizationAuditLogger, ScopeType } from './audit_logger'; +import { Space } from '../../../spaces/server'; + +export enum ReadOperations { + Get = 'get', + GetAlertState = 'getAlertState', + Find = 'find', +} + +export enum WriteOperations { + Create = 'create', + Delete = 'delete', + Update = 'update', + UpdateApiKey = 'updateApiKey', + Enable = 'enable', + Disable = 'disable', + MuteAll = 'muteAll', + UnmuteAll = 'unmuteAll', + MuteInstance = 'muteInstance', + UnmuteInstance = 'unmuteInstance', +} + +interface HasPrivileges { + read: boolean; + all: boolean; +} +type AuthorizedConsumers = Record; +export interface RegistryAlertTypeWithAuth extends RegistryAlertType { + authorizedConsumers: AuthorizedConsumers; +} + +type IsAuthorizedAtProducerLevel = boolean; + +export interface ConstructorOptions { + alertTypeRegistry: AlertTypeRegistry; + request: KibanaRequest; + features: FeaturesPluginStart; + getSpace: (request: KibanaRequest) => Promise; + auditLogger: AlertsAuthorizationAuditLogger; + authorization?: SecurityPluginSetup['authz']; +} + +export class AlertsAuthorization { + private readonly alertTypeRegistry: AlertTypeRegistry; + private readonly request: KibanaRequest; + private readonly authorization?: SecurityPluginSetup['authz']; + private readonly auditLogger: AlertsAuthorizationAuditLogger; + private readonly featuresIds: Promise>; + private readonly allPossibleConsumers: Promise; + + constructor({ + alertTypeRegistry, + request, + authorization, + features, + auditLogger, + getSpace, + }: ConstructorOptions) { + this.request = request; + this.authorization = authorization; + this.alertTypeRegistry = alertTypeRegistry; + this.auditLogger = auditLogger; + + this.featuresIds = getSpace(request) + .then((maybeSpace) => new Set(maybeSpace?.disabledFeatures ?? [])) + .then( + (disabledFeatures) => + new Set( + features + .getFeatures() + .filter( + ({ id, alerting }) => + // ignore features which are disabled in the user's space + !disabledFeatures.has(id) && + // ignore features which don't grant privileges to alerting + (alerting?.length ?? 0 > 0) + ) + .map((feature) => feature.id) + ) + ) + .catch(() => { + // failing to fetch the space means the user is likely not privileged in the + // active space at all, which means that their list of features should be empty + return new Set(); + }); + + this.allPossibleConsumers = this.featuresIds.then((featuresIds) => + featuresIds.size + ? asAuthorizedConsumers([ALERTS_FEATURE_ID, ...featuresIds], { + read: true, + all: true, + }) + : {} + ); + } + + private shouldCheckAuthorization(): boolean { + return this.authorization?.mode?.useRbacForRequest(this.request) ?? false; + } + + public async ensureAuthorized( + alertTypeId: string, + consumer: string, + operation: ReadOperations | WriteOperations + ) { + const { authorization } = this; + + const isAvailableConsumer = has(await this.allPossibleConsumers, consumer); + if (authorization && this.shouldCheckAuthorization()) { + const alertType = this.alertTypeRegistry.get(alertTypeId); + const requiredPrivilegesByScope = { + consumer: authorization.actions.alerting.get(alertTypeId, consumer, operation), + producer: authorization.actions.alerting.get(alertTypeId, alertType.producer, operation), + }; + + // We special case the Alerts Management `consumer` as we don't want to have to + // manually authorize each alert type in the management UI + const shouldAuthorizeConsumer = consumer !== ALERTS_FEATURE_ID; + + const checkPrivileges = authorization.checkPrivilegesDynamicallyWithRequest(this.request); + const { hasAllRequested, username, privileges } = await checkPrivileges( + shouldAuthorizeConsumer && consumer !== alertType.producer + ? [ + // check for access at consumer level + requiredPrivilegesByScope.consumer, + // check for access at producer level + requiredPrivilegesByScope.producer, + ] + : [ + // skip consumer privilege checks under `alerts` as all alert types can + // be created under `alerts` if you have producer level privileges + requiredPrivilegesByScope.producer, + ] + ); + + if (!isAvailableConsumer) { + /** + * Under most circumstances this would have been caught by `checkPrivileges` as + * a user can't have Privileges to an unknown consumer, but super users + * don't actually get "privilege checked" so the made up consumer *will* return + * as Privileged. + * This check will ensure we don't accidentally let these through + */ + throw Boom.forbidden( + this.auditLogger.alertsAuthorizationFailure( + username, + alertTypeId, + ScopeType.Consumer, + consumer, + operation + ) + ); + } + + if (hasAllRequested) { + this.auditLogger.alertsAuthorizationSuccess( + username, + alertTypeId, + ScopeType.Consumer, + consumer, + operation + ); + } else { + const authorizedPrivileges = map( + privileges.filter((privilege) => privilege.authorized), + 'privilege' + ); + const unauthorizedScopes = mapValues( + requiredPrivilegesByScope, + (privilege) => !authorizedPrivileges.includes(privilege) + ); + + const [unauthorizedScopeType, unauthorizedScope] = + shouldAuthorizeConsumer && unauthorizedScopes.consumer + ? [ScopeType.Consumer, consumer] + : [ScopeType.Producer, alertType.producer]; + + throw Boom.forbidden( + this.auditLogger.alertsAuthorizationFailure( + username, + alertTypeId, + unauthorizedScopeType, + unauthorizedScope, + operation + ) + ); + } + } else if (!isAvailableConsumer) { + throw Boom.forbidden( + this.auditLogger.alertsAuthorizationFailure( + '', + alertTypeId, + ScopeType.Consumer, + consumer, + operation + ) + ); + } + } + + public async getFindAuthorizationFilter(): Promise<{ + filter?: string; + ensureAlertTypeIsAuthorized: (alertTypeId: string, consumer: string) => void; + logSuccessfulAuthorization: () => void; + }> { + if (this.authorization && this.shouldCheckAuthorization()) { + const { + username, + authorizedAlertTypes, + } = await this.augmentAlertTypesWithAuthorization(this.alertTypeRegistry.list(), [ + ReadOperations.Find, + ]); + + if (!authorizedAlertTypes.size) { + throw Boom.forbidden( + this.auditLogger.alertsUnscopedAuthorizationFailure(username!, 'find') + ); + } + + const authorizedAlertTypeIdsToConsumers = new Set( + [...authorizedAlertTypes].reduce((alertTypeIdConsumerPairs, alertType) => { + for (const consumer of Object.keys(alertType.authorizedConsumers)) { + alertTypeIdConsumerPairs.push(`${alertType.id}/${consumer}`); + } + return alertTypeIdConsumerPairs; + }, []) + ); + + const authorizedEntries: Map> = new Map(); + return { + filter: `(${this.asFiltersByAlertTypeAndConsumer(authorizedAlertTypes).join(' or ')})`, + ensureAlertTypeIsAuthorized: (alertTypeId: string, consumer: string) => { + if (!authorizedAlertTypeIdsToConsumers.has(`${alertTypeId}/${consumer}`)) { + throw Boom.forbidden( + this.auditLogger.alertsAuthorizationFailure( + username!, + alertTypeId, + ScopeType.Consumer, + consumer, + 'find' + ) + ); + } else { + if (authorizedEntries.has(alertTypeId)) { + authorizedEntries.get(alertTypeId)!.add(consumer); + } else { + authorizedEntries.set(alertTypeId, new Set([consumer])); + } + } + }, + logSuccessfulAuthorization: () => { + if (authorizedEntries.size) { + this.auditLogger.alertsBulkAuthorizationSuccess( + username!, + [...authorizedEntries.entries()].reduce>( + (authorizedPairs, [alertTypeId, consumers]) => { + for (const consumer of consumers) { + authorizedPairs.push([alertTypeId, consumer]); + } + return authorizedPairs; + }, + [] + ), + ScopeType.Consumer, + 'find' + ); + } + }, + }; + } + return { + ensureAlertTypeIsAuthorized: (alertTypeId: string, consumer: string) => {}, + logSuccessfulAuthorization: () => {}, + }; + } + + public async filterByAlertTypeAuthorization( + alertTypes: Set, + operations: Array + ): Promise> { + const { authorizedAlertTypes } = await this.augmentAlertTypesWithAuthorization( + alertTypes, + operations + ); + return authorizedAlertTypes; + } + + private async augmentAlertTypesWithAuthorization( + alertTypes: Set, + operations: Array + ): Promise<{ + username?: string; + hasAllRequested: boolean; + authorizedAlertTypes: Set; + }> { + const featuresIds = await this.featuresIds; + if (this.authorization && this.shouldCheckAuthorization()) { + const checkPrivileges = this.authorization.checkPrivilegesDynamicallyWithRequest( + this.request + ); + + // add an empty `authorizedConsumers` array on each alertType + const alertTypesWithAuthorization = this.augmentWithAuthorizedConsumers(alertTypes, {}); + + // map from privilege to alertType which we can refer back to when analyzing the result + // of checkPrivileges + const privilegeToAlertType = new Map< + string, + [RegistryAlertTypeWithAuth, string, HasPrivileges, IsAuthorizedAtProducerLevel] + >(); + // as we can't ask ES for the user's individual privileges we need to ask for each feature + // and alertType in the system whether this user has this privilege + for (const alertType of alertTypesWithAuthorization) { + for (const feature of featuresIds) { + for (const operation of operations) { + privilegeToAlertType.set( + this.authorization!.actions.alerting.get(alertType.id, feature, operation), + [ + alertType, + feature, + hasPrivilegeByOperation(operation), + alertType.producer === feature, + ] + ); + } + } + } + + const { username, hasAllRequested, privileges } = await checkPrivileges([ + ...privilegeToAlertType.keys(), + ]); + + return { + username, + hasAllRequested, + authorizedAlertTypes: hasAllRequested + ? // has access to all features + this.augmentWithAuthorizedConsumers(alertTypes, await this.allPossibleConsumers) + : // only has some of the required privileges + privileges.reduce((authorizedAlertTypes, { authorized, privilege }) => { + if (authorized && privilegeToAlertType.has(privilege)) { + const [ + alertType, + feature, + hasPrivileges, + isAuthorizedAtProducerLevel, + ] = privilegeToAlertType.get(privilege)!; + alertType.authorizedConsumers[feature] = mergeHasPrivileges( + hasPrivileges, + alertType.authorizedConsumers[feature] + ); + + if (isAuthorizedAtProducerLevel) { + // granting privileges under the producer automatically authorized the Alerts Management UI as well + alertType.authorizedConsumers[ALERTS_FEATURE_ID] = mergeHasPrivileges( + hasPrivileges, + alertType.authorizedConsumers[ALERTS_FEATURE_ID] + ); + } + authorizedAlertTypes.add(alertType); + } + return authorizedAlertTypes; + }, new Set()), + }; + } else { + return { + hasAllRequested: true, + authorizedAlertTypes: this.augmentWithAuthorizedConsumers( + new Set([...alertTypes].filter((alertType) => featuresIds.has(alertType.producer))), + await this.allPossibleConsumers + ), + }; + } + } + + private augmentWithAuthorizedConsumers( + alertTypes: Set, + authorizedConsumers: AuthorizedConsumers + ): Set { + return new Set( + Array.from(alertTypes).map((alertType) => ({ + ...alertType, + authorizedConsumers: { ...authorizedConsumers }, + })) + ); + } + + private asFiltersByAlertTypeAndConsumer(alertTypes: Set): string[] { + return Array.from(alertTypes).reduce((filters, { id, authorizedConsumers }) => { + ensureFieldIsSafeForQuery('alertTypeId', id); + filters.push( + `(alert.attributes.alertTypeId:${id} and alert.attributes.consumer:(${Object.keys( + authorizedConsumers + ) + .map((consumer) => { + ensureFieldIsSafeForQuery('alertTypeId', id); + return consumer; + }) + .join(' or ')}))` + ); + return filters; + }, []); + } +} + +export function ensureFieldIsSafeForQuery(field: string, value: string): boolean { + const invalid = value.match(/([>=<\*:()]+|\s+)/g); + if (invalid) { + const whitespace = remove(invalid, (chars) => chars.trim().length === 0); + const errors = []; + if (whitespace.length) { + errors.push(`whitespace`); + } + if (invalid.length) { + errors.push(`invalid character${invalid.length > 1 ? `s` : ``}: ${invalid?.join(`, `)}`); + } + throw new Error(`expected ${field} not to include ${errors.join(' and ')}`); + } + return true; +} + +function mergeHasPrivileges(left: HasPrivileges, right?: HasPrivileges): HasPrivileges { + return { + read: (left.read || right?.read) ?? false, + all: (left.all || right?.all) ?? false, + }; +} + +function hasPrivilegeByOperation(operation: ReadOperations | WriteOperations): HasPrivileges { + const read = Object.values(ReadOperations).includes((operation as unknown) as ReadOperations); + const all = Object.values(WriteOperations).includes((operation as unknown) as WriteOperations); + return { + read: read || all, + all, + }; +} + +function asAuthorizedConsumers( + consumers: string[], + hasPrivileges: HasPrivileges +): AuthorizedConsumers { + return fromPairs(consumers.map((feature) => [feature, hasPrivileges])); +} diff --git a/x-pack/plugins/alerts/server/authorization/audit_logger.mock.ts b/x-pack/plugins/alerts/server/authorization/audit_logger.mock.ts new file mode 100644 index 0000000000000..ca6a35b24bcac --- /dev/null +++ b/x-pack/plugins/alerts/server/authorization/audit_logger.mock.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 { AlertsAuthorizationAuditLogger } from './audit_logger'; + +const createAlertsAuthorizationAuditLoggerMock = () => { + const mocked = ({ + getAuthorizationMessage: jest.fn(), + alertsAuthorizationFailure: jest.fn(), + alertsUnscopedAuthorizationFailure: jest.fn(), + alertsAuthorizationSuccess: jest.fn(), + alertsBulkAuthorizationSuccess: jest.fn(), + } as unknown) as jest.Mocked; + return mocked; +}; + +export const alertsAuthorizationAuditLoggerMock: { + create: () => jest.Mocked; +} = { + create: createAlertsAuthorizationAuditLoggerMock, +}; diff --git a/x-pack/plugins/alerts/server/authorization/audit_logger.test.ts b/x-pack/plugins/alerts/server/authorization/audit_logger.test.ts new file mode 100644 index 0000000000000..40973a3a67a51 --- /dev/null +++ b/x-pack/plugins/alerts/server/authorization/audit_logger.test.ts @@ -0,0 +1,311 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { AlertsAuthorizationAuditLogger, ScopeType } from './audit_logger'; + +const createMockAuditLogger = () => { + return { + log: jest.fn(), + }; +}; + +describe(`#constructor`, () => { + test('initializes a noop auditLogger if security logger is unavailable', () => { + const alertsAuditLogger = new AlertsAuthorizationAuditLogger(undefined); + + const username = 'foo-user'; + const alertTypeId = 'alert-type-id'; + const scopeType = ScopeType.Consumer; + const scope = 'myApp'; + const operation = 'create'; + expect(() => { + alertsAuditLogger.alertsAuthorizationFailure( + username, + alertTypeId, + scopeType, + scope, + operation + ); + + alertsAuditLogger.alertsAuthorizationSuccess( + username, + alertTypeId, + scopeType, + scope, + operation + ); + }).not.toThrow(); + }); +}); + +describe(`#alertsUnscopedAuthorizationFailure`, () => { + test('logs auth failure of operation', () => { + const auditLogger = createMockAuditLogger(); + const alertsAuditLogger = new AlertsAuthorizationAuditLogger(auditLogger); + const username = 'foo-user'; + const operation = 'create'; + + alertsAuditLogger.alertsUnscopedAuthorizationFailure(username, operation); + + expect(auditLogger.log.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "alerts_unscoped_authorization_failure", + "foo-user Unauthorized to create any alert types", + Object { + "operation": "create", + "username": "foo-user", + }, + ] + `); + }); + + test('logs auth failure with producer scope', () => { + const auditLogger = createMockAuditLogger(); + const alertsAuditLogger = new AlertsAuthorizationAuditLogger(auditLogger); + const username = 'foo-user'; + const alertTypeId = 'alert-type-id'; + const scopeType = ScopeType.Producer; + const scope = 'myOtherApp'; + const operation = 'create'; + + alertsAuditLogger.alertsAuthorizationFailure( + username, + alertTypeId, + scopeType, + scope, + operation + ); + + expect(auditLogger.log.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "alerts_authorization_failure", + "foo-user Unauthorized to create a \\"alert-type-id\\" alert by \\"myOtherApp\\"", + Object { + "alertTypeId": "alert-type-id", + "operation": "create", + "scope": "myOtherApp", + "scopeType": 1, + "username": "foo-user", + }, + ] + `); + }); +}); + +describe(`#alertsAuthorizationFailure`, () => { + test('logs auth failure with consumer scope', () => { + const auditLogger = createMockAuditLogger(); + const alertsAuditLogger = new AlertsAuthorizationAuditLogger(auditLogger); + const username = 'foo-user'; + const alertTypeId = 'alert-type-id'; + const scopeType = ScopeType.Consumer; + const scope = 'myApp'; + const operation = 'create'; + + alertsAuditLogger.alertsAuthorizationFailure( + username, + alertTypeId, + scopeType, + scope, + operation + ); + + expect(auditLogger.log.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "alerts_authorization_failure", + "foo-user Unauthorized to create a \\"alert-type-id\\" alert for \\"myApp\\"", + Object { + "alertTypeId": "alert-type-id", + "operation": "create", + "scope": "myApp", + "scopeType": 0, + "username": "foo-user", + }, + ] + `); + }); + + test('logs auth failure with producer scope', () => { + const auditLogger = createMockAuditLogger(); + const alertsAuditLogger = new AlertsAuthorizationAuditLogger(auditLogger); + const username = 'foo-user'; + const alertTypeId = 'alert-type-id'; + const scopeType = ScopeType.Producer; + const scope = 'myOtherApp'; + const operation = 'create'; + + alertsAuditLogger.alertsAuthorizationFailure( + username, + alertTypeId, + scopeType, + scope, + operation + ); + + expect(auditLogger.log.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "alerts_authorization_failure", + "foo-user Unauthorized to create a \\"alert-type-id\\" alert by \\"myOtherApp\\"", + Object { + "alertTypeId": "alert-type-id", + "operation": "create", + "scope": "myOtherApp", + "scopeType": 1, + "username": "foo-user", + }, + ] + `); + }); +}); + +describe(`#alertsBulkAuthorizationSuccess`, () => { + test('logs auth success with consumer scope', () => { + const auditLogger = createMockAuditLogger(); + const alertsAuditLogger = new AlertsAuthorizationAuditLogger(auditLogger); + const username = 'foo-user'; + const scopeType = ScopeType.Consumer; + const authorizedEntries: Array<[string, string]> = [ + ['alert-type-id', 'myApp'], + ['other-alert-type-id', 'myOtherApp'], + ]; + const operation = 'create'; + + alertsAuditLogger.alertsBulkAuthorizationSuccess( + username, + authorizedEntries, + scopeType, + operation + ); + + expect(auditLogger.log.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "alerts_authorization_success", + "foo-user Authorized to create: \\"alert-type-id\\" alert for \\"myApp\\", \\"other-alert-type-id\\" alert for \\"myOtherApp\\"", + Object { + "authorizedEntries": Array [ + Array [ + "alert-type-id", + "myApp", + ], + Array [ + "other-alert-type-id", + "myOtherApp", + ], + ], + "operation": "create", + "scopeType": 0, + "username": "foo-user", + }, + ] + `); + }); + + test('logs auth success with producer scope', () => { + const auditLogger = createMockAuditLogger(); + const alertsAuditLogger = new AlertsAuthorizationAuditLogger(auditLogger); + const username = 'foo-user'; + const scopeType = ScopeType.Producer; + const authorizedEntries: Array<[string, string]> = [ + ['alert-type-id', 'myApp'], + ['other-alert-type-id', 'myOtherApp'], + ]; + const operation = 'create'; + + alertsAuditLogger.alertsBulkAuthorizationSuccess( + username, + authorizedEntries, + scopeType, + operation + ); + + expect(auditLogger.log.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "alerts_authorization_success", + "foo-user Authorized to create: \\"alert-type-id\\" alert by \\"myApp\\", \\"other-alert-type-id\\" alert by \\"myOtherApp\\"", + Object { + "authorizedEntries": Array [ + Array [ + "alert-type-id", + "myApp", + ], + Array [ + "other-alert-type-id", + "myOtherApp", + ], + ], + "operation": "create", + "scopeType": 1, + "username": "foo-user", + }, + ] + `); + }); +}); + +describe(`#savedObjectsAuthorizationSuccess`, () => { + test('logs auth success with consumer scope', () => { + const auditLogger = createMockAuditLogger(); + const alertsAuditLogger = new AlertsAuthorizationAuditLogger(auditLogger); + const username = 'foo-user'; + const alertTypeId = 'alert-type-id'; + const scopeType = ScopeType.Consumer; + const scope = 'myApp'; + const operation = 'create'; + + alertsAuditLogger.alertsAuthorizationSuccess( + username, + alertTypeId, + scopeType, + scope, + operation + ); + + expect(auditLogger.log.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "alerts_authorization_success", + "foo-user Authorized to create a \\"alert-type-id\\" alert for \\"myApp\\"", + Object { + "alertTypeId": "alert-type-id", + "operation": "create", + "scope": "myApp", + "scopeType": 0, + "username": "foo-user", + }, + ] + `); + }); + + test('logs auth success with producer scope', () => { + const auditLogger = createMockAuditLogger(); + const alertsAuditLogger = new AlertsAuthorizationAuditLogger(auditLogger); + const username = 'foo-user'; + const alertTypeId = 'alert-type-id'; + const scopeType = ScopeType.Producer; + const scope = 'myOtherApp'; + const operation = 'create'; + + alertsAuditLogger.alertsAuthorizationSuccess( + username, + alertTypeId, + scopeType, + scope, + operation + ); + + expect(auditLogger.log.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "alerts_authorization_success", + "foo-user Authorized to create a \\"alert-type-id\\" alert by \\"myOtherApp\\"", + Object { + "alertTypeId": "alert-type-id", + "operation": "create", + "scope": "myOtherApp", + "scopeType": 1, + "username": "foo-user", + }, + ] + `); + }); +}); diff --git a/x-pack/plugins/alerts/server/authorization/audit_logger.ts b/x-pack/plugins/alerts/server/authorization/audit_logger.ts new file mode 100644 index 0000000000000..f930da2ce428c --- /dev/null +++ b/x-pack/plugins/alerts/server/authorization/audit_logger.ts @@ -0,0 +1,117 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { AuditLogger } from '../../../security/server'; + +export enum ScopeType { + Consumer, + Producer, +} + +export enum AuthorizationResult { + Unauthorized = 'Unauthorized', + Authorized = 'Authorized', +} + +export class AlertsAuthorizationAuditLogger { + private readonly auditLogger: AuditLogger; + + constructor(auditLogger: AuditLogger = { log() {} }) { + this.auditLogger = auditLogger; + } + + public getAuthorizationMessage( + authorizationResult: AuthorizationResult, + alertTypeId: string, + scopeType: ScopeType, + scope: string, + operation: string + ): string { + return `${authorizationResult} to ${operation} a "${alertTypeId}" alert ${ + scopeType === ScopeType.Consumer ? `for "${scope}"` : `by "${scope}"` + }`; + } + + public alertsAuthorizationFailure( + username: string, + alertTypeId: string, + scopeType: ScopeType, + scope: string, + operation: string + ): string { + const message = this.getAuthorizationMessage( + AuthorizationResult.Unauthorized, + alertTypeId, + scopeType, + scope, + operation + ); + this.auditLogger.log('alerts_authorization_failure', `${username} ${message}`, { + username, + alertTypeId, + scopeType, + scope, + operation, + }); + return message; + } + + public alertsUnscopedAuthorizationFailure(username: string, operation: string): string { + const message = `Unauthorized to ${operation} any alert types`; + this.auditLogger.log('alerts_unscoped_authorization_failure', `${username} ${message}`, { + username, + operation, + }); + return message; + } + + public alertsAuthorizationSuccess( + username: string, + alertTypeId: string, + scopeType: ScopeType, + scope: string, + operation: string + ): string { + const message = this.getAuthorizationMessage( + AuthorizationResult.Authorized, + alertTypeId, + scopeType, + scope, + operation + ); + this.auditLogger.log('alerts_authorization_success', `${username} ${message}`, { + username, + alertTypeId, + scopeType, + scope, + operation, + }); + return message; + } + + public alertsBulkAuthorizationSuccess( + username: string, + authorizedEntries: Array<[string, string]>, + scopeType: ScopeType, + operation: string + ): string { + const message = `${AuthorizationResult.Authorized} to ${operation}: ${authorizedEntries + .map( + ([alertTypeId, scope]) => + `"${alertTypeId}" alert ${ + scopeType === ScopeType.Consumer ? `for "${scope}"` : `by "${scope}"` + }` + ) + .join(', ')}`; + this.auditLogger.log('alerts_authorization_success', `${username} ${message}`, { + username, + scopeType, + authorizedEntries, + operation, + }); + return message; + } +} diff --git a/x-pack/plugins/alerts/server/index.ts b/x-pack/plugins/alerts/server/index.ts index 727e38d9ba56b..515de771e7d6b 100644 --- a/x-pack/plugins/alerts/server/index.ts +++ b/x-pack/plugins/alerts/server/index.ts @@ -21,7 +21,7 @@ export { PartialAlert, } from './types'; export { PluginSetupContract, PluginStartContract } from './plugin'; -export { FindOptions, FindResult } from './alerts_client'; +export { FindResult } from './alerts_client'; export { AlertInstance } from './alert_instance'; export { parseDuration } from './lib'; diff --git a/x-pack/plugins/alerts/server/lib/validate_alert_type_params.test.ts b/x-pack/plugins/alerts/server/lib/validate_alert_type_params.test.ts index d31b15030fd3a..1e6c26c02e65b 100644 --- a/x-pack/plugins/alerts/server/lib/validate_alert_type_params.test.ts +++ b/x-pack/plugins/alerts/server/lib/validate_alert_type_params.test.ts @@ -20,7 +20,7 @@ test('should return passed in params when validation not defined', () => { ], defaultActionGroupId: 'default', async executor() {}, - producer: 'alerting', + producer: 'alerts', }, { foo: true, @@ -48,7 +48,7 @@ test('should validate and apply defaults when params is valid', () => { }), }, async executor() {}, - producer: 'alerting', + producer: 'alerts', }, { param1: 'value' } ); @@ -77,7 +77,7 @@ test('should validate and throw error when params is invalid', () => { }), }, async executor() {}, - producer: 'alerting', + producer: 'alerts', }, {} ) diff --git a/x-pack/plugins/alerts/server/plugin.test.ts b/x-pack/plugins/alerts/server/plugin.test.ts index 008a9bb804c5b..e65d195290259 100644 --- a/x-pack/plugins/alerts/server/plugin.test.ts +++ b/x-pack/plugins/alerts/server/plugin.test.ts @@ -11,6 +11,8 @@ import { encryptedSavedObjectsMock } from '../../encrypted_saved_objects/server/ import { taskManagerMock } from '../../task_manager/server/mocks'; import { eventLogServiceMock } from '../../event_log/server/event_log_service.mock'; import { KibanaRequest, CoreSetup } from 'kibana/server'; +import { featuresPluginMock } from '../../features/server/mocks'; +import { Feature } from '../../features/server'; describe('Alerting Plugin', () => { describe('setup()', () => { @@ -80,8 +82,10 @@ describe('Alerting Plugin', () => { actions: { execute: jest.fn(), getActionsClientWithRequest: jest.fn(), + getActionsAuthorizationWithRequest: jest.fn(), }, encryptedSavedObjects: encryptedSavedObjectsMock.createStart(), + features: mockFeatures(), } as unknown) as AlertingPluginsStart ); @@ -124,9 +128,11 @@ describe('Alerting Plugin', () => { actions: { execute: jest.fn(), getActionsClientWithRequest: jest.fn(), + getActionsAuthorizationWithRequest: jest.fn(), }, spaces: () => null, encryptedSavedObjects: encryptedSavedObjectsMock.createStart(), + features: mockFeatures(), } as unknown) as AlertingPluginsStart ); @@ -150,3 +156,31 @@ describe('Alerting Plugin', () => { }); }); }); + +function mockFeatures() { + const features = featuresPluginMock.createSetup(); + features.getFeatures.mockReturnValue([ + new Feature({ + id: 'appName', + name: 'appName', + app: [], + privileges: { + all: { + savedObject: { + all: [], + read: [], + }, + ui: [], + }, + read: { + savedObject: { + all: [], + read: [], + }, + ui: [], + }, + }, + }), + ]); + return features; +} diff --git a/x-pack/plugins/alerts/server/plugin.ts b/x-pack/plugins/alerts/server/plugin.ts index 07ed021d8ca84..2f0df44197553 100644 --- a/x-pack/plugins/alerts/server/plugin.ts +++ b/x-pack/plugins/alerts/server/plugin.ts @@ -58,6 +58,7 @@ import { Services } from './types'; import { registerAlertsUsageCollector } from './usage'; import { initializeAlertingTelemetry, scheduleAlertingTelemetry } from './usage/task'; import { IEventLogger, IEventLogService } from '../../event_log/server'; +import { PluginStartContract as FeaturesPluginStart } from '../../features/server'; import { setupSavedObjects } from './saved_objects'; const EVENT_LOG_PROVIDER = 'alerting'; @@ -90,6 +91,7 @@ export interface AlertingPluginsStart { actions: ActionsPluginStartContract; taskManager: TaskManagerStartContract; encryptedSavedObjects: EncryptedSavedObjectsPluginStart; + features: FeaturesPluginStart; } export class AlertingPlugin { @@ -127,6 +129,16 @@ export class AlertingPlugin { this.spaces = plugins.spaces?.spacesService; this.security = plugins.security; + core.capabilities.registerProvider(() => { + return { + management: { + insightsAndAlerting: { + triggersActions: true, + }, + }, + }; + }); + this.isESOUsingEphemeralEncryptionKey = plugins.encryptedSavedObjects.usingEphemeralEncryptionKey; @@ -216,12 +228,26 @@ export class AlertingPlugin { getSpaceId(request: KibanaRequest) { return spaces?.getSpaceId(request); }, + async getSpace(request: KibanaRequest) { + return spaces?.getActiveSpace(request); + }, actions: plugins.actions, + features: plugins.features, }); + const getAlertsClientWithRequest = (request: KibanaRequest) => { + if (isESOUsingEphemeralEncryptionKey === true) { + throw new Error( + `Unable to create alerts client due to the Encrypted Saved Objects plugin using an ephemeral encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in kibana.yml` + ); + } + return alertsClientFactory!.create(request, core.savedObjects); + }; + taskRunnerFactory.initialize({ logger, getServices: this.getServicesFactory(core.savedObjects, core.elasticsearch), + getAlertsClientWithRequest, spaceIdToNamespace: this.spaceIdToNamespace, actionsPlugin: plugins.actions, encryptedSavedObjectsClient, @@ -233,18 +259,7 @@ export class AlertingPlugin { return { listTypes: alertTypeRegistry!.list.bind(this.alertTypeRegistry!), - // Ability to get an alerts client from legacy code - getAlertsClientWithRequest: (request: KibanaRequest) => { - if (isESOUsingEphemeralEncryptionKey === true) { - throw new Error( - `Unable to create alerts client due to the Encrypted Saved Objects plugin using an ephemeral encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in kibana.yml` - ); - } - return alertsClientFactory!.create( - request, - this.getScopedClientWithAlertSavedObjectType(core.savedObjects, request) - ); - }, + getAlertsClientWithRequest, }; } @@ -252,14 +267,11 @@ export class AlertingPlugin { core: CoreSetup ): IContextProvider, 'alerting'> => { const { alertTypeRegistry, alertsClientFactory } = this; - return async (context, request) => { + return async function alertsRouteHandlerContext(context, request) { const [{ savedObjects }] = await core.getStartServices(); return { getAlertsClient: () => { - return alertsClientFactory!.create( - request, - this.getScopedClientWithAlertSavedObjectType(savedObjects, request) - ); + return alertsClientFactory!.create(request, savedObjects); }, listTypes: alertTypeRegistry!.list.bind(alertTypeRegistry!), }; diff --git a/x-pack/plugins/alerts/server/routes/create.test.ts b/x-pack/plugins/alerts/server/routes/create.test.ts index 9e941903eeaed..274acaf01c475 100644 --- a/x-pack/plugins/alerts/server/routes/create.test.ts +++ b/x-pack/plugins/alerts/server/routes/create.test.ts @@ -75,13 +75,6 @@ describe('createAlertRoute', () => { const [config, handler] = router.post.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-all", - ], - } - `); alertsClient.create.mockResolvedValueOnce(createResult); diff --git a/x-pack/plugins/alerts/server/routes/create.ts b/x-pack/plugins/alerts/server/routes/create.ts index 6238fca024e55..91a81f6d84b71 100644 --- a/x-pack/plugins/alerts/server/routes/create.ts +++ b/x-pack/plugins/alerts/server/routes/create.ts @@ -47,9 +47,6 @@ export const createAlertRoute = (router: IRouter, licenseState: LicenseState) => validate: { body: bodySchema, }, - options: { - tags: ['access:alerting-all'], - }, }, handleDisabledApiKeysError( router.handleLegacyErrors(async function ( diff --git a/x-pack/plugins/alerts/server/routes/delete.test.ts b/x-pack/plugins/alerts/server/routes/delete.test.ts index 9ba4e20312e17..d9c5aa2d59c87 100644 --- a/x-pack/plugins/alerts/server/routes/delete.test.ts +++ b/x-pack/plugins/alerts/server/routes/delete.test.ts @@ -30,13 +30,6 @@ describe('deleteAlertRoute', () => { const [config, handler] = router.delete.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-all", - ], - } - `); alertsClient.delete.mockResolvedValueOnce({}); diff --git a/x-pack/plugins/alerts/server/routes/delete.ts b/x-pack/plugins/alerts/server/routes/delete.ts index 2034bd21fbed6..b073c59149171 100644 --- a/x-pack/plugins/alerts/server/routes/delete.ts +++ b/x-pack/plugins/alerts/server/routes/delete.ts @@ -27,9 +27,6 @@ export const deleteAlertRoute = (router: IRouter, licenseState: LicenseState) => validate: { params: paramSchema, }, - options: { - tags: ['access:alerting-all'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/alerts/server/routes/disable.test.ts b/x-pack/plugins/alerts/server/routes/disable.test.ts index a82d09854a604..74f7b2eb8a570 100644 --- a/x-pack/plugins/alerts/server/routes/disable.test.ts +++ b/x-pack/plugins/alerts/server/routes/disable.test.ts @@ -30,13 +30,6 @@ describe('disableAlertRoute', () => { const [config, handler] = router.post.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/_disable"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-all", - ], - } - `); alertsClient.disable.mockResolvedValueOnce(); diff --git a/x-pack/plugins/alerts/server/routes/disable.ts b/x-pack/plugins/alerts/server/routes/disable.ts index dfc5dfbdd5aa2..234f8ed959a5d 100644 --- a/x-pack/plugins/alerts/server/routes/disable.ts +++ b/x-pack/plugins/alerts/server/routes/disable.ts @@ -27,9 +27,6 @@ export const disableAlertRoute = (router: IRouter, licenseState: LicenseState) = validate: { params: paramSchema, }, - options: { - tags: ['access:alerting-all'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/alerts/server/routes/enable.test.ts b/x-pack/plugins/alerts/server/routes/enable.test.ts index 4ee3a12a59dc7..c9575ef87f767 100644 --- a/x-pack/plugins/alerts/server/routes/enable.test.ts +++ b/x-pack/plugins/alerts/server/routes/enable.test.ts @@ -29,13 +29,6 @@ describe('enableAlertRoute', () => { const [config, handler] = router.post.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/_enable"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-all", - ], - } - `); alertsClient.enable.mockResolvedValueOnce(); diff --git a/x-pack/plugins/alerts/server/routes/enable.ts b/x-pack/plugins/alerts/server/routes/enable.ts index b6f86b97d6a3a..c162b4a9844b3 100644 --- a/x-pack/plugins/alerts/server/routes/enable.ts +++ b/x-pack/plugins/alerts/server/routes/enable.ts @@ -28,9 +28,6 @@ export const enableAlertRoute = (router: IRouter, licenseState: LicenseState) => validate: { params: paramSchema, }, - options: { - tags: ['access:alerting-all'], - }, }, handleDisabledApiKeysError( router.handleLegacyErrors(async function ( diff --git a/x-pack/plugins/alerts/server/routes/find.test.ts b/x-pack/plugins/alerts/server/routes/find.test.ts index f20ee0a54dcd9..46702f96a2e10 100644 --- a/x-pack/plugins/alerts/server/routes/find.test.ts +++ b/x-pack/plugins/alerts/server/routes/find.test.ts @@ -31,13 +31,6 @@ describe('findAlertRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/_find"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-read", - ], - } - `); const findResult = { page: 1, diff --git a/x-pack/plugins/alerts/server/routes/find.ts b/x-pack/plugins/alerts/server/routes/find.ts index 80c9c20eec7da..ef3b16dc9e517 100644 --- a/x-pack/plugins/alerts/server/routes/find.ts +++ b/x-pack/plugins/alerts/server/routes/find.ts @@ -16,7 +16,7 @@ import { LicenseState } from '../lib/license_state'; import { verifyApiAccess } from '../lib/license_api_access'; import { BASE_ALERT_API_PATH } from '../../common'; import { renameKeys } from './lib/rename_keys'; -import { FindOptions } from '..'; +import { FindOptions } from '../alerts_client'; // config definition const querySchema = schema.object({ @@ -50,9 +50,6 @@ export const findAlertRoute = (router: IRouter, licenseState: LicenseState) => { validate: { query: querySchema, }, - options: { - tags: ['access:alerting-read'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/alerts/server/routes/get.test.ts b/x-pack/plugins/alerts/server/routes/get.test.ts index b11224ff4794e..8c4b06adf70f7 100644 --- a/x-pack/plugins/alerts/server/routes/get.test.ts +++ b/x-pack/plugins/alerts/server/routes/get.test.ts @@ -61,13 +61,6 @@ describe('getAlertRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-read", - ], - } - `); alertsClient.get.mockResolvedValueOnce(mockedAlert); diff --git a/x-pack/plugins/alerts/server/routes/get.ts b/x-pack/plugins/alerts/server/routes/get.ts index ae9ebe1299371..0f3fc4b2f3e41 100644 --- a/x-pack/plugins/alerts/server/routes/get.ts +++ b/x-pack/plugins/alerts/server/routes/get.ts @@ -27,9 +27,6 @@ export const getAlertRoute = (router: IRouter, licenseState: LicenseState) => { validate: { params: paramSchema, }, - options: { - tags: ['access:alerting-read'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/alerts/server/routes/get_alert_state.test.ts b/x-pack/plugins/alerts/server/routes/get_alert_state.test.ts index 8c9051093f85b..d5bf9737d39ab 100644 --- a/x-pack/plugins/alerts/server/routes/get_alert_state.test.ts +++ b/x-pack/plugins/alerts/server/routes/get_alert_state.test.ts @@ -48,13 +48,6 @@ describe('getAlertStateRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/state"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-read", - ], - } - `); alertsClient.getAlertState.mockResolvedValueOnce(mockedAlertState); @@ -91,13 +84,6 @@ describe('getAlertStateRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/state"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-read", - ], - } - `); alertsClient.getAlertState.mockResolvedValueOnce(undefined); @@ -134,13 +120,6 @@ describe('getAlertStateRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/state"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-read", - ], - } - `); alertsClient.getAlertState = jest .fn() diff --git a/x-pack/plugins/alerts/server/routes/get_alert_state.ts b/x-pack/plugins/alerts/server/routes/get_alert_state.ts index b27ae3758e1b9..089fc80fca355 100644 --- a/x-pack/plugins/alerts/server/routes/get_alert_state.ts +++ b/x-pack/plugins/alerts/server/routes/get_alert_state.ts @@ -27,9 +27,6 @@ export const getAlertStateRoute = (router: IRouter, licenseState: LicenseState) validate: { params: paramSchema, }, - options: { - tags: ['access:alerting-read'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/alerts/server/routes/list_alert_types.test.ts b/x-pack/plugins/alerts/server/routes/list_alert_types.test.ts index 3192154f6664c..af20dd6e202ba 100644 --- a/x-pack/plugins/alerts/server/routes/list_alert_types.test.ts +++ b/x-pack/plugins/alerts/server/routes/list_alert_types.test.ts @@ -9,6 +9,9 @@ import { httpServiceMock } from 'src/core/server/mocks'; import { mockLicenseState } from '../lib/license_state.mock'; import { verifyApiAccess } from '../lib/license_api_access'; import { mockHandlerArguments } from './_mock_handler_arguments'; +import { alertsClientMock } from '../alerts_client.mock'; + +const alertsClient = alertsClientMock.create(); jest.mock('../lib/license_api_access.ts', () => ({ verifyApiAccess: jest.fn(), @@ -28,13 +31,6 @@ describe('listAlertTypesRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/list_alert_types"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-read", - ], - } - `); const listTypes = [ { @@ -47,12 +43,17 @@ describe('listAlertTypesRoute', () => { }, ], defaultActionGroupId: 'default', - actionVariables: [], + authorizedConsumers: {}, + actionVariables: { + context: [], + state: [], + }, producer: 'test', }, ]; + alertsClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); - const [context, req, res] = mockHandlerArguments({ listTypes }, {}, ['ok']); + const [context, req, res] = mockHandlerArguments({ alertsClient }, {}, ['ok']); expect(await handler(context, req, res)).toMatchInlineSnapshot(` Object { @@ -64,7 +65,11 @@ describe('listAlertTypesRoute', () => { "name": "Default", }, ], - "actionVariables": Array [], + "actionVariables": Object { + "context": Array [], + "state": Array [], + }, + "authorizedConsumers": Object {}, "defaultActionGroupId": "default", "id": "1", "name": "name", @@ -74,7 +79,7 @@ describe('listAlertTypesRoute', () => { } `); - expect(context.alerting!.listTypes).toHaveBeenCalledTimes(1); + expect(alertsClient.listAlertTypes).toHaveBeenCalledTimes(1); expect(res.ok).toHaveBeenCalledWith({ body: listTypes, @@ -90,19 +95,11 @@ describe('listAlertTypesRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/list_alert_types"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-read", - ], - } - `); const listTypes = [ { id: '1', name: 'name', - enabled: true, actionGroups: [ { id: 'default', @@ -110,13 +107,19 @@ describe('listAlertTypesRoute', () => { }, ], defaultActionGroupId: 'default', - actionVariables: [], - producer: 'alerting', + authorizedConsumers: {}, + actionVariables: { + context: [], + state: [], + }, + producer: 'alerts', }, ]; + alertsClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); + const [context, req, res] = mockHandlerArguments( - { listTypes }, + { alertsClient }, { params: { id: '1' }, }, @@ -141,13 +144,6 @@ describe('listAlertTypesRoute', () => { const [config, handler] = router.get.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/list_alert_types"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-read", - ], - } - `); const listTypes = [ { @@ -160,13 +156,19 @@ describe('listAlertTypesRoute', () => { }, ], defaultActionGroupId: 'default', - actionVariables: [], - producer: 'alerting', + authorizedConsumers: {}, + actionVariables: { + context: [], + state: [], + }, + producer: 'alerts', }, ]; + alertsClient.listAlertTypes.mockResolvedValueOnce(new Set(listTypes)); + const [context, req, res] = mockHandlerArguments( - { listTypes }, + { alertsClient }, { params: { id: '1' }, }, diff --git a/x-pack/plugins/alerts/server/routes/list_alert_types.ts b/x-pack/plugins/alerts/server/routes/list_alert_types.ts index 51a4558108e29..bf516120fbe93 100644 --- a/x-pack/plugins/alerts/server/routes/list_alert_types.ts +++ b/x-pack/plugins/alerts/server/routes/list_alert_types.ts @@ -20,9 +20,6 @@ export const listAlertTypesRoute = (router: IRouter, licenseState: LicenseState) { path: `${BASE_ALERT_API_PATH}/list_alert_types`, validate: {}, - options: { - tags: ['access:alerting-read'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, @@ -34,7 +31,7 @@ export const listAlertTypesRoute = (router: IRouter, licenseState: LicenseState) return res.badRequest({ body: 'RouteHandlerContext is not registered for alerting' }); } return res.ok({ - body: context.alerting.listTypes(), + body: Array.from(await context.alerting.getAlertsClient().listAlertTypes()), }); }) ); diff --git a/x-pack/plugins/alerts/server/routes/mute_all.test.ts b/x-pack/plugins/alerts/server/routes/mute_all.test.ts index bcdb8cbd022ac..efa3cdebad8ff 100644 --- a/x-pack/plugins/alerts/server/routes/mute_all.test.ts +++ b/x-pack/plugins/alerts/server/routes/mute_all.test.ts @@ -29,13 +29,6 @@ describe('muteAllAlertRoute', () => { const [config, handler] = router.post.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/_mute_all"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-all", - ], - } - `); alertsClient.muteAll.mockResolvedValueOnce(); diff --git a/x-pack/plugins/alerts/server/routes/mute_all.ts b/x-pack/plugins/alerts/server/routes/mute_all.ts index 5b05d7231c385..6735121d4edb0 100644 --- a/x-pack/plugins/alerts/server/routes/mute_all.ts +++ b/x-pack/plugins/alerts/server/routes/mute_all.ts @@ -27,9 +27,6 @@ export const muteAllAlertRoute = (router: IRouter, licenseState: LicenseState) = validate: { params: paramSchema, }, - options: { - tags: ['access:alerting-all'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/alerts/server/routes/mute_instance.test.ts b/x-pack/plugins/alerts/server/routes/mute_instance.test.ts index c382c12de21cd..6e700e4e3fd46 100644 --- a/x-pack/plugins/alerts/server/routes/mute_instance.test.ts +++ b/x-pack/plugins/alerts/server/routes/mute_instance.test.ts @@ -31,13 +31,6 @@ describe('muteAlertInstanceRoute', () => { expect(config.path).toMatchInlineSnapshot( `"/api/alerts/alert/{alert_id}/alert_instance/{alert_instance_id}/_mute"` ); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-all", - ], - } - `); alertsClient.muteInstance.mockResolvedValueOnce(); diff --git a/x-pack/plugins/alerts/server/routes/mute_instance.ts b/x-pack/plugins/alerts/server/routes/mute_instance.ts index 00550f4af3418..5e2ffc7d519ed 100644 --- a/x-pack/plugins/alerts/server/routes/mute_instance.ts +++ b/x-pack/plugins/alerts/server/routes/mute_instance.ts @@ -30,9 +30,6 @@ export const muteAlertInstanceRoute = (router: IRouter, licenseState: LicenseSta validate: { params: paramSchema, }, - options: { - tags: ['access:alerting-all'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/alerts/server/routes/unmute_all.test.ts b/x-pack/plugins/alerts/server/routes/unmute_all.test.ts index e13af38fe4cb1..81fdc5bb4dd76 100644 --- a/x-pack/plugins/alerts/server/routes/unmute_all.test.ts +++ b/x-pack/plugins/alerts/server/routes/unmute_all.test.ts @@ -28,13 +28,6 @@ describe('unmuteAllAlertRoute', () => { const [config, handler] = router.post.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/_unmute_all"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-all", - ], - } - `); alertsClient.unmuteAll.mockResolvedValueOnce(); diff --git a/x-pack/plugins/alerts/server/routes/unmute_all.ts b/x-pack/plugins/alerts/server/routes/unmute_all.ts index 1efc9ed40054e..a987380541696 100644 --- a/x-pack/plugins/alerts/server/routes/unmute_all.ts +++ b/x-pack/plugins/alerts/server/routes/unmute_all.ts @@ -27,9 +27,6 @@ export const unmuteAllAlertRoute = (router: IRouter, licenseState: LicenseState) validate: { params: paramSchema, }, - options: { - tags: ['access:alerting-all'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/alerts/server/routes/unmute_instance.test.ts b/x-pack/plugins/alerts/server/routes/unmute_instance.test.ts index b2e2f24e91de9..04e97dbe5e538 100644 --- a/x-pack/plugins/alerts/server/routes/unmute_instance.test.ts +++ b/x-pack/plugins/alerts/server/routes/unmute_instance.test.ts @@ -31,13 +31,6 @@ describe('unmuteAlertInstanceRoute', () => { expect(config.path).toMatchInlineSnapshot( `"/api/alerts/alert/{alertId}/alert_instance/{alertInstanceId}/_unmute"` ); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-all", - ], - } - `); alertsClient.unmuteInstance.mockResolvedValueOnce(); diff --git a/x-pack/plugins/alerts/server/routes/unmute_instance.ts b/x-pack/plugins/alerts/server/routes/unmute_instance.ts index 967f9f890c9fb..15b882e585804 100644 --- a/x-pack/plugins/alerts/server/routes/unmute_instance.ts +++ b/x-pack/plugins/alerts/server/routes/unmute_instance.ts @@ -28,9 +28,6 @@ export const unmuteAlertInstanceRoute = (router: IRouter, licenseState: LicenseS validate: { params: paramSchema, }, - options: { - tags: ['access:alerting-all'], - }, }, router.handleLegacyErrors(async function ( context: RequestHandlerContext, diff --git a/x-pack/plugins/alerts/server/routes/update.test.ts b/x-pack/plugins/alerts/server/routes/update.test.ts index c7d23f2670b45..dedb08a9972c2 100644 --- a/x-pack/plugins/alerts/server/routes/update.test.ts +++ b/x-pack/plugins/alerts/server/routes/update.test.ts @@ -52,13 +52,6 @@ describe('updateAlertRoute', () => { const [config, handler] = router.put.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-all", - ], - } - `); alertsClient.update.mockResolvedValueOnce(mockedResponse); diff --git a/x-pack/plugins/alerts/server/routes/update.ts b/x-pack/plugins/alerts/server/routes/update.ts index 99b81dfc5b56e..9b2fe9a43810b 100644 --- a/x-pack/plugins/alerts/server/routes/update.ts +++ b/x-pack/plugins/alerts/server/routes/update.ts @@ -49,9 +49,6 @@ export const updateAlertRoute = (router: IRouter, licenseState: LicenseState) => body: bodySchema, params: paramSchema, }, - options: { - tags: ['access:alerting-all'], - }, }, handleDisabledApiKeysError( router.handleLegacyErrors(async function ( diff --git a/x-pack/plugins/alerts/server/routes/update_api_key.test.ts b/x-pack/plugins/alerts/server/routes/update_api_key.test.ts index babae59553b5b..5aa91d215be90 100644 --- a/x-pack/plugins/alerts/server/routes/update_api_key.test.ts +++ b/x-pack/plugins/alerts/server/routes/update_api_key.test.ts @@ -29,13 +29,6 @@ describe('updateApiKeyRoute', () => { const [config, handler] = router.post.mock.calls[0]; expect(config.path).toMatchInlineSnapshot(`"/api/alerts/alert/{id}/_update_api_key"`); - expect(config.options).toMatchInlineSnapshot(` - Object { - "tags": Array [ - "access:alerting-all", - ], - } - `); alertsClient.updateApiKey.mockResolvedValueOnce(); diff --git a/x-pack/plugins/alerts/server/routes/update_api_key.ts b/x-pack/plugins/alerts/server/routes/update_api_key.ts index 4736351a25cbd..d44649b05b929 100644 --- a/x-pack/plugins/alerts/server/routes/update_api_key.ts +++ b/x-pack/plugins/alerts/server/routes/update_api_key.ts @@ -28,9 +28,6 @@ export const updateApiKeyRoute = (router: IRouter, licenseState: LicenseState) = validate: { params: paramSchema, }, - options: { - tags: ['access:alerting-all'], - }, }, handleDisabledApiKeysError( router.handleLegacyErrors(async function ( diff --git a/x-pack/plugins/alerts/server/saved_objects/index.ts b/x-pack/plugins/alerts/server/saved_objects/index.ts index 06ce8d673e6b7..c98d9bcbd9ae5 100644 --- a/x-pack/plugins/alerts/server/saved_objects/index.ts +++ b/x-pack/plugins/alerts/server/saved_objects/index.ts @@ -6,7 +6,6 @@ import { SavedObjectsServiceSetup } from 'kibana/server'; import mappings from './mappings.json'; -import { getMigrations } from './migrations'; import { EncryptedSavedObjectsPluginSetup } from '../../../encrypted_saved_objects/server'; export function setupSavedObjects( @@ -17,7 +16,6 @@ export function setupSavedObjects( name: 'alert', hidden: true, namespaceType: 'single', - migrations: getMigrations(encryptedSavedObjects), mappings: mappings.alert, }); diff --git a/x-pack/plugins/alerts/server/saved_objects/migrations.test.ts b/x-pack/plugins/alerts/server/saved_objects/migrations.test.ts deleted file mode 100644 index 38cda5a9a0f7c..0000000000000 --- a/x-pack/plugins/alerts/server/saved_objects/migrations.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import uuid from 'uuid'; -import { getMigrations } from './migrations'; -import { RawAlert } from '../types'; -import { SavedObjectUnsanitizedDoc } from 'kibana/server'; -import { encryptedSavedObjectsMock } from '../../../encrypted_saved_objects/server/mocks'; -import { migrationMocks } from 'src/core/server/mocks'; - -const { log } = migrationMocks.createContext(); -const encryptedSavedObjectsSetup = encryptedSavedObjectsMock.createSetup(); - -describe('7.9.0', () => { - beforeEach(() => { - jest.resetAllMocks(); - encryptedSavedObjectsSetup.createMigration.mockImplementation( - (shouldMigrateWhenPredicate, migration) => migration - ); - }); - - test('changes nothing on alerts by other plugins', () => { - const migration790 = getMigrations(encryptedSavedObjectsSetup)['7.9.0']; - const alert = getMockData({}); - expect(migration790(alert, { log })).toMatchObject(alert); - - expect(encryptedSavedObjectsSetup.createMigration).toHaveBeenCalledWith( - expect.any(Function), - expect.any(Function) - ); - }); - - test('migrates the consumer for alerting', () => { - const migration790 = getMigrations(encryptedSavedObjectsSetup)['7.9.0']; - const alert = getMockData({ - consumer: 'alerting', - }); - expect(migration790(alert, { log })).toMatchObject({ - ...alert, - attributes: { - ...alert.attributes, - consumer: 'alerts', - }, - }); - }); -}); - -function getMockData( - overwrites: Record = {} -): SavedObjectUnsanitizedDoc { - return { - attributes: { - enabled: true, - name: 'abc', - tags: ['foo'], - alertTypeId: '123', - consumer: 'bar', - apiKey: '', - apiKeyOwner: '', - schedule: { interval: '10s' }, - throttle: null, - params: { - bar: true, - }, - muteAll: false, - mutedInstanceIds: [], - createdBy: new Date().toISOString(), - updatedBy: new Date().toISOString(), - createdAt: new Date().toISOString(), - actions: [ - { - group: 'default', - actionRef: '1', - actionTypeId: '1', - params: { - foo: true, - }, - }, - ], - ...overwrites, - }, - id: uuid.v4(), - type: 'alert', - }; -} diff --git a/x-pack/plugins/alerts/server/saved_objects/migrations.ts b/x-pack/plugins/alerts/server/saved_objects/migrations.ts deleted file mode 100644 index 142102dd711c7..0000000000000 --- a/x-pack/plugins/alerts/server/saved_objects/migrations.ts +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { - SavedObjectMigrationMap, - SavedObjectUnsanitizedDoc, - SavedObjectMigrationFn, -} from '../../../../../src/core/server'; -import { RawAlert } from '../types'; -import { EncryptedSavedObjectsPluginSetup } from '../../../encrypted_saved_objects/server'; - -export function getMigrations( - encryptedSavedObjects: EncryptedSavedObjectsPluginSetup -): SavedObjectMigrationMap { - return { - '7.9.0': changeAlertingConsumer(encryptedSavedObjects), - }; -} - -/** - * In v7.9.0 we changed the Alerting plugin so it uses the `consumer` value of `alerts` - * prior to that we were using `alerting` and we need to keep these in sync - */ -function changeAlertingConsumer( - encryptedSavedObjects: EncryptedSavedObjectsPluginSetup -): SavedObjectMigrationFn { - const consumerMigration = new Map(); - consumerMigration.set('alerting', 'alerts'); - - return encryptedSavedObjects.createMigration( - function shouldBeMigrated(doc): doc is SavedObjectUnsanitizedDoc { - return consumerMigration.has(doc.attributes.consumer); - }, - (doc: SavedObjectUnsanitizedDoc): SavedObjectUnsanitizedDoc => { - const { - attributes: { consumer }, - } = doc; - return { - ...doc, - attributes: { - ...doc.attributes, - consumer: consumerMigration.get(consumer) ?? consumer, - }, - }; - } - ); -} diff --git a/x-pack/plugins/alerts/server/task_runner/create_execution_handler.test.ts b/x-pack/plugins/alerts/server/task_runner/create_execution_handler.test.ts index 3b1948c5e7ad7..677040d8174e3 100644 --- a/x-pack/plugins/alerts/server/task_runner/create_execution_handler.test.ts +++ b/x-pack/plugins/alerts/server/task_runner/create_execution_handler.test.ts @@ -20,7 +20,7 @@ const alertType: AlertType = { ], defaultActionGroupId: 'default', executor: jest.fn(), - producer: 'alerting', + producer: 'alerts', }; const actionsClient = actionsClientMock.create(); @@ -50,6 +50,11 @@ const createExecutionHandlerParams = { }, ], request: {} as KibanaRequest, + alertParams: { + foo: true, + contextVal: 'My other {{context.value}} goes here', + stateVal: 'My other {{state.value}} goes here', + }, }; beforeEach(() => { diff --git a/x-pack/plugins/alerts/server/task_runner/create_execution_handler.ts b/x-pack/plugins/alerts/server/task_runner/create_execution_handler.ts index e1e1568d2f13c..c21d81779e5e0 100644 --- a/x-pack/plugins/alerts/server/task_runner/create_execution_handler.ts +++ b/x-pack/plugins/alerts/server/task_runner/create_execution_handler.ts @@ -5,7 +5,7 @@ */ import { map } from 'lodash'; -import { AlertAction, State, Context, AlertType } from '../types'; +import { AlertAction, State, Context, AlertType, AlertParams } from '../types'; import { Logger, KibanaRequest } from '../../../../../src/core/server'; import { transformActionParams } from './transform_action_params'; import { PluginStartContract as ActionsPluginStartContract } from '../../../actions/server'; @@ -24,6 +24,7 @@ interface CreateExecutionHandlerOptions { logger: Logger; eventLogger: IEventLogger; request: KibanaRequest; + alertParams: AlertParams; } interface ExecutionHandlerOptions { @@ -45,6 +46,7 @@ export function createExecutionHandler({ alertType, eventLogger, request, + alertParams, }: CreateExecutionHandlerOptions) { const alertTypeActionGroups = new Set(map(alertType.actionGroups, 'id')); return async ({ actionGroup, context, state, alertInstanceId }: ExecutionHandlerOptions) => { @@ -66,6 +68,7 @@ export function createExecutionHandler({ context, actionParams: action.params, state, + alertParams, }), }; }); diff --git a/x-pack/plugins/alerts/server/task_runner/task_runner.test.ts b/x-pack/plugins/alerts/server/task_runner/task_runner.test.ts index 7a031c6671fd0..4abe58de5a904 100644 --- a/x-pack/plugins/alerts/server/task_runner/task_runner.test.ts +++ b/x-pack/plugins/alerts/server/task_runner/task_runner.test.ts @@ -14,7 +14,7 @@ import { encryptedSavedObjectsMock } from '../../../encrypted_saved_objects/serv import { loggingSystemMock } from '../../../../../src/core/server/mocks'; import { PluginStartContract as ActionsPluginStart } from '../../../actions/server'; import { actionsMock, actionsClientMock } from '../../../actions/server/mocks'; -import { alertsMock } from '../mocks'; +import { alertsMock, alertsClientMock } from '../mocks'; import { eventLoggerMock } from '../../../event_log/server/event_logger.mock'; import { IEventLogger } from '../../../event_log/server'; import { SavedObjectsErrorHelpers } from '../../../../../src/core/server'; @@ -25,7 +25,7 @@ const alertType = { actionGroups: [{ id: 'default', name: 'Default' }], defaultActionGroupId: 'default', executor: jest.fn(), - producer: 'alerting', + producer: 'alerts', }; let fakeTimer: sinon.SinonFakeTimers; @@ -56,8 +56,8 @@ describe('Task Runner', () => { const encryptedSavedObjectsClient = encryptedSavedObjectsMock.createClient(); const services = alertsMock.createAlertServices(); - const savedObjectsClient = services.savedObjectsClient; const actionsClient = actionsClientMock.create(); + const alertsClient = alertsClientMock.create(); const taskRunnerFactoryInitializerParams: jest.Mocked & { actionsPlugin: jest.Mocked; @@ -65,6 +65,7 @@ describe('Task Runner', () => { } = { getServices: jest.fn().mockReturnValue(services), actionsPlugin: actionsMock.createStart(), + getAlertsClientWithRequest: jest.fn().mockReturnValue(alertsClient), encryptedSavedObjectsClient, logger: loggingSystemMock.create().get(), spaceIdToNamespace: jest.fn().mockReturnValue(undefined), @@ -74,34 +75,31 @@ describe('Task Runner', () => { const mockedAlertTypeSavedObject = { id: '1', - type: 'alert', - attributes: { - enabled: true, - alertTypeId: '123', - schedule: { interval: '10s' }, - name: 'alert-name', - tags: ['alert-', '-tags'], - createdBy: 'alert-creator', - updatedBy: 'alert-updater', - mutedInstanceIds: [], - params: { - bar: true, - }, - actions: [ - { - group: 'default', - actionRef: 'action_0', - params: { - foo: true, - }, - }, - ], + consumer: 'bar', + createdAt: new Date('2019-02-12T21:01:22.479Z'), + updatedAt: new Date('2019-02-12T21:01:22.479Z'), + throttle: null, + muteAll: false, + enabled: true, + alertTypeId: '123', + apiKeyOwner: 'elastic', + schedule: { interval: '10s' }, + name: 'alert-name', + tags: ['alert-', '-tags'], + createdBy: 'alert-creator', + updatedBy: 'alert-updater', + mutedInstanceIds: [], + params: { + bar: true, }, - references: [ + actions: [ { - name: 'action_0', - type: 'action', + group: 'default', id: '1', + actionTypeId: 'action', + params: { + foo: true, + }, }, ], }; @@ -109,6 +107,7 @@ describe('Task Runner', () => { beforeEach(() => { jest.resetAllMocks(); taskRunnerFactoryInitializerParams.getServices.mockReturnValue(services); + taskRunnerFactoryInitializerParams.getAlertsClientWithRequest.mockReturnValue(alertsClient); taskRunnerFactoryInitializerParams.actionsPlugin.getActionsClientWithRequest.mockResolvedValue( actionsClient ); @@ -126,7 +125,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - savedObjectsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); + alertsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -200,7 +199,7 @@ describe('Task Runner', () => { mockedTaskInstance, taskRunnerFactoryInitializerParams ); - savedObjectsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); + alertsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -285,7 +284,7 @@ describe('Task Runner', () => { ], }, message: - "alert: test:1: 'alert-name' instanceId: '1' scheduled actionGroup: 'default' action: undefined:1", + "alert: test:1: 'alert-name' instanceId: '1' scheduled actionGroup: 'default' action: action:1", }); }); @@ -302,7 +301,7 @@ describe('Task Runner', () => { mockedTaskInstance, taskRunnerFactoryInitializerParams ); - savedObjectsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); + alertsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -412,7 +411,7 @@ describe('Task Runner', () => { }, ], }, - "message": "alert: test:1: 'alert-name' instanceId: '1' scheduled actionGroup: 'default' action: undefined:1", + "message": "alert: test:1: 'alert-name' instanceId: '1' scheduled actionGroup: 'default' action: action:1", }, ], ] @@ -439,7 +438,7 @@ describe('Task Runner', () => { }, taskRunnerFactoryInitializerParams ); - savedObjectsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); + alertsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -526,7 +525,7 @@ describe('Task Runner', () => { mockedTaskInstance, taskRunnerFactoryInitializerParams ); - savedObjectsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); + alertsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -548,44 +547,13 @@ describe('Task Runner', () => { ); }); - test('throws error if reference not found', async () => { - const taskRunner = new TaskRunner( - alertType, - mockedTaskInstance, - taskRunnerFactoryInitializerParams - ); - savedObjectsClient.get.mockResolvedValueOnce({ - ...mockedAlertTypeSavedObject, - references: [], - }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ - id: '1', - type: 'alert', - attributes: { - apiKey: Buffer.from('123:abc').toString('base64'), - }, - references: [], - }); - expect(await taskRunner.run()).toMatchInlineSnapshot(` - Object { - "runAt": 1970-01-01T00:00:10.000Z, - "state": Object { - "previousStartedAt": 1970-01-01T00:00:00.000Z, - }, - } - `); - expect(taskRunnerFactoryInitializerParams.logger.error).toHaveBeenCalledWith( - `Executing Alert \"1\" has resulted in Error: Action reference \"action_0\" not found in alert id: 1` - ); - }); - test('uses API key when provided', async () => { const taskRunner = new TaskRunner( alertType, mockedTaskInstance, taskRunnerFactoryInitializerParams ); - savedObjectsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); + alertsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -621,7 +589,7 @@ describe('Task Runner', () => { mockedTaskInstance, taskRunnerFactoryInitializerParams ); - savedObjectsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); + alertsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -660,7 +628,7 @@ describe('Task Runner', () => { taskRunnerFactoryInitializerParams ); - savedObjectsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); + alertsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -722,7 +690,7 @@ describe('Task Runner', () => { taskRunnerFactoryInitializerParams ); - savedObjectsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); + alertsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); const runnerResult = await taskRunner.run(); @@ -747,7 +715,7 @@ describe('Task Runner', () => { taskRunnerFactoryInitializerParams ); - savedObjectsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); + alertsClient.get.mockResolvedValueOnce(mockedAlertTypeSavedObject); encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ id: '1', type: 'alert', @@ -770,7 +738,7 @@ describe('Task Runner', () => { }); test('recovers gracefully when the Alert Task Runner throws an exception when fetching attributes', async () => { - savedObjectsClient.get.mockImplementation(() => { + alertsClient.get.mockImplementation(() => { throw new Error('OMG'); }); @@ -802,7 +770,7 @@ describe('Task Runner', () => { }); test('avoids rescheduling a failed Alert Task Runner when it throws due to failing to fetch the alert', async () => { - savedObjectsClient.get.mockImplementation(() => { + alertsClient.get.mockImplementation(() => { throw SavedObjectsErrorHelpers.createGenericNotFoundError('task', '1'); }); diff --git a/x-pack/plugins/alerts/server/task_runner/task_runner.ts b/x-pack/plugins/alerts/server/task_runner/task_runner.ts index 3c66b57bb9416..04fea58f250a3 100644 --- a/x-pack/plugins/alerts/server/task_runner/task_runner.ts +++ b/x-pack/plugins/alerts/server/task_runner/task_runner.ts @@ -5,7 +5,7 @@ */ import { pickBy, mapValues, omit, without } from 'lodash'; -import { Logger, SavedObject, KibanaRequest } from '../../../../../src/core/server'; +import { Logger, KibanaRequest } from '../../../../../src/core/server'; import { TaskRunnerContext } from './task_runner_factory'; import { ConcreteTaskInstance } from '../../../task_manager/server'; import { createExecutionHandler } from './create_execution_handler'; @@ -17,15 +17,18 @@ import { RawAlert, IntervalSchedule, Services, - AlertInfoParams, - AlertTaskState, RawAlertInstance, + AlertTaskState, + Alert, + AlertExecutorOptions, + SanitizedAlert, } from '../types'; import { promiseResult, map, Resultable, asOk, asErr, resolveErr } from '../lib/result_type'; import { taskInstanceToAlertTaskInstance } from './alert_task_instance'; import { EVENT_LOG_ACTIONS } from '../plugin'; import { IEvent, IEventLogger, SAVED_OBJECT_REL_PRIMARY } from '../../../event_log/server'; import { isAlertSavedObjectNotFoundError } from '../lib/is_alert_not_found_error'; +import { AlertsClient } from '../alerts_client'; const FALLBACK_RETRY_INTERVAL: IntervalSchedule = { interval: '5m' }; @@ -93,8 +96,12 @@ export class TaskRunner { } as unknown) as KibanaRequest; } - async getServicesWithSpaceLevelPermissions(spaceId: string, apiKey: string | null) { - return this.context.getServices(this.getFakeKibanaRequest(spaceId, apiKey)); + private getServicesWithSpaceLevelPermissions( + spaceId: string, + apiKey: string | null + ): [Services, PublicMethodsOf] { + const request = this.getFakeKibanaRequest(spaceId, apiKey); + return [this.context.getServices(request), this.context.getAlertsClientWithRequest(request)]; } private getExecutionHandler( @@ -103,21 +110,9 @@ export class TaskRunner { tags: string[] | undefined, spaceId: string, apiKey: string | null, - actions: RawAlert['actions'], - references: SavedObject['references'] + actions: Alert['actions'], + alertParams: RawAlert['params'] ) { - // Inject ids into actions - const actionsWithIds = actions.map((action) => { - const actionReference = references.find((obj) => obj.name === action.actionRef); - if (!actionReference) { - throw new Error(`Action reference "${action.actionRef}" not found in alert id: ${alertId}`); - } - return { - ...action, - id: actionReference.id, - }; - }); - return createExecutionHandler({ alertId, alertName, @@ -125,11 +120,12 @@ export class TaskRunner { logger: this.logger, actionsPlugin: this.context.actionsPlugin, apiKey, - actions: actionsWithIds, + actions, spaceId, alertType: this.alertType, eventLogger: this.context.eventLogger, request: this.getFakeKibanaRequest(spaceId, apiKey), + alertParams, }); } @@ -146,20 +142,12 @@ export class TaskRunner { async executeAlertInstances( services: Services, - alertInfoParams: AlertInfoParams, + alert: SanitizedAlert, + params: AlertExecutorOptions['params'], executionHandler: ReturnType, spaceId: string ): Promise { - const { - params, - throttle, - muteAll, - mutedInstanceIds, - name, - tags, - createdBy, - updatedBy, - } = alertInfoParams; + const { throttle, muteAll, mutedInstanceIds, name, tags, createdBy, updatedBy } = alert; const { params: { alertId }, state: { alertInstances: alertRawInstances = {}, alertTypeState = {}, previousStartedAt }, @@ -262,33 +250,23 @@ export class TaskRunner { }; } - async validateAndExecuteAlert( - services: Services, - apiKey: string | null, - attributes: RawAlert, - references: SavedObject['references'] - ) { + async validateAndExecuteAlert(services: Services, apiKey: string | null, alert: SanitizedAlert) { const { params: { alertId, spaceId }, } = this.taskInstance; // Validate - const params = validateAlertTypeParams(this.alertType, attributes.params); + const validatedParams = validateAlertTypeParams(this.alertType, alert.params); const executionHandler = this.getExecutionHandler( alertId, - attributes.name, - attributes.tags, + alert.name, + alert.tags, spaceId, apiKey, - attributes.actions, - references - ); - return this.executeAlertInstances( - services, - { ...attributes, params }, - executionHandler, - spaceId + alert.actions, + alert.params ); + return this.executeAlertInstances(services, alert, validatedParams, executionHandler, spaceId); } async loadAlertAttributesAndRun(): Promise> { @@ -297,17 +275,17 @@ export class TaskRunner { } = this.taskInstance; const apiKey = await this.getApiKeyForAlertPermissions(alertId, spaceId); - const services = await this.getServicesWithSpaceLevelPermissions(spaceId, apiKey); + const [services, alertsClient] = await this.getServicesWithSpaceLevelPermissions( + spaceId, + apiKey + ); // Ensure API key is still valid and user has access - const { attributes, references } = await services.savedObjectsClient.get( - 'alert', - alertId - ); + const alert = await alertsClient.get({ id: alertId }); return { state: await promiseResult( - this.validateAndExecuteAlert(services, apiKey, attributes, references) + this.validateAndExecuteAlert(services, apiKey, alert) ), runAt: asOk( getNextRunAt( @@ -315,7 +293,7 @@ export class TaskRunner { // we do not currently have a good way of returning the type // from SavedObjectsClient, and as we currenrtly require a schedule // and we only support `interval`, we can cast this safely - attributes.schedule as IntervalSchedule + alert.schedule ) ), }; diff --git a/x-pack/plugins/alerts/server/task_runner/task_runner_factory.test.ts b/x-pack/plugins/alerts/server/task_runner/task_runner_factory.test.ts index 8f3e44b1cf42d..9af7d9ddc44eb 100644 --- a/x-pack/plugins/alerts/server/task_runner/task_runner_factory.test.ts +++ b/x-pack/plugins/alerts/server/task_runner/task_runner_factory.test.ts @@ -10,7 +10,7 @@ import { TaskRunnerContext, TaskRunnerFactory } from './task_runner_factory'; import { encryptedSavedObjectsMock } from '../../../encrypted_saved_objects/server/mocks'; import { loggingSystemMock } from '../../../../../src/core/server/mocks'; import { actionsMock } from '../../../actions/server/mocks'; -import { alertsMock } from '../mocks'; +import { alertsMock, alertsClientMock } from '../mocks'; import { eventLoggerMock } from '../../../event_log/server/event_logger.mock'; const alertType = { @@ -19,7 +19,7 @@ const alertType = { actionGroups: [{ id: 'default', name: 'Default' }], defaultActionGroupId: 'default', executor: jest.fn(), - producer: 'alerting', + producer: 'alerts', }; let fakeTimer: sinon.SinonFakeTimers; @@ -52,9 +52,11 @@ describe('Task Runner Factory', () => { const encryptedSavedObjectsPlugin = encryptedSavedObjectsMock.createStart(); const services = alertsMock.createAlertServices(); + const alertsClient = alertsClientMock.create(); const taskRunnerFactoryInitializerParams: jest.Mocked = { getServices: jest.fn().mockReturnValue(services), + getAlertsClientWithRequest: jest.fn().mockReturnValue(alertsClient), actionsPlugin: actionsMock.createStart(), encryptedSavedObjectsClient: encryptedSavedObjectsPlugin.getClient(), logger: loggingSystemMock.create().get(), diff --git a/x-pack/plugins/alerts/server/task_runner/task_runner_factory.ts b/x-pack/plugins/alerts/server/task_runner/task_runner_factory.ts index ca762cf2b2105..6f83e34cdbe03 100644 --- a/x-pack/plugins/alerts/server/task_runner/task_runner_factory.ts +++ b/x-pack/plugins/alerts/server/task_runner/task_runner_factory.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { Logger } from '../../../../../src/core/server'; +import { Logger, KibanaRequest } from '../../../../../src/core/server'; import { RunContext } from '../../../task_manager/server'; import { EncryptedSavedObjectsClient } from '../../../encrypted_saved_objects/server'; import { PluginStartContract as ActionsPluginStartContract } from '../../../actions/server'; @@ -15,10 +15,12 @@ import { } from '../types'; import { TaskRunner } from './task_runner'; import { IEventLogger } from '../../../event_log/server'; +import { AlertsClient } from '../alerts_client'; export interface TaskRunnerContext { logger: Logger; getServices: GetServicesFunction; + getAlertsClientWithRequest(request: KibanaRequest): PublicMethodsOf; actionsPlugin: ActionsPluginStartContract; eventLogger: IEventLogger; encryptedSavedObjectsClient: EncryptedSavedObjectsClient; diff --git a/x-pack/plugins/alerts/server/task_runner/transform_action_params.test.ts b/x-pack/plugins/alerts/server/task_runner/transform_action_params.test.ts index d5c310caf3fda..ddbef8e32e708 100644 --- a/x-pack/plugins/alerts/server/task_runner/transform_action_params.test.ts +++ b/x-pack/plugins/alerts/server/task_runner/transform_action_params.test.ts @@ -13,6 +13,7 @@ test('skips non string parameters', () => { empty1: null, empty2: undefined, date: '2019-02-12T21:01:22.479Z', + message: 'Value "{{params.foo}}" exists', }; const result = transformActionParams({ actionParams, @@ -23,6 +24,9 @@ test('skips non string parameters', () => { tags: ['tag-A', 'tag-B'], spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: { + foo: 'test', + }, }); expect(result).toMatchInlineSnapshot(` Object { @@ -30,6 +34,7 @@ test('skips non string parameters', () => { "date": "2019-02-12T21:01:22.479Z", "empty1": null, "empty2": undefined, + "message": "Value \\"test\\" exists", "number": 1, } `); @@ -49,6 +54,7 @@ test('missing parameters get emptied out', () => { tags: ['tag-A', 'tag-B'], spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { @@ -71,6 +77,7 @@ test('context parameters are passed to templates', () => { tags: ['tag-A', 'tag-B'], spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { @@ -92,6 +99,7 @@ test('state parameters are passed to templates', () => { tags: ['tag-A', 'tag-B'], spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { @@ -113,6 +121,7 @@ test('alertId is passed to templates', () => { tags: ['tag-A', 'tag-B'], spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { @@ -134,6 +143,7 @@ test('alertName is passed to templates', () => { tags: ['tag-A', 'tag-B'], spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { @@ -155,6 +165,7 @@ test('tags is passed to templates', () => { tags: ['tag-A', 'tag-B'], spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { @@ -175,6 +186,7 @@ test('undefined tags is passed to templates', () => { alertName: 'alert-name', spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { @@ -196,6 +208,7 @@ test('empty tags is passed to templates', () => { tags: [], spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { @@ -217,6 +230,7 @@ test('spaceId is passed to templates', () => { tags: ['tag-A', 'tag-B'], spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { @@ -238,6 +252,7 @@ test('alertInstanceId is passed to templates', () => { tags: ['tag-A', 'tag-B'], spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { @@ -261,6 +276,7 @@ test('works recursively', () => { tags: ['tag-A', 'tag-B'], spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { @@ -286,6 +302,7 @@ test('works recursively with arrays', () => { tags: ['tag-A', 'tag-B'], spaceId: 'spaceId-A', alertInstanceId: '2', + alertParams: {}, }); expect(result).toMatchInlineSnapshot(` Object { diff --git a/x-pack/plugins/alerts/server/task_runner/transform_action_params.ts b/x-pack/plugins/alerts/server/task_runner/transform_action_params.ts index fa4a0e40ddee5..30f062eee3705 100644 --- a/x-pack/plugins/alerts/server/task_runner/transform_action_params.ts +++ b/x-pack/plugins/alerts/server/task_runner/transform_action_params.ts @@ -6,7 +6,7 @@ import Mustache from 'mustache'; import { isString, cloneDeepWith } from 'lodash'; -import { AlertActionParams, State, Context } from '../types'; +import { AlertActionParams, State, Context, AlertParams } from '../types'; interface TransformActionParamsOptions { alertId: string; @@ -17,6 +17,7 @@ interface TransformActionParamsOptions { actionParams: AlertActionParams; state: State; context: Context; + alertParams: AlertParams; } export function transformActionParams({ @@ -28,6 +29,7 @@ export function transformActionParams({ context, actionParams, state, + alertParams, }: TransformActionParamsOptions): AlertActionParams { const result = cloneDeepWith(actionParams, (value: unknown) => { if (!isString(value)) return; @@ -43,6 +45,7 @@ export function transformActionParams({ alertInstanceId, context, state, + params: alertParams, }; return Mustache.render(value, variables); }); diff --git a/x-pack/plugins/alerts/server/types.ts b/x-pack/plugins/alerts/server/types.ts index 66eec370f2c20..154a9564518e8 100644 --- a/x-pack/plugins/alerts/server/types.ts +++ b/x-pack/plugins/alerts/server/types.ts @@ -23,6 +23,8 @@ import { export type State = Record; // eslint-disable-next-line @typescript-eslint/no-explicit-any export type Context = Record; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type AlertParams = Record; export type WithoutQueryAndParams = Pick>; export type GetServicesFunction = (request: KibanaRequest) => Services; export type GetBasePathFunction = (spaceId?: string) => string; @@ -82,6 +84,7 @@ export interface AlertType { actionVariables?: { context?: ActionVariable[]; state?: ActionVariable[]; + params?: ActionVariable[]; }; } diff --git a/x-pack/plugins/apm/e2e/cypress/plugins/index.js b/x-pack/plugins/apm/e2e/cypress/plugins/index.js index 540b887d55df5..c5529c747adcd 100644 --- a/x-pack/plugins/apm/e2e/cypress/plugins/index.js +++ b/x-pack/plugins/apm/e2e/cypress/plugins/index.js @@ -29,6 +29,8 @@ module.exports = (on) => { // readFileMaybe on('task', { + // ESLint thinks this is a react component for some reason. + // eslint-disable-next-line react/function-component-definition readFileMaybe(filename) { if (fs.existsSync(filename)) { return fs.readFileSync(filename, 'utf8'); diff --git a/x-pack/plugins/apm/public/application/index.tsx b/x-pack/plugins/apm/public/application/index.tsx index c39afe6da215e..0c9c6eb86225b 100644 --- a/x-pack/plugins/apm/public/application/index.tsx +++ b/x-pack/plugins/apm/public/application/index.tsx @@ -37,7 +37,7 @@ const MainContainer = styled.div` height: 100%; `; -const App = () => { +function App() { const [darkMode] = useUiSetting$('theme:darkMode'); return ( @@ -59,9 +59,9 @@ const App = () => { ); -}; +} -const ApmAppRoot = ({ +function ApmAppRoot({ core, deps, routerHistory, @@ -71,7 +71,7 @@ const ApmAppRoot = ({ deps: ApmPluginSetupDeps; routerHistory: typeof history; config: ConfigSchema; -}) => { +}) { const i18nCore = core.i18n; const plugins = deps; const apmPluginContextValue = { @@ -111,7 +111,7 @@ const ApmAppRoot = ({ ); -}; +} /** * This module is rendered asynchronously in the Kibana platform. diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/index.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/index.tsx index 1096c0c77db30..5c16bf0f324be 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/index.tsx @@ -53,7 +53,7 @@ interface Props { items: ErrorGroupListAPIResponse; } -const ErrorGroupList: React.FC = (props) => { +function ErrorGroupList(props: Props) { const { items } = props; const { urlParams } = useUrlParams(); const { serviceName } = urlParams; @@ -213,6 +213,6 @@ const ErrorGroupList: React.FC = (props) => { sortItems={false} /> ); -}; +} export { ErrorGroupList }; diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/index.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/index.tsx index b9a28c1c1841f..fe2303d645ec9 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/index.tsx @@ -22,7 +22,7 @@ import { LocalUIFilters } from '../../shared/LocalUIFilters'; import { ErrorDistribution } from '../ErrorGroupDetails/Distribution'; import { ErrorGroupList } from './List'; -const ErrorGroupOverview: React.FC = () => { +function ErrorGroupOverview() { const { urlParams, uiFilters } = useUrlParams(); const { serviceName, start, end, sortField, sortDirection } = urlParams; @@ -123,6 +123,6 @@ const ErrorGroupOverview: React.FC = () => {
); -}; +} export { ErrorGroupOverview }; diff --git a/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.test.tsx b/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.test.tsx index 6aec6e9bf181a..2c19356a7fd52 100644 --- a/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.test.tsx +++ b/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.test.tsx @@ -16,6 +16,7 @@ import { } from '../../../context/ApmPluginContext/MockApmPluginContext'; const setBreadcrumbs = jest.fn(); +const changeTitle = jest.fn(); function mountBreadcrumb(route: string, params = '') { mount( @@ -27,6 +28,7 @@ function mountBreadcrumb(route: string, params = '') { ...mockApmPluginContextValue.core, chrome: { ...mockApmPluginContextValue.core.chrome, + docTitle: { change: changeTitle }, setBreadcrumbs, }, }, @@ -42,23 +44,14 @@ function mountBreadcrumb(route: string, params = '') { } describe('UpdateBreadcrumbs', () => { - let realDoc: Document; - beforeEach(() => { - realDoc = window.document; - (window.document as any) = { - title: 'Kibana', - }; setBreadcrumbs.mockReset(); + changeTitle.mockReset(); }); - afterEach(() => { - (window.document as any) = realDoc; - }); - - it('Homepage', () => { + it('Changes the homepage title', () => { mountBreadcrumb('/'); - expect(window.document.title).toMatchInlineSnapshot(`"APM"`); + expect(changeTitle).toHaveBeenCalledWith(['APM']); }); it('/services/:serviceName/errors/:groupId', () => { @@ -90,9 +83,13 @@ describe('UpdateBreadcrumbs', () => { }, { text: 'myGroupId', href: undefined }, ]); - expect(window.document.title).toMatchInlineSnapshot( - `"myGroupId | Errors | opbeans-node | Services | APM"` - ); + expect(changeTitle).toHaveBeenCalledWith([ + 'myGroupId', + 'Errors', + 'opbeans-node', + 'Services', + 'APM', + ]); }); it('/services/:serviceName/errors', () => { @@ -104,9 +101,12 @@ describe('UpdateBreadcrumbs', () => { { text: 'opbeans-node', href: '#/services/opbeans-node?kuery=myKuery' }, { text: 'Errors', href: undefined }, ]); - expect(window.document.title).toMatchInlineSnapshot( - `"Errors | opbeans-node | Services | APM"` - ); + expect(changeTitle).toHaveBeenCalledWith([ + 'Errors', + 'opbeans-node', + 'Services', + 'APM', + ]); }); it('/services/:serviceName/transactions', () => { @@ -118,9 +118,12 @@ describe('UpdateBreadcrumbs', () => { { text: 'opbeans-node', href: '#/services/opbeans-node?kuery=myKuery' }, { text: 'Transactions', href: undefined }, ]); - expect(window.document.title).toMatchInlineSnapshot( - `"Transactions | opbeans-node | Services | APM"` - ); + expect(changeTitle).toHaveBeenCalledWith([ + 'Transactions', + 'opbeans-node', + 'Services', + 'APM', + ]); }); it('/services/:serviceName/transactions/view?transactionName=my-transaction-name', () => { @@ -139,8 +142,12 @@ describe('UpdateBreadcrumbs', () => { }, { text: 'my-transaction-name', href: undefined }, ]); - expect(window.document.title).toMatchInlineSnapshot( - `"my-transaction-name | Transactions | opbeans-node | Services | APM"` - ); + expect(changeTitle).toHaveBeenCalledWith([ + 'my-transaction-name', + 'Transactions', + 'opbeans-node', + 'Services', + 'APM', + ]); }); }); diff --git a/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.tsx b/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.tsx index 7a27eae6e89f7..e7657c63f41bb 100644 --- a/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.tsx +++ b/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.tsx @@ -22,10 +22,7 @@ interface Props { } function getTitleFromBreadCrumbs(breadcrumbs: Breadcrumb[]) { - return breadcrumbs - .map(({ value }) => value) - .reverse() - .join(' | '); + return breadcrumbs.map(({ value }) => value).reverse(); } class UpdateBreadcrumbsComponent extends React.Component { @@ -43,7 +40,9 @@ class UpdateBreadcrumbsComponent extends React.Component { } ); - document.title = getTitleFromBreadCrumbs(this.props.breadcrumbs); + this.props.core.chrome.docTitle.change( + getTitleFromBreadCrumbs(this.props.breadcrumbs) + ); this.props.core.chrome.setBreadcrumbs(breadcrumbs); } diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/Breakdowns/BreakdownFilter.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/Breakdowns/BreakdownFilter.tsx index 332cf40a465f9..7e5e7cdc53c55 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/Breakdowns/BreakdownFilter.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/Breakdowns/BreakdownFilter.tsx @@ -20,11 +20,11 @@ interface Props { onBreakdownChange: (values: BreakdownItem[]) => void; } -export const BreakdownFilter = ({ +export function BreakdownFilter({ id, selectedBreakdowns, onBreakdownChange, -}: Props) => { +}: Props) { const categories: BreakdownItem[] = [ { name: 'Browser', @@ -65,4 +65,4 @@ export const BreakdownFilter = ({ }} /> ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/Breakdowns/BreakdownGroup.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/Breakdowns/BreakdownGroup.tsx index 5bf84b6c918c5..d4f80667ce98b 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/Breakdowns/BreakdownGroup.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/Breakdowns/BreakdownGroup.tsx @@ -22,12 +22,12 @@ export interface BreakdownGroupProps { onChange: (values: BreakdownItem[]) => void; } -export const BreakdownGroup = ({ +export function BreakdownGroup({ id, disabled, onChange, items, -}: BreakdownGroupProps) => { +}: BreakdownGroupProps) { const [isOpen, setIsOpen] = useState(false); const [activeItems, setActiveItems] = useState(items); @@ -97,4 +97,4 @@ export const BreakdownGroup = ({ ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/ChartWrapper/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/ChartWrapper/index.tsx index a3cfbb28abee2..970365779a0a2 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/ChartWrapper/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/ChartWrapper/index.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { FC, HTMLAttributes } from 'react'; +import React, { HTMLAttributes, ReactNode } from 'react'; import { EuiErrorBoundary, EuiFlexGroup, @@ -13,6 +13,7 @@ import { } from '@elastic/eui'; interface Props { + children?: ReactNode; /** * Height for the chart */ @@ -27,12 +28,12 @@ interface Props { 'aria-label'?: string; } -export const ChartWrapper: FC = ({ +export function ChartWrapper({ loading = false, height = '100%', children, ...rest -}) => { +}: Props) { const opacity = loading === true ? 0.3 : 1; return ( @@ -60,4 +61,4 @@ export const ChartWrapper: FC = ({ )} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/PageLoadDistChart.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/PageLoadDistChart.tsx index 6c5b539fcecfa..b2b5e66d06ac6 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/PageLoadDistChart.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/PageLoadDistChart.tsx @@ -70,6 +70,7 @@ export function PageLoadDistChart({ onPercentileChange(minX, maxX); }; + // eslint-disable-next-line react/function-component-definition const headerFormatter: TooltipValueFormatter = (tooltip: TooltipValue) => { return (
diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/VisitorBreakdownChart.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/VisitorBreakdownChart.tsx index 1e28fde4aa2b4..9f9ffdf7168b8 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/VisitorBreakdownChart.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/VisitorBreakdownChart.tsx @@ -29,7 +29,7 @@ interface Props { }>; } -export const VisitorBreakdownChart = ({ options }: Props) => { +export function VisitorBreakdownChart({ options }: Props) { const [darkMode] = useUiSetting$('theme:darkMode'); return ( @@ -93,4 +93,4 @@ export const VisitorBreakdownChart = ({ options }: Props) => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/BreakdownSeries.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/BreakdownSeries.tsx index 0c47ad24128ef..475a235ef5eed 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/BreakdownSeries.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/BreakdownSeries.tsx @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { FC, useEffect } from 'react'; import { CurveType, LineSeries, ScaleType } from '@elastic/charts'; +import React, { useEffect } from 'react'; import { PercentileRange } from './index'; import { useBreakdowns } from './use_breakdowns'; @@ -16,12 +16,12 @@ interface Props { onLoadingChange: (loading: boolean) => void; } -export const BreakdownSeries: FC = ({ +export function BreakdownSeries({ field, value, percentileRange, onLoadingChange, -}) => { +}: Props) { const { data, status } = useBreakdowns({ field, value, @@ -47,4 +47,4 @@ export const BreakdownSeries: FC = ({ ))} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/PercentileAnnotations.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/PercentileAnnotations.tsx index 9066dd73159b1..407ec42f03ff5 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/PercentileAnnotations.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/PercentileAnnotations.tsx @@ -33,7 +33,7 @@ const PercentileMarker = styled.span` bottom: 205px; `; -export const PercentileAnnotations = ({ percentiles }: Props) => { +export function PercentileAnnotations({ percentiles }: Props) { const dataValues = generateAnnotationData(percentiles) ?? []; const style: Partial = { @@ -44,17 +44,17 @@ export const PercentileAnnotations = ({ percentiles }: Props) => { }, }; - const PercentileTooltip = ({ + function PercentileTooltip({ annotation, }: { annotation: LineAnnotationDatum; - }) => { + }) { return ( {annotation.details}th Percentile ); - }; + } return ( <> @@ -82,4 +82,4 @@ export const PercentileAnnotations = ({ percentiles }: Props) => { ))} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/index.tsx index adeff2b31fd93..c7545ff9a2764 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/index.tsx @@ -24,7 +24,7 @@ export interface PercentileRange { max?: number | null; } -export const PageLoadDistribution = () => { +export function PageLoadDistribution() { const { urlParams, uiFilters } = useUrlParams(); const { start, end, serviceName } = urlParams; @@ -115,4 +115,4 @@ export const PageLoadDistribution = () => { />
); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/PageViewsTrend/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/PageViewsTrend/index.tsx index c6ef319f8a666..0f43c0ddf540d 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/PageViewsTrend/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/PageViewsTrend/index.tsx @@ -13,7 +13,7 @@ import { BreakdownFilter } from '../Breakdowns/BreakdownFilter'; import { PageViewsChart } from '../Charts/PageViewsChart'; import { BreakdownItem } from '../../../../../typings/ui_filters'; -export const PageViewsTrend = () => { +export function PageViewsTrend() { const { urlParams, uiFilters } = useUrlParams(); const { start, end, serviceName } = urlParams; @@ -68,4 +68,4 @@ export const PageViewsTrend = () => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/RumDashboard.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/RumDashboard.tsx index 2eb79257334d7..8c8164972328f 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/RumDashboard.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/RumDashboard.tsx @@ -18,7 +18,7 @@ import { PageLoadDistribution } from './PageLoadDistribution'; import { I18LABELS } from './translations'; import { VisitorBreakdown } from './VisitorBreakdown'; -export const RumDashboard = () => { +export function RumDashboard() { return ( @@ -54,4 +54,4 @@ export const RumDashboard = () => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/RumHeader/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/RumHeader/index.tsx index b1ff38fdd2d79..6b3fcb3b03466 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/RumHeader/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/RumHeader/index.tsx @@ -5,16 +5,18 @@ */ import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import React from 'react'; +import React, { ReactNode } from 'react'; import { DatePicker } from '../../../shared/DatePicker'; -export const RumHeader: React.FC = ({ children }) => ( - <> - - {children} - - - - - -); +export function RumHeader({ children }: { children: ReactNode }) { + return ( + <> + + {children} + + + + + + ); +} diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdown/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdown/index.tsx index 2e17e27587b63..5c68ebb1667ab 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdown/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdown/index.tsx @@ -11,7 +11,7 @@ import { VisitorBreakdownLabel } from '../translations'; import { useFetcher } from '../../../../hooks/useFetcher'; import { useUrlParams } from '../../../../hooks/useUrlParams'; -export const VisitorBreakdown = () => { +export function VisitorBreakdown() { const { urlParams, uiFilters } = useUrlParams(); const { start, end, serviceName } = urlParams; @@ -62,4 +62,4 @@ export const VisitorBreakdown = () => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/EmptyBanner.test.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/EmptyBanner.test.tsx index b330129f83785..f314fbbb1fba0 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/EmptyBanner.test.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/EmptyBanner.test.tsx @@ -4,32 +4,38 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { FunctionComponent } from 'react'; import { act, wait } from '@testing-library/react'; import cytoscape from 'cytoscape'; -import { CytoscapeContext } from './Cytoscape'; -import { EmptyBanner } from './EmptyBanner'; +import React, { ReactNode } from 'react'; import { MockApmPluginContextWrapper } from '../../../context/ApmPluginContext/MockApmPluginContext'; import { renderWithTheme } from '../../../utils/testHelpers'; +import { CytoscapeContext } from './Cytoscape'; +import { EmptyBanner } from './EmptyBanner'; const cy = cytoscape({}); -const wrapper: FunctionComponent = ({ children }) => ( - - {children} - -); +function wrapper({ children }: { children: ReactNode }) { + return ( + + + {children} + + + ); +} describe('EmptyBanner', () => { describe('when cy is undefined', () => { it('renders null', () => { - const noCytoscapeWrapper: FunctionComponent = ({ children }) => ( - - - {children} - - - ); + function noCytoscapeWrapper({ children }: { children: ReactNode }) { + return ( + + + {children} + + + ); + } const component = renderWithTheme(, { wrapper: noCytoscapeWrapper, }); diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/LoadingOverlay.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/LoadingOverlay.tsx index 9e805058e8cb5..8557c3f0c0798 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/LoadingOverlay.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/LoadingOverlay.tsx @@ -34,26 +34,28 @@ interface Props { percentageLoaded: number; } -export const LoadingOverlay = ({ isLoading, percentageLoaded }: Props) => ( - - {isLoading && ( - - - - - - - {i18n.translate('xpack.apm.loadingServiceMap', { - defaultMessage: - 'Loading service map... This might take a short while.', - })} - - - )} - -); +export function LoadingOverlay({ isLoading, percentageLoaded }: Props) { + return ( + + {isLoading && ( + + + + + + + {i18n.translate('xpack.apm.loadingServiceMap', { + defaultMessage: + 'Loading service map... This might take a short while.', + })} + + + )} + + ); +} diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Buttons.test.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Buttons.test.tsx new file mode 100644 index 0000000000000..4146266b17916 --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Buttons.test.tsx @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { Buttons } from './Buttons'; +import { render } from '@testing-library/react'; + +describe('Popover Buttons', () => { + it('renders', () => { + expect(() => + render() + ).not.toThrowError(); + }); + + it('handles focus click', async () => { + const onFocusClick = jest.fn(); + const result = render( + + ); + const focusButton = await result.findByText('Focus map'); + + focusButton.click(); + + expect(onFocusClick).toHaveBeenCalledTimes(1); + }); +}); diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Buttons.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Buttons.tsx index d67447e04ef81..cb33fb32f3b0d 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Buttons.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Buttons.tsx @@ -22,7 +22,12 @@ export function Buttons({ onFocusClick = () => {}, selectedNodeServiceName, }: ButtonsProps) { - const urlParams = useUrlParams().urlParams as APMQueryParams; + // The params may contain the service name. We want to use the selected node's + // service name in the button URLs, so make a copy and set the + // `serviceName` property. + const urlParams = { ...useUrlParams().urlParams } as APMQueryParams; + urlParams.serviceName = selectedNodeServiceName; + const detailsUrl = getAPMHref( `/services/${selectedNodeServiceName}/transactions`, '', diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Contents.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Contents.tsx index 78466b2659bb7..4911d7f147d7c 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Contents.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Contents.tsx @@ -34,20 +34,21 @@ interface ContentsProps { // @ts-ignore `documentMode` is not recognized as a valid property of `document`. const isIE11 = !!window.MSInputMethodContext && !!document.documentMode; -const FlexColumnGroup = (props: { +function FlexColumnGroup(props: { children: React.ReactNode; style: React.CSSProperties; direction: 'column'; gutterSize: 's'; -}) => { +}) { if (isIE11) { const { direction, gutterSize, ...rest } = props; return
; } return ; -}; -const FlexColumnItem = (props: { children: React.ReactNode }) => - isIE11 ?
: ; +} +function FlexColumnItem(props: { children: React.ReactNode }) { + return isIE11 ?
: ; +} export function Contents({ selectedNodeData, diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/index.test.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/index.test.tsx index f36b94f2971cd..4a56f75b05de9 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/index.test.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/index.test.tsx @@ -5,7 +5,7 @@ */ import { render } from '@testing-library/react'; -import React, { FunctionComponent } from 'react'; +import React, { ReactNode } from 'react'; import { License } from '../../../../../licensing/common/license'; import { LicenseContext } from '../../../context/LicenseContext'; import { ServiceMap } from './'; @@ -22,13 +22,13 @@ const expiredLicense = new License({ }, }); -const Wrapper: FunctionComponent = ({ children }) => { +function Wrapper({ children }: { children?: ReactNode }) { return ( {children} ); -}; +} describe('ServiceMap', () => { describe('with an inactive license', () => { diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/index.tsx index 7f3d25efa6f44..d4be4da2ae1c5 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/index.tsx @@ -29,7 +29,7 @@ interface ServiceMapProps { serviceName?: string; } -export const ServiceMap = ({ serviceName }: ServiceMapProps) => { +export function ServiceMap({ serviceName }: ServiceMapProps) { const theme = useTheme(); const license = useLicense(); const { urlParams } = useUrlParams(); @@ -101,4 +101,4 @@ export const ServiceMap = ({ serviceName }: ServiceMapProps) => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/ServiceNodeOverview/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceNodeOverview/index.tsx index 62ea3bc42860a..5537a73d228e8 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceNodeOverview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceNodeOverview/index.tsx @@ -36,7 +36,7 @@ const ServiceNodeName = styled.div` ${truncate(px(8 * unit))} `; -const ServiceNodeOverview = () => { +function ServiceNodeOverview() { const { uiFilters, urlParams } = useUrlParams(); const { serviceName, start, end } = urlParams; @@ -182,6 +182,6 @@ const ServiceNodeOverview = () => { ); -}; +} export { ServiceNodeOverview }; diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/index.tsx index 0f23e230733b4..ce325a57426f5 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/index.tsx @@ -38,7 +38,7 @@ interface Props { refetch: () => void; } -export const AgentConfigurationList = ({ status, data, refetch }: Props) => { +export function AgentConfigurationList({ status, data, refetch }: Props) { const theme = useTheme(); const [configToBeDeleted, setConfigToBeDeleted] = useState( null @@ -219,4 +219,4 @@ export const AgentConfigurationList = ({ status, data, refetch }: Props) => { /> ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateCustomLinkButton.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateCustomLinkButton.tsx index 919cc4debe4d8..2e860ebe22c0f 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateCustomLinkButton.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateCustomLinkButton.tsx @@ -7,15 +7,13 @@ import React from 'react'; import { EuiButton } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -export const CreateCustomLinkButton = ({ - onClick, -}: { - onClick: () => void; -}) => ( - - {i18n.translate( - 'xpack.apm.settings.customizeUI.customLink.createCustomLink', - { defaultMessage: 'Create custom link' } - )} - -); +export function CreateCustomLinkButton({ onClick }: { onClick: () => void }) { + return ( + + {i18n.translate( + 'xpack.apm.settings.customizeUI.customLink.createCustomLink', + { defaultMessage: 'Create custom link' } + )} + + ); +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/Documentation.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/Documentation.tsx index 48a0288f11ae5..262d22be25272 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/Documentation.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/Documentation.tsx @@ -9,8 +9,14 @@ import { ElasticDocsLink } from '../../../../../shared/Links/ElasticDocsLink'; interface Props { label: string; } -export const Documentation = ({ label }: Props) => ( - - {label} - -); +export function Documentation({ label }: Props) { + return ( + + {label} + + ); +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FiltersSection.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FiltersSection.tsx index daadc1bace9c4..8cf0f03175fc2 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FiltersSection.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FiltersSection.tsx @@ -26,13 +26,13 @@ import { getSelectOptions, } from './helper'; -export const FiltersSection = ({ +export function FiltersSection({ filters, onChangeFilters, }: { filters: Filter[]; onChangeFilters: (filters: Filter[]) => void; -}) => { +}) { const onChangeFilter = ( key: Filter['key'], value: Filter['value'], @@ -147,25 +147,27 @@ export const FiltersSection = ({ /> ); -}; +} -const AddFilterButton = ({ +function AddFilterButton({ onClick, isDisabled, }: { onClick: () => void; isDisabled: boolean; -}) => ( - - {i18n.translate( - 'xpack.apm.settings.customizeUI.customLink.flyout.filters.addAnotherFilter', - { - defaultMessage: 'Add another filter', - } - )} - -); +}) { + return ( + + {i18n.translate( + 'xpack.apm.settings.customizeUI.customLink.flyout.filters.addAnotherFilter', + { + defaultMessage: 'Add another filter', + } + )} + + ); +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FlyoutFooter.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FlyoutFooter.tsx index 4fde75602990c..17c3fb265bca5 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FlyoutFooter.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FlyoutFooter.tsx @@ -14,7 +14,7 @@ import { import { i18n } from '@kbn/i18n'; import { DeleteButton } from './DeleteButton'; -export const FlyoutFooter = ({ +export function FlyoutFooter({ onClose, isSaving, onDelete, @@ -26,7 +26,7 @@ export const FlyoutFooter = ({ onDelete: () => void; customLinkId?: string; isSaveButtonEnabled: boolean; -}) => { +}) { return ( @@ -61,4 +61,4 @@ export const FlyoutFooter = ({ ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkPreview.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkPreview.tsx index b229157d1b1a8..b7250bda30966 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkPreview.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkPreview.tsx @@ -41,7 +41,7 @@ const fetchTransaction = debounce( const getTextColor = (value?: string) => (value ? 'default' : 'subdued'); -export const LinkPreview = ({ label, url, filters }: Props) => { +export function LinkPreview({ label, url, filters }: Props) { const [transaction, setTransaction] = useState(); useEffect(() => { @@ -128,4 +128,4 @@ export const LinkPreview = ({ label, url, filters }: Props) => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkSection.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkSection.tsx index 6a31752d11705..49307cbb8efba 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkSection.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkSection.tsx @@ -31,12 +31,7 @@ interface Props { onChangeUrl: (url: string) => void; } -export const LinkSection = ({ - label, - onChangeLabel, - url, - onChangeUrl, -}: Props) => { +export function LinkSection({ label, onChangeLabel, url, onChangeUrl }: Props) { const inputFields: InputField[] = [ { name: 'label', @@ -145,4 +140,4 @@ export const LinkSection = ({ })} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/index.tsx index ccd98bd005666..9687846d6c520 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/index.tsx @@ -37,13 +37,13 @@ interface Props { const filtersEmptyState: Filter[] = [{ key: '', value: '' }]; -export const CustomLinkFlyout = ({ +export function CustomLinkFlyout({ onClose, onSave, onDelete, defaults, customLinkId, -}: Props) => { +}: Props) { const { toasts } = useApmPluginContext().core.notifications; const [isSaving, setIsSaving] = useState(false); @@ -139,4 +139,4 @@ export const CustomLinkFlyout = ({ ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkTable.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkTable.tsx index f2aabc878bf2d..d512ea19c7892 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkTable.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkTable.tsx @@ -24,10 +24,7 @@ interface Props { onCustomLinkSelected: (customLink: CustomLink) => void; } -export const CustomLinkTable = ({ - items = [], - onCustomLinkSelected, -}: Props) => { +export function CustomLinkTable({ items = [], onCustomLinkSelected }: Props) { const [searchTerm, setSearchTerm] = useState(''); const columns = [ @@ -121,20 +118,22 @@ export const CustomLinkTable = ({ /> ); -}; +} -const NoResultFound = ({ value }: { value: string }) => ( - - - - {i18n.translate( - 'xpack.apm.settings.customizeUI.customLink.table.noResultFound', - { - defaultMessage: `No results for "{value}".`, - values: { value }, - } - )} - - - -); +function NoResultFound({ value }: { value: string }) { + return ( + + + + {i18n.translate( + 'xpack.apm.settings.customizeUI.customLink.table.noResultFound', + { + defaultMessage: `No results for "{value}".`, + values: { value }, + } + )} + + + + ); +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/EmptyPrompt.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/EmptyPrompt.tsx index ee9350e320e1a..9411043c0b716 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/EmptyPrompt.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/EmptyPrompt.tsx @@ -8,11 +8,11 @@ import { i18n } from '@kbn/i18n'; import React from 'react'; import { CreateCustomLinkButton } from './CreateCustomLinkButton'; -export const EmptyPrompt = ({ +export function EmptyPrompt({ onCreateCustomLinkClick, }: { onCreateCustomLinkClick: () => void; -}) => { +}) { return ( } /> ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/Title.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/Title.tsx index 95b8adb403981..22d8749d78834 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/Title.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/Title.tsx @@ -7,34 +7,36 @@ import { EuiFlexGroup, EuiFlexItem, EuiIconTip, EuiTitle } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -export const Title = () => ( - - - - - -

- {i18n.translate('xpack.apm.settings.customizeUI.customLink', { - defaultMessage: 'Custom Links', - })} -

-
+export function Title() { + return ( + + + + + +

+ {i18n.translate('xpack.apm.settings.customizeUI.customLink', { + defaultMessage: 'Custom Links', + })} +

+
- - - -
-
-
-
-); + + + +
+
+
+
+ ); +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.test.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.test.tsx index d633d466b6614..56c420878cdba 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.test.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.test.tsx @@ -35,9 +35,8 @@ const data = [ ]; describe('CustomLink', () => { - let callApmApiSpy: jest.SpyInstance; beforeAll(() => { - callApmApiSpy = jest.spyOn(apmApi, 'callApmApi').mockReturnValue({}); + jest.spyOn(apmApi, 'callApmApi').mockReturnValue({}); }); afterAll(() => { jest.resetAllMocks(); @@ -103,7 +102,7 @@ describe('CustomLink', () => { ]); }); - it('checks if create custom link button is available and working', async () => { + it('checks if create custom link button is available and working', () => { const { queryByText, getByText } = render( @@ -115,7 +114,6 @@ describe('CustomLink', () => { act(() => { fireEvent.click(getByText('Create custom link')); }); - await wait(() => expect(callApmApiSpy).toHaveBeenCalled()); expect(queryByText('Create link')).toBeInTheDocument(); }); }); @@ -133,7 +131,7 @@ describe('CustomLink', () => { }); }); - const openFlyout = async () => { + const openFlyout = () => { const component = render( @@ -145,15 +143,12 @@ describe('CustomLink', () => { act(() => { fireEvent.click(component.getByText('Create custom link')); }); - await wait(() => - expect(component.queryByText('Create link')).toBeInTheDocument() - ); - await wait(() => expect(callApmApiSpy).toHaveBeenCalled()); + expect(component.queryByText('Create link')).toBeInTheDocument(); return component; }; it('creates a custom link', async () => { - const component = await openFlyout(); + const component = openFlyout(); const labelInput = component.getByTestId('label'); act(() => { fireEvent.change(labelInput, { @@ -167,7 +162,7 @@ describe('CustomLink', () => { }); }); await act(async () => { - await wait(() => fireEvent.submit(component.getByText('Save'))); + fireEvent.submit(component.getByText('Save')); }); expect(saveCustomLinkSpy).toHaveBeenCalledTimes(1); }); @@ -186,11 +181,12 @@ describe('CustomLink', () => { act(() => { fireEvent.click(editButtons[0]); }); - expect(component.queryByText('Create link')).toBeInTheDocument(); + await wait(() => + expect(component.queryByText('Create link')).toBeInTheDocument() + ); await act(async () => { - await wait(() => fireEvent.click(component.getByText('Delete'))); + fireEvent.click(component.getByText('Delete')); }); - expect(callApmApiSpy).toHaveBeenCalled(); expect(refetch).toHaveBeenCalled(); }); @@ -200,8 +196,8 @@ describe('CustomLink', () => { fireEvent.click(component.getByText('Add another filter')); } }; - it('checks if add filter button is disabled after all elements have been added', async () => { - const component = await openFlyout(); + it('checks if add filter button is disabled after all elements have been added', () => { + const component = openFlyout(); expect(component.getAllByText('service.name').length).toEqual(1); addFilterField(component, 1); expect(component.getAllByText('service.name').length).toEqual(2); @@ -211,8 +207,8 @@ describe('CustomLink', () => { addFilterField(component, 2); expect(component.getAllByText('service.name').length).toEqual(4); }); - it('removes items already selected', async () => { - const component = await openFlyout(); + it('removes items already selected', () => { + const component = openFlyout(); const addFieldAndCheck = ( fieldName: string, diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.tsx index b4acc783d08ed..aa34515ea460a 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.tsx @@ -18,7 +18,7 @@ import { Title } from './Title'; import { CreateCustomLinkButton } from './CreateCustomLinkButton'; import { LicensePrompt } from '../../../../shared/LicensePrompt'; -export const CustomLinkOverview = () => { +export function CustomLinkOverview() { const license = useLicense(); const hasValidLicense = license?.isActive && license?.hasAtLeast('gold'); @@ -107,4 +107,4 @@ export const CustomLinkOverview = () => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/index.tsx index c88eba1c87b57..84408a7624403 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/index.tsx @@ -9,7 +9,7 @@ import { EuiTitle, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { CustomLinkOverview } from './CustomLink'; -export const CustomizeUI = () => { +export function CustomizeUI() { return ( <> @@ -23,4 +23,4 @@ export const CustomizeUI = () => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx index c9328c4988e5f..cb2090d1cbe2b 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx @@ -31,11 +31,11 @@ interface Props { onCreateJobSuccess: () => void; onCancel: () => void; } -export const AddEnvironments = ({ +export function AddEnvironments({ currentEnvironments, onCreateJobSuccess, onCancel, -}: Props) => { +}: Props) { const { notifications, application } = useApmPluginContext().core; const canCreateJob = !!application.capabilities.ml.canCreateJob; const { toasts } = notifications; @@ -175,4 +175,4 @@ export const AddEnvironments = ({ ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/index.tsx index abbe1e2c83c7b..dab30761c6ebe 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/index.tsx @@ -28,7 +28,7 @@ const DEFAULT_VALUE: AnomalyDetectionApiResponse = { errorCode: undefined, }; -export const AnomalyDetection = () => { +export function AnomalyDetection() { const plugin = useApmPluginContext(); const canGetJobs = !!plugin.core.application.capabilities.ml.canGetJobs; const license = useLicense(); @@ -112,4 +112,4 @@ export const AnomalyDetection = () => { )} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/jobs_list.tsx b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/jobs_list.tsx index 67227f99cb5f1..8494004ae5639 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/jobs_list.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/jobs_list.tsx @@ -65,7 +65,7 @@ interface Props { status: FETCH_STATUS; onAddEnvironments: () => void; } -export const JobsList = ({ data, status, onAddEnvironments }: Props) => { +export function JobsList({ data, status, onAddEnvironments }: Props) { const { jobs, hasLegacyJobs, errorCode } = data; return ( @@ -127,7 +127,7 @@ export const JobsList = ({ data, status, onAddEnvironments }: Props) => { {hasLegacyJobs && } ); -}; +} function getNoItemsMessage({ status, @@ -152,7 +152,7 @@ function getNoItemsMessage({ if (status === FETCH_STATUS.FAILURE) { return i18n.translate( 'xpack.apm.settings.anomalyDetection.jobList.failedFetchText', - { defaultMessage: 'Unabled to fetch anomaly detection jobs.' } + { defaultMessage: 'Unable to fetch anomaly detection jobs.' } ); } diff --git a/x-pack/plugins/apm/public/components/app/Settings/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/index.tsx index 6d8571bf57767..bd2ea706e492d 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/index.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { ReactNode } from 'react'; import { i18n } from '@kbn/i18n'; import { EuiButtonEmpty, @@ -17,7 +17,7 @@ import { HomeLink } from '../../shared/Links/apm/HomeLink'; import { useLocation } from '../../../hooks/useLocation'; import { getAPMHref } from '../../shared/Links/apm/APMLink'; -export const Settings: React.FC = (props) => { +export function Settings(props: { children: ReactNode }) { const { search, pathname } = useLocation(); return ( <> @@ -84,4 +84,4 @@ export const Settings: React.FC = (props) => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/TraceLink/index.tsx b/x-pack/plugins/apm/public/components/app/TraceLink/index.tsx index 3eb5a855ee3b4..55ab275002b4e 100644 --- a/x-pack/plugins/apm/public/components/app/TraceLink/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TraceLink/index.tsx @@ -58,7 +58,7 @@ const redirectToTracePage = ({ }, }); -export const TraceLink = () => { +export function TraceLink() { const { urlParams } = useUrlParams(); const { traceIdLink: traceId, rangeFrom, rangeTo } = urlParams; @@ -93,4 +93,4 @@ export const TraceLink = () => { Fetching trace...} /> ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/TraceOverview/TraceList.tsx b/x-pack/plugins/apm/public/components/app/TraceOverview/TraceList.tsx index 898e32f5c2c09..f54255ec0cd18 100644 --- a/x-pack/plugins/apm/public/components/app/TraceOverview/TraceList.tsx +++ b/x-pack/plugins/apm/public/components/app/TraceOverview/TraceList.tsx @@ -9,7 +9,7 @@ import { i18n } from '@kbn/i18n'; import React from 'react'; import styled from 'styled-components'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { ITransactionGroup } from '../../../../server/lib/transaction_groups/transform'; +import { TransactionGroup } from '../../../../server/lib/transaction_groups/fetcher'; import { fontSizes, truncate } from '../../../style/variables'; import { asMillisecondDuration } from '../../../utils/formatters'; import { EmptyMessage } from '../../shared/EmptyMessage'; @@ -24,11 +24,11 @@ const StyledTransactionLink = styled(TransactionDetailLink)` `; interface Props { - items: ITransactionGroup[]; + items: TransactionGroup[]; isLoading: boolean; } -const traceListColumns: Array> = [ +const traceListColumns: Array> = [ { field: 'name', name: i18n.translate('xpack.apm.tracesTable.nameColumnLabel', { @@ -36,8 +36,8 @@ const traceListColumns: Array> = [ }), width: '40%', sortable: true, - render: (name: string, { sample }: ITransactionGroup) => ( - + render: (_: string, { sample }: TransactionGroup) => ( + > = [ transactionName={sample.transaction.name} transactionType={sample.transaction.type} > - {name} + {sample.transaction.name} ), diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/Distribution/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/Distribution/index.tsx index 1244dd01a3b43..90bbe0a5a2135 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/Distribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/Distribution/index.tsx @@ -7,19 +7,19 @@ import { EuiIconTip, EuiTitle } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import d3 from 'd3'; -import React, { FunctionComponent, useCallback } from 'react'; import { isEmpty } from 'lodash'; +import React, { useCallback } from 'react'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { TransactionDistributionAPIResponse } from '../../../../../server/lib/transactions/distribution'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { IBucket } from '../../../../../server/lib/transactions/distribution/get_buckets/transform'; import { IUrlParams } from '../../../../context/UrlParamsContext/types'; import { getDurationFormatter } from '../../../../utils/formatters'; +import { history } from '../../../../utils/history'; // @ts-ignore import Histogram from '../../../shared/charts/Histogram'; import { EmptyMessage } from '../../../shared/EmptyMessage'; import { fromQuery, toQuery } from '../../../shared/Links/url_helpers'; -import { history } from '../../../../utils/history'; import { LoadingStatePrompt } from '../../../shared/LoadingStatePrompt'; interface IChartPoint { @@ -99,9 +99,7 @@ interface Props { bucketIndex: number; } -export const TransactionDistribution: FunctionComponent = ( - props: Props -) => { +export function TransactionDistribution(props: Props) { const { distribution, urlParams: { transactionType }, @@ -211,4 +209,4 @@ export const TransactionDistribution: FunctionComponent = ( />
); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/ErrorCount.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/ErrorCount.tsx index 89757b227f8fd..20f93bce29ca8 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/ErrorCount.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/ErrorCount.tsx @@ -12,21 +12,23 @@ interface Props { count: number; } -export const ErrorCount = ({ count }: Props) => ( - -

- { - e.stopPropagation(); - }} - > - {i18n.translate('xpack.apm.transactionDetails.errorCount', { - defaultMessage: - '{errorCount, number} {errorCount, plural, one {Error} other {Errors}}', - values: { errorCount: count }, - })} - -

-
-); +export function ErrorCount({ count }: Props) { + return ( + +

+ { + e.stopPropagation(); + }} + > + {i18n.translate('xpack.apm.transactionDetails.errorCount', { + defaultMessage: + '{errorCount, number} {errorCount, plural, one {Error} other {Errors}}', + values: { errorCount: count }, + })} + +

+
+ ); +} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/TruncateHeightSection.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/TruncateHeightSection.tsx index 64e20cf10d8aa..4f32df2b3115e 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/TruncateHeightSection.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/TruncateHeightSection.tsx @@ -6,7 +6,7 @@ import { EuiIcon, EuiLink } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import React, { Fragment, useEffect, useRef, useState } from 'react'; +import React, { Fragment, ReactNode, useEffect, useRef, useState } from 'react'; import styled from 'styled-components'; import { px, units } from '../../../../../../../style/variables'; @@ -16,13 +16,11 @@ const ToggleButtonContainer = styled.div` `; interface Props { + children: ReactNode; previewHeight: number; } -export const TruncateHeightSection: React.FC = ({ - children, - previewHeight, -}) => { +export function TruncateHeightSection({ children, previewHeight }: Props) { const contentContainerEl = useRef(null); const [showToggle, setShowToggle] = useState(true); @@ -73,4 +71,4 @@ export const TruncateHeightSection: React.FC = ({ ) : null} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallFlyout.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallFlyout.tsx index f0150e5a1b758..7e1dbddf56025 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallFlyout.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallFlyout.tsx @@ -15,12 +15,13 @@ interface Props { location: Location; toggleFlyout: ({ location }: { location: Location }) => void; } -export const WaterfallFlyout: React.FC = ({ + +export function WaterfallFlyout({ waterfallItemId, waterfall, location, toggleFlyout, -}) => { +}: Props) { const currentItem = waterfall.items.find( (item) => item.id === waterfallItemId ); @@ -58,4 +59,4 @@ export const WaterfallFlyout: React.FC = ({ default: return null; } -}; +} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallItem.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallItem.tsx index a25ae71947f21..a4d42bcf51d01 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallItem.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallItem.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { ReactNode } from 'react'; import styled from 'styled-components'; import { EuiIcon, EuiText, EuiTitle, EuiToolTip } from '@elastic/eui'; @@ -109,13 +109,11 @@ function PrefixIcon({ item }: { item: IWaterfallItem }) { } interface SpanActionToolTipProps { + children: ReactNode; item?: IWaterfallItem; } -const SpanActionToolTip: React.FC = ({ - item, - children, -}) => { +function SpanActionToolTip({ item, children }: SpanActionToolTipProps) { if (item?.docType === 'span') { return ( @@ -124,7 +122,7 @@ const SpanActionToolTip: React.FC = ({ ); } return <>{children}; -}; +} function Duration({ item }: { item: IWaterfallItem }) { return ( diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/index.tsx index 78235594f40ec..1fd0ec761b1ae 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/index.tsx @@ -67,12 +67,12 @@ interface Props { exceedsMax: boolean; } -export const Waterfall: React.FC = ({ +export function Waterfall({ waterfall, exceedsMax, waterfallItemId, location, -}) => { +}: Props) { const itemContainerHeight = 58; // TODO: This is a nasty way to calculate the height of the svg element. A better approach should be found const waterfallHeight = itemContainerHeight * waterfall.items.length; @@ -81,7 +81,7 @@ export const Waterfall: React.FC = ({ const agentMarks = getAgentMarks(waterfall.entryTransaction); const errorMarks = getErrorMarks(waterfall.errorItems, serviceColors); - const renderWaterfallItem = (item: IWaterfallItem) => { + function renderWaterfallItem(item: IWaterfallItem) { const errorCount = item.docType === 'transaction' ? waterfall.errorsPerTransaction[item.doc.transaction.id] @@ -99,7 +99,7 @@ export const Waterfall: React.FC = ({ onClick={() => toggleFlyout({ item, location })} /> ); - }; + } return ( @@ -134,4 +134,4 @@ export const Waterfall: React.FC = ({ /> ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/index.tsx index beb0c03f37f8f..12676b7c15f1c 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/index.tsx @@ -37,14 +37,14 @@ interface Props { traceSamples: IBucket['samples']; } -export const WaterfallWithSummmary: React.FC = ({ +export function WaterfallWithSummmary({ urlParams, location, waterfall, exceedsMax, isLoading, traceSamples, -}) => { +}: Props) { const [sampleActivePage, setSampleActivePage] = useState(0); useEffect(() => { @@ -135,4 +135,4 @@ export const WaterfallWithSummmary: React.FC = ({ /> ); -}; +} diff --git a/x-pack/plugins/apm/public/components/app/TransactionOverview/List/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionOverview/List/index.tsx index ae1b07bde0c87..2b1c1b8e8c11c 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionOverview/List/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionOverview/List/index.tsx @@ -10,7 +10,7 @@ import React, { useMemo } from 'react'; import styled from 'styled-components'; import { NOT_AVAILABLE_LABEL } from '../../../../../common/i18n'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { ITransactionGroup } from '../../../../../server/lib/transaction_groups/transform'; +import { TransactionGroup } from '../../../../../server/lib/transaction_groups/fetcher'; import { fontFamilyCode, truncate } from '../../../../style/variables'; import { asDecimal, asMillisecondDuration } from '../../../../utils/formatters'; import { ImpactBar } from '../../../shared/ImpactBar'; @@ -25,12 +25,12 @@ const TransactionNameLink = styled(TransactionDetailLink)` `; interface Props { - items: ITransactionGroup[]; + items: TransactionGroup[]; isLoading: boolean; } export function TransactionList({ items, isLoading }: Props) { - const columns: Array> = useMemo( + const columns: Array> = useMemo( () => [ { field: 'name', @@ -39,11 +39,11 @@ export function TransactionList({ items, isLoading }: Props) { }), width: '50%', sortable: true, - render: (transactionName: string, { sample }: ITransactionGroup) => { + render: (_, { sample }: TransactionGroup) => { return ( - {transactionName || NOT_AVAILABLE_LABEL} + {sample.transaction.name || NOT_AVAILABLE_LABEL} ); diff --git a/x-pack/plugins/apm/public/components/shared/ApmHeader/index.tsx b/x-pack/plugins/apm/public/components/shared/ApmHeader/index.tsx index cccbdc8d86d91..4ffd422801816 100644 --- a/x-pack/plugins/apm/public/components/shared/ApmHeader/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/ApmHeader/index.tsx @@ -5,29 +5,31 @@ */ import { EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; -import React from 'react'; +import React, { ReactNode } from 'react'; import { KueryBar } from '../KueryBar'; import { DatePicker } from '../DatePicker'; import { EnvironmentFilter } from '../EnvironmentFilter'; -export const ApmHeader: React.FC = ({ children }) => ( - <> - - {children} - - - - +export function ApmHeader({ children }: { children: ReactNode }) { + return ( + <> + + {children} + + + + - + - - - - - - - - - -); + + + + + + + + + + ); +} diff --git a/x-pack/plugins/apm/public/components/shared/DatePicker/__test__/DatePicker.test.tsx b/x-pack/plugins/apm/public/components/shared/DatePicker/__test__/DatePicker.test.tsx index 215e97aebf646..36e33fba89fbb 100644 --- a/x-pack/plugins/apm/public/components/shared/DatePicker/__test__/DatePicker.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/DatePicker/__test__/DatePicker.test.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { ReactNode } from 'react'; import { LocationProvider } from '../../../../context/LocationContext'; import { UrlParamsContext, @@ -21,18 +21,24 @@ import { MockApmPluginContextWrapper } from '../../../../context/ApmPluginContex const mockHistoryPush = jest.spyOn(history, 'push'); const mockRefreshTimeRange = jest.fn(); -const MockUrlParamsProvider: React.FC<{ +function MockUrlParamsProvider({ + params = {}, + children, +}: { + children: ReactNode; params?: IUrlParams; -}> = ({ params = {}, children }) => ( - -); +}) { + return ( + + ); +} function mountDatePicker(params?: IUrlParams) { return mount( diff --git a/x-pack/plugins/apm/public/components/shared/EmptyMessage.tsx b/x-pack/plugins/apm/public/components/shared/EmptyMessage.tsx index f300ed9d65aac..296df901d309e 100644 --- a/x-pack/plugins/apm/public/components/shared/EmptyMessage.tsx +++ b/x-pack/plugins/apm/public/components/shared/EmptyMessage.tsx @@ -14,7 +14,7 @@ interface Props { hideSubheading?: boolean; } -const EmptyMessage: React.FC = ({ +function EmptyMessage({ heading = i18n.translate('xpack.apm.emptyMessage.noDataFoundLabel', { defaultMessage: 'No data found.', }), @@ -22,7 +22,7 @@ const EmptyMessage: React.FC = ({ defaultMessage: 'Try another time range or reset the search filter.', }), hideSubheading = false, -}) => { +}: Props) { return ( = ({ body={!hideSubheading && subheading} /> ); -}; +} export { EmptyMessage }; diff --git a/x-pack/plugins/apm/public/components/shared/EnvironmentBadge/index.tsx b/x-pack/plugins/apm/public/components/shared/EnvironmentBadge/index.tsx index 47e52285b6851..a430eea1cf40c 100644 --- a/x-pack/plugins/apm/public/components/shared/EnvironmentBadge/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/EnvironmentBadge/index.tsx @@ -11,7 +11,7 @@ import { EuiBadge, EuiToolTip } from '@elastic/eui'; interface Props { environments: string[]; } -export const EnvironmentBadge: React.FC = ({ environments = [] }) => { +export function EnvironmentBadge({ environments = [] }: Props) { if (environments.length < 3) { return ( <> @@ -42,4 +42,4 @@ export const EnvironmentBadge: React.FC = ({ environments = [] }) => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/EnvironmentFilter/index.tsx b/x-pack/plugins/apm/public/components/shared/EnvironmentFilter/index.tsx index 28dd5e7a5a363..1490ca42679b9 100644 --- a/x-pack/plugins/apm/public/components/shared/EnvironmentFilter/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/EnvironmentFilter/index.tsx @@ -65,7 +65,7 @@ function getOptions(environments: string[]) { ]; } -export const EnvironmentFilter: React.FC = () => { +export function EnvironmentFilter() { const location = useLocation(); const { uiFilters, urlParams } = useUrlParams(); @@ -90,4 +90,4 @@ export const EnvironmentFilter: React.FC = () => { isLoading={status === 'loading'} /> ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/EuiTabLink.tsx b/x-pack/plugins/apm/public/components/shared/EuiTabLink.tsx index 8538ea6a510ce..d29ccd8abcd42 100644 --- a/x-pack/plugins/apm/public/components/shared/EuiTabLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/EuiTabLink.tsx @@ -32,7 +32,7 @@ const Wrapper = styled.div<{ isSelected: boolean }>` } `; -const EuiTabLink = (props: Props) => { +function EuiTabLink(props: Props) { const { isSelected, children } = props; const className = cls('euiTab', { @@ -44,6 +44,6 @@ const EuiTabLink = (props: Props) => { {children} ); -}; +} export { EuiTabLink }; diff --git a/x-pack/plugins/apm/public/components/shared/HeightRetainer/index.tsx b/x-pack/plugins/apm/public/components/shared/HeightRetainer/index.tsx index be8ff87617c80..5c8755f9f586f 100644 --- a/x-pack/plugins/apm/public/components/shared/HeightRetainer/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/HeightRetainer/index.tsx @@ -6,7 +6,12 @@ import React, { useEffect, useRef } from 'react'; -export const HeightRetainer: React.FC = (props) => { +export function HeightRetainer( + props: React.DetailedHTMLProps< + React.HTMLAttributes, + HTMLDivElement + > +) { const containerElement = useRef(null); const minHeight = useRef(0); @@ -26,4 +31,4 @@ export const HeightRetainer: React.FC = (props) => { style={{ minHeight: minHeight.current }} /> ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx b/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx index 6ddc4eecba7ed..502f5f0034b5f 100644 --- a/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx @@ -112,7 +112,6 @@ export function KueryBar() { setState({ ...state, suggestions, isLoadingSuggestions: false }); } catch (e) { - // eslint-disable-next-line no-console console.error('Error while fetching suggestions', e); } } diff --git a/x-pack/plugins/apm/public/components/shared/LicensePrompt/index.tsx b/x-pack/plugins/apm/public/components/shared/LicensePrompt/index.tsx index d8464fdfa8481..8409326243614 100644 --- a/x-pack/plugins/apm/public/components/shared/LicensePrompt/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/LicensePrompt/index.tsx @@ -14,10 +14,9 @@ interface Props { showBetaBadge?: boolean; } -export const LicensePrompt = ({ text, showBetaBadge = false }: Props) => { +export function LicensePrompt({ text, showBetaBadge = false }: Props) { const licensePageUrl = useKibanaUrl( - '/app/kibana', - '/management/stack/license_management/home' + '/app/management/stack/license_management' ); const renderLicenseBody = ( @@ -60,4 +59,4 @@ export const LicensePrompt = ({ text, showBetaBadge = false }: Props) => { ); return <>{showBetaBadge ? renderWithBetaBadge : renderLicenseBody}; -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverErrorLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverErrorLink.tsx index 5679e31a9898b..d83f10cf1975f 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverErrorLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverErrorLink.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { ReactNode } from 'react'; import { ERROR_GROUP_ID, SERVICE_NAME, @@ -32,13 +32,18 @@ function getDiscoverQuery(error: APMError, kuery?: string) { }; } -const DiscoverErrorLink: React.FC<{ +function DiscoverErrorLink({ + error, + kuery, + children, +}: { + children?: ReactNode; readonly error: APMError; readonly kuery?: string; -}> = ({ error, kuery, children }) => { +}) { return ( ); -}; +} export { DiscoverErrorLink }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverSpanLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverSpanLink.tsx index 5fce3e842d8da..d7751c43b5943 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverSpanLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverSpanLink.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { ReactNode } from 'react'; import { SPAN_ID } from '../../../../../common/elasticsearch_fieldnames'; import { Span } from '../../../../../typings/es_schemas/ui/span'; import { DiscoverLink } from './DiscoverLink'; @@ -22,8 +22,12 @@ function getDiscoverQuery(span: Span) { }; } -export const DiscoverSpanLink: React.FC<{ +export function DiscoverSpanLink({ + span, + children, +}: { readonly span: Span; -}> = ({ span, children }) => { + children?: ReactNode; +}) { return ; -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverTransactionLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverTransactionLink.tsx index e2500617155c1..223fabbdb0d6f 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverTransactionLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverTransactionLink.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { ReactNode } from 'react'; import { PROCESSOR_EVENT, TRACE_ID, @@ -32,10 +32,14 @@ export function getDiscoverQuery(transaction: Transaction) { }; } -export const DiscoverTransactionLink: React.FC<{ +export function DiscoverTransactionLink({ + transaction, + children, +}: { readonly transaction: Transaction; -}> = ({ transaction, children }) => { + children?: ReactNode; +}) { return ( ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLJobLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLJobLink.tsx index f3c5b49287293..887ac2ff6bbb9 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLJobLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLJobLink.tsx @@ -4,24 +4,25 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { ReactNode } from 'react'; import { EuiLink } from '@elastic/eui'; import { useTimeSeriesExplorerHref } from './useTimeSeriesExplorerHref'; interface Props { + children?: ReactNode; jobId: string; external?: boolean; serviceName?: string; transactionType?: string; } -export const MLJobLink: React.FC = ({ +export function MLJobLink({ jobId, serviceName, transactionType, external, children, -}) => { +}: Props) { const href = useTimeSeriesExplorerHref({ jobId, serviceName, @@ -36,4 +37,4 @@ export const MLJobLink: React.FC = ({ target={external ? '_blank' : undefined} /> ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorDetailLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorDetailLink.tsx index c788da6a0d240..1ff32b17f3245 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorDetailLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorDetailLink.tsx @@ -11,13 +11,13 @@ interface Props extends APMLinkExtendProps { errorGroupId: string; } -const ErrorDetailLink = ({ serviceName, errorGroupId, ...rest }: Props) => { +function ErrorDetailLink({ serviceName, errorGroupId, ...rest }: Props) { return ( ); -}; +} export { ErrorDetailLink }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorOverviewLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorOverviewLink.tsx index 684531d50897c..862b1ac649648 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorOverviewLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorOverviewLink.tsx @@ -14,7 +14,7 @@ interface Props extends APMLinkExtendProps { query?: APMQueryParams; } -const ErrorOverviewLink = ({ serviceName, query, ...rest }: Props) => { +function ErrorOverviewLink({ serviceName, query, ...rest }: Props) { const { urlParams } = useUrlParams(); const persistedFilters = pickKeys( @@ -35,6 +35,6 @@ const ErrorOverviewLink = ({ serviceName, query, ...rest }: Props) => { {...rest} /> ); -}; +} export { ErrorOverviewLink }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/HomeLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/HomeLink.tsx index 92ff3164880e8..724b9536dfaa3 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/HomeLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/HomeLink.tsx @@ -6,8 +6,8 @@ import React from 'react'; import { APMLink, APMLinkExtendProps } from './APMLink'; -const HomeLink = (props: APMLinkExtendProps) => { +function HomeLink(props: APMLinkExtendProps) { return ; -}; +} export { HomeLink }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/MetricOverviewLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/MetricOverviewLink.tsx index bd3e3b36a8601..35ba5db68d507 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/MetricOverviewLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/MetricOverviewLink.tsx @@ -12,7 +12,7 @@ interface Props extends APMLinkExtendProps { serviceName: string; } -const MetricOverviewLink = ({ serviceName, ...rest }: Props) => { +function MetricOverviewLink({ serviceName, ...rest }: Props) { const { urlParams } = useUrlParams(); const persistedFilters = pickKeys( @@ -30,6 +30,6 @@ const MetricOverviewLink = ({ serviceName, ...rest }: Props) => { {...rest} /> ); -}; +} export { MetricOverviewLink }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceMapLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceMapLink.tsx index 36c108160bdb2..ff8b1354daeb5 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceMapLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceMapLink.tsx @@ -16,11 +16,11 @@ interface ServiceMapLinkProps extends APMLinkExtendProps { serviceName?: string; } -const ServiceMapLink = ({ serviceName, ...rest }: ServiceMapLinkProps) => { +function ServiceMapLink({ serviceName, ...rest }: ServiceMapLinkProps) { const path = serviceName ? `/services/${serviceName}/service-map` : '/service-map'; return ; -}; +} export { ServiceMapLink }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceNodeMetricOverviewLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceNodeMetricOverviewLink.tsx index 1473221cca2be..2553ec4353194 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceNodeMetricOverviewLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceNodeMetricOverviewLink.tsx @@ -13,11 +13,11 @@ interface Props extends APMLinkExtendProps { serviceNodeName: string; } -const ServiceNodeMetricOverviewLink = ({ +function ServiceNodeMetricOverviewLink({ serviceName, serviceNodeName, ...rest -}: Props) => { +}: Props) { const { urlParams } = useUrlParams(); const persistedFilters = pickKeys( @@ -37,6 +37,6 @@ const ServiceNodeMetricOverviewLink = ({ {...rest} /> ); -}; +} export { ServiceNodeMetricOverviewLink }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceNodeOverviewLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceNodeOverviewLink.tsx index b479ab77e1127..111c2391cd54f 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceNodeOverviewLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceNodeOverviewLink.tsx @@ -12,7 +12,7 @@ interface Props extends APMLinkExtendProps { serviceName: string; } -const ServiceNodeOverviewLink = ({ serviceName, ...rest }: Props) => { +function ServiceNodeOverviewLink({ serviceName, ...rest }: Props) { const { urlParams } = useUrlParams(); const persistedFilters = pickKeys( @@ -30,6 +30,6 @@ const ServiceNodeOverviewLink = ({ serviceName, ...rest }: Props) => { {...rest} /> ); -}; +} export { ServiceNodeOverviewLink }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceOverviewLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceOverviewLink.tsx index 577209a26e46b..2081fc4767903 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceOverviewLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/ServiceOverviewLink.tsx @@ -14,12 +14,12 @@ import { APMLink, APMLinkExtendProps } from './APMLink'; import { useUrlParams } from '../../../../hooks/useUrlParams'; import { pickKeys } from '../../../../../common/utils/pick_keys'; -const ServiceOverviewLink = (props: APMLinkExtendProps) => { +function ServiceOverviewLink(props: APMLinkExtendProps) { const { urlParams } = useUrlParams(); const persistedFilters = pickKeys(urlParams, 'host', 'agentName'); return ; -}; +} export { ServiceOverviewLink }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/SettingsLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/SettingsLink.tsx index 853972f4df402..80f3053b86f93 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/SettingsLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/SettingsLink.tsx @@ -6,8 +6,8 @@ import React from 'react'; import { APMLink, APMLinkExtendProps } from './APMLink'; -const SettingsLink = (props: APMLinkExtendProps) => { +function SettingsLink(props: APMLinkExtendProps) { return ; -}; +} export { SettingsLink }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/TraceOverviewLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/TraceOverviewLink.tsx index dc4519365cbc2..8f3ea191fab1a 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/TraceOverviewLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/TraceOverviewLink.tsx @@ -14,7 +14,7 @@ import { APMLink, APMLinkExtendProps } from './APMLink'; import { useUrlParams } from '../../../../hooks/useUrlParams'; import { pickKeys } from '../../../../../common/utils/pick_keys'; -const TraceOverviewLink = (props: APMLinkExtendProps) => { +function TraceOverviewLink(props: APMLinkExtendProps) { const { urlParams } = useUrlParams(); const persistedFilters = pickKeys( @@ -26,6 +26,6 @@ const TraceOverviewLink = (props: APMLinkExtendProps) => { ); return ; -}; +} export { TraceOverviewLink }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/TransactionDetailLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/TransactionDetailLink.tsx index c7eba1984472e..2ca3dce5da9ce 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/TransactionDetailLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/TransactionDetailLink.tsx @@ -17,14 +17,14 @@ interface Props extends APMLinkExtendProps { transactionType: string; } -export const TransactionDetailLink = ({ +export function TransactionDetailLink({ serviceName, traceId, transactionId, transactionName, transactionType, ...rest -}: Props) => { +}: Props) { const { urlParams } = useUrlParams(); const persistedFilters = pickKeys( @@ -46,4 +46,4 @@ export const TransactionDetailLink = ({ {...rest} /> ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/TransactionOverviewLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/TransactionOverviewLink.tsx index ccef83ee73fb8..adc64f5a2d3dc 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/TransactionOverviewLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/TransactionOverviewLink.tsx @@ -12,7 +12,7 @@ interface Props extends APMLinkExtendProps { serviceName: string; } -const TransactionOverviewLink = ({ serviceName, ...rest }: Props) => { +function TransactionOverviewLink({ serviceName, ...rest }: Props) { const { urlParams } = useUrlParams(); const persistedFilters = pickKeys( @@ -31,6 +31,6 @@ const TransactionOverviewLink = ({ serviceName, ...rest }: Props) => { {...rest} /> ); -}; +} export { TransactionOverviewLink }; diff --git a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/FilterBadgeList.tsx b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/FilterBadgeList.tsx index 9191f4e797637..2090a92bf0de4 100644 --- a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/FilterBadgeList.tsx +++ b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/FilterBadgeList.tsx @@ -20,24 +20,26 @@ interface Props { onRemove: (val: string) => void; } -const FilterBadgeList = ({ onRemove, value }: Props) => ( - - {value.map((val) => ( - - - - ))} - -); +function FilterBadgeList({ onRemove, value }: Props) { + return ( + + {value.map((val) => ( + + + + ))} + + ); +} export { FilterBadgeList }; diff --git a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/FilterTitleButton.tsx b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/FilterTitleButton.tsx index 26125ab0f5343..0d306f5133716 100644 --- a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/FilterTitleButton.tsx +++ b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/FilterTitleButton.tsx @@ -24,7 +24,7 @@ const Button = styled(EuiButtonEmpty).attrs(() => ({ type Props = React.ComponentProps; -export const FilterTitleButton = (props: Props) => { +export function FilterTitleButton(props: Props) { return ( ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/index.tsx b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/index.tsx index 167574f9aa00d..c13439a3c5928 100644 --- a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/index.tsx @@ -66,14 +66,7 @@ interface Props { type Option = EuiSelectable['props']['options'][0]; -const Filter = ({ - name, - title, - options, - onChange, - value, - showCount, -}: Props) => { +function Filter({ name, title, options, onChange, value, showCount }: Props) { const [showPopover, setShowPopover] = useState(false); const toggleShowPopover = () => setShowPopover((show) => !show); @@ -176,6 +169,6 @@ const Filter = ({ ) : null} ); -}; +} export { Filter }; diff --git a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/ServiceNameFilter/index.tsx b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/ServiceNameFilter/index.tsx index 405a4cacae714..99656b05db450 100644 --- a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/ServiceNameFilter/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/ServiceNameFilter/index.tsx @@ -21,7 +21,7 @@ interface Props { loading: boolean; } -const ServiceNameFilter = ({ loading, serviceNames }: Props) => { +function ServiceNameFilter({ loading, serviceNames }: Props) { const { urlParams: { serviceName }, } = useUrlParams(); @@ -72,6 +72,6 @@ const ServiceNameFilter = ({ loading, serviceNames }: Props) => { /> ); -}; +} export { ServiceNameFilter }; diff --git a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/TransactionTypeFilter/index.tsx b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/TransactionTypeFilter/index.tsx index 0e6b1c5904fc5..afd2d023d16ba 100644 --- a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/TransactionTypeFilter/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/TransactionTypeFilter/index.tsx @@ -20,7 +20,7 @@ interface Props { transactionTypes: string[]; } -const TransactionTypeFilter = ({ transactionTypes }: Props) => { +function TransactionTypeFilter({ transactionTypes }: Props) { const { urlParams: { transactionType }, } = useUrlParams(); @@ -59,6 +59,6 @@ const TransactionTypeFilter = ({ transactionTypes }: Props) => { /> ); -}; +} export { TransactionTypeFilter }; diff --git a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/index.tsx b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/index.tsx index 020b7481c68ea..fedf96b4cc4ea 100644 --- a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/index.tsx @@ -31,13 +31,13 @@ const ButtonWrapper = styled.div` display: inline-block; `; -const LocalUIFilters = ({ +function LocalUIFilters({ projection, params, filterNames, children, showCount = true, -}: Props) => { +}: Props) { const { filters, setFilterValue, clearValues } = useLocalUIFilters({ filterNames, projection, @@ -91,6 +91,6 @@ const LocalUIFilters = ({ ) : null} ); -}; +} export { LocalUIFilters }; diff --git a/x-pack/plugins/apm/public/components/shared/MetadataTable/index.tsx b/x-pack/plugins/apm/public/components/shared/MetadataTable/index.tsx index eace3035a3555..8dfb1e0ce960d 100644 --- a/x-pack/plugins/apm/public/components/shared/MetadataTable/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/MetadataTable/index.tsx @@ -91,18 +91,20 @@ export function MetadataTable({ sections }: Props) { ); } -const NoResultFound = ({ value }: { value: string }) => ( - - - - {i18n.translate( - 'xpack.apm.propertiesTable.agentFeature.noResultFound', - { - defaultMessage: `No results for "{value}".`, - values: { value }, - } - )} - - - -); +function NoResultFound({ value }: { value: string }) { + return ( + + + + {i18n.translate( + 'xpack.apm.propertiesTable.agentFeature.noResultFound', + { + defaultMessage: `No results for "{value}".`, + values: { value }, + } + )} + + + + ); +} diff --git a/x-pack/plugins/apm/public/components/shared/SelectWithPlaceholder/index.tsx b/x-pack/plugins/apm/public/components/shared/SelectWithPlaceholder/index.tsx index e0da91fae2ba7..02939b18401fe 100644 --- a/x-pack/plugins/apm/public/components/shared/SelectWithPlaceholder/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/SelectWithPlaceholder/index.tsx @@ -19,6 +19,7 @@ const DEFAULT_PLACEHOLDER = i18n.translate('xpack.apm.selectPlaceholder', { * with `hasNoInitialSelection`. It uses the `placeholder` prop to populate * the first option as the initial, not selected option. */ +// eslint-disable-next-line react/function-component-definition export const SelectWithPlaceholder: typeof EuiSelect = (props) => { const placeholder = props.placeholder || DEFAULT_PLACEHOLDER; return ( diff --git a/x-pack/plugins/apm/public/components/shared/ServiceAlertTrigger/PopoverExpression/index.tsx b/x-pack/plugins/apm/public/components/shared/ServiceAlertTrigger/PopoverExpression/index.tsx index 1abdb94c8313e..b07672eeaee06 100644 --- a/x-pack/plugins/apm/public/components/shared/ServiceAlertTrigger/PopoverExpression/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/ServiceAlertTrigger/PopoverExpression/index.tsx @@ -13,7 +13,7 @@ interface Props { children?: React.ReactNode; } -export const PopoverExpression = (props: Props) => { +export function PopoverExpression(props: Props) { const { title, value, children } = props; const [popoverOpen, setPopoverOpen] = useState(false); @@ -36,4 +36,4 @@ export const PopoverExpression = (props: Props) => { {children} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.tsx index 48580146c6fe1..5891895629318 100644 --- a/x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.tsx +++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.tsx @@ -29,7 +29,7 @@ interface Props { isLibraryFrame: boolean; } -const FrameHeading: React.FC = ({ stackframe, isLibraryFrame }) => { +function FrameHeading({ stackframe, isLibraryFrame }: Props) { const FileDetail = isLibraryFrame ? LibraryFrameFileDetail : AppFrameFileDetail; @@ -50,6 +50,6 @@ const FrameHeading: React.FC = ({ stackframe, isLibraryFrame }) => { )} ); -}; +} export { FrameHeading }; diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/Variables.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/Variables.tsx index 4bd6d361d6714..07b5ed6868df5 100644 --- a/x-pack/plugins/apm/public/components/shared/Stacktrace/Variables.tsx +++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/Variables.tsx @@ -23,7 +23,7 @@ interface Props { vars: IStackframe['vars']; } -export const Variables = ({ vars }: Props) => { +export function Variables({ vars }: Props) { if (!vars) { return null; } @@ -46,4 +46,4 @@ export const Variables = ({ vars }: Props) => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/Summary/DurationSummaryItem.tsx b/x-pack/plugins/apm/public/components/shared/Summary/DurationSummaryItem.tsx index 831f72e3925af..7858bebead408 100644 --- a/x-pack/plugins/apm/public/components/shared/Summary/DurationSummaryItem.tsx +++ b/x-pack/plugins/apm/public/components/shared/Summary/DurationSummaryItem.tsx @@ -15,11 +15,7 @@ interface Props { parentType: 'trace' | 'transaction'; } -const DurationSummaryItem = ({ - duration, - totalDuration, - parentType, -}: Props) => { +function DurationSummaryItem({ duration, totalDuration, parentType }: Props) { const calculatedTotalDuration = totalDuration === undefined ? duration : totalDuration; @@ -41,6 +37,6 @@ const DurationSummaryItem = ({ ); -}; +} export { DurationSummaryItem }; diff --git a/x-pack/plugins/apm/public/components/shared/Summary/ErrorCountSummaryItemBadge.tsx b/x-pack/plugins/apm/public/components/shared/Summary/ErrorCountSummaryItemBadge.tsx index b6ea6a714017d..ed33c59af36f4 100644 --- a/x-pack/plugins/apm/public/components/shared/Summary/ErrorCountSummaryItemBadge.tsx +++ b/x-pack/plugins/apm/public/components/shared/Summary/ErrorCountSummaryItemBadge.tsx @@ -19,7 +19,7 @@ const Badge = (styled(EuiBadge)` margin-top: ${px(units.eighth)}; ` as unknown) as typeof EuiBadge; -export const ErrorCountSummaryItemBadge = ({ count }: Props) => { +export function ErrorCountSummaryItemBadge({ count }: Props) { const theme = useTheme(); return ( @@ -31,4 +31,4 @@ export const ErrorCountSummaryItemBadge = ({ count }: Props) => { })} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/Summary/TransactionSummary.tsx b/x-pack/plugins/apm/public/components/shared/Summary/TransactionSummary.tsx index 86b42844f1fa7..98543ffaa9218 100644 --- a/x-pack/plugins/apm/public/components/shared/Summary/TransactionSummary.tsx +++ b/x-pack/plugins/apm/public/components/shared/Summary/TransactionSummary.tsx @@ -20,7 +20,7 @@ interface Props { errorCount: number; } -const getTransactionResultSummaryItem = (transaction: Transaction) => { +function getTransactionResultSummaryItem(transaction: Transaction) { const result = transaction.transaction.result; const isRumAgent = isRumAgentName(transaction.agent.name); const url = isRumAgent @@ -39,13 +39,9 @@ const getTransactionResultSummaryItem = (transaction: Transaction) => { } return null; -}; +} -const TransactionSummary = ({ - transaction, - totalDuration, - errorCount, -}: Props) => { +function TransactionSummary({ transaction, totalDuration, errorCount }: Props) { const items = [ , ; -}; +} export { TransactionSummary }; diff --git a/x-pack/plugins/apm/public/components/shared/Summary/index.tsx b/x-pack/plugins/apm/public/components/shared/Summary/index.tsx index 55ac525d71192..aea62c88f5833 100644 --- a/x-pack/plugins/apm/public/components/shared/Summary/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/Summary/index.tsx @@ -26,7 +26,7 @@ const Item = styled(EuiFlexItem)` } `; -const Summary = ({ items }: Props) => { +function Summary({ items }: Props) { const filteredItems = items.filter(Boolean) as React.ReactElement[]; return ( @@ -38,6 +38,6 @@ const Summary = ({ items }: Props) => { ))} ); -}; +} export { Summary }; diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/CustomLinkPopover.tsx b/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/CustomLinkPopover.tsx index 00a839adc2fdd..27c6aa82ac674 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/CustomLinkPopover.tsx +++ b/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/CustomLinkPopover.tsx @@ -24,7 +24,7 @@ const ScrollableContainer = styled.div` overflow: scroll; `; -export const CustomLinkPopover = ({ +export function CustomLinkPopover({ customLinks, onCreateCustomLinkClick, onClose, @@ -34,7 +34,7 @@ export const CustomLinkPopover = ({ onCreateCustomLinkClick: () => void; onClose: () => void; transaction: Transaction; -}) => { +}) { return ( <> @@ -71,4 +71,4 @@ export const CustomLinkPopover = ({ ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/CustomLinkSection.tsx b/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/CustomLinkSection.tsx index 40143b53f17c5..6b421bc370332 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/CustomLinkSection.tsx +++ b/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/CustomLinkSection.tsx @@ -24,28 +24,30 @@ const TruncateText = styled(EuiText)` ${truncate(px(units.unit * 25))} `; -export const CustomLinkSection = ({ +export function CustomLinkSection({ customLinks, transaction, }: { customLinks: CustomLink[]; transaction: Transaction; -}) => ( -
    - {customLinks.map((link) => { - let href = link.url; - try { - href = Mustache.render(link.url, transaction); - } catch (e) { - // ignores any error that happens - } - return ( - - - {link.label} - - - ); - })} -
-); +}) { + return ( +
    + {customLinks.map((link) => { + let href = link.url; + try { + href = Mustache.render(link.url, transaction); + } catch (e) { + // ignores any error that happens + } + return ( + + + {link.label} + + + ); + })} +
+ ); +} diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/ManageCustomLink.tsx b/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/ManageCustomLink.tsx index 9740a9f1ee847..09cdaa26004bb 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/ManageCustomLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/ManageCustomLink.tsx @@ -14,46 +14,48 @@ import { import { i18n } from '@kbn/i18n'; import { APMLink } from '../../Links/apm/APMLink'; -export const ManageCustomLink = ({ +export function ManageCustomLink({ onCreateCustomLinkClick, showCreateCustomLinkButton = true, }: { onCreateCustomLinkClick: () => void; showCreateCustomLinkButton?: boolean; -}) => ( - - - - - - - - - - - {showCreateCustomLinkButton && ( - - - {i18n.translate('xpack.apm.customLink.buttom.create.title', { - defaultMessage: 'Create', +}) { + return ( + + + + + + > + + + + - )} - - - -); + {showCreateCustomLinkButton && ( + + + {i18n.translate('xpack.apm.customLink.buttom.create.title', { + defaultMessage: 'Create', + })} + + + )} + + + + ); +} diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/index.tsx b/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/index.tsx index 40ac3c31d1d43..d6484f52e84f9 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLink/index.tsx @@ -37,7 +37,7 @@ const SeeMoreButton = styled.button<{ show: boolean }>` } `; -export const CustomLink = ({ +export function CustomLink({ customLinks, status, onCreateCustomLinkClick, @@ -49,7 +49,7 @@ export const CustomLink = ({ onCreateCustomLinkClick: () => void; onSeeMoreClick: () => void; transaction: Transaction; -}) => { +}) { const renderEmptyPrompt = ( <> @@ -125,4 +125,4 @@ export const CustomLink = ({ )} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/TransactionActionMenu.tsx b/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/TransactionActionMenu.tsx index 2507eca9ff663..77d70c626183f 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/TransactionActionMenu.tsx +++ b/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/TransactionActionMenu.tsx @@ -6,10 +6,8 @@ import { EuiButtonEmpty } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import React, { FunctionComponent, useMemo, useState, MouseEvent } from 'react'; +import React, { MouseEvent, useMemo, useState } from 'react'; import url from 'url'; -import { Filter } from '../../../../common/custom_link/custom_link_types'; -import { Transaction } from '../../../../typings/es_schemas/ui/transaction'; import { ActionMenu, ActionMenuDivider, @@ -19,32 +17,34 @@ import { SectionSubtitle, SectionTitle, } from '../../../../../observability/public'; +import { Filter } from '../../../../common/custom_link/custom_link_types'; +import { Transaction } from '../../../../typings/es_schemas/ui/transaction'; import { useApmPluginContext } from '../../../hooks/useApmPluginContext'; import { useFetcher } from '../../../hooks/useFetcher'; +import { useLicense } from '../../../hooks/useLicense'; import { useLocation } from '../../../hooks/useLocation'; import { useUrlParams } from '../../../hooks/useUrlParams'; import { CustomLinkFlyout } from '../../app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout'; +import { convertFiltersToQuery } from '../../app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/helper'; import { CustomLink } from './CustomLink'; import { CustomLinkPopover } from './CustomLink/CustomLinkPopover'; import { getSections } from './sections'; -import { useLicense } from '../../../hooks/useLicense'; -import { convertFiltersToQuery } from '../../app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/helper'; interface Props { readonly transaction: Transaction; } -const ActionMenuButton = ({ onClick }: { onClick: () => void }) => ( - - {i18n.translate('xpack.apm.transactionActionMenu.actionsButtonLabel', { - defaultMessage: 'Actions', - })} - -); - -export const TransactionActionMenu: FunctionComponent = ({ - transaction, -}: Props) => { +function ActionMenuButton({ onClick }: { onClick: () => void }) { + return ( + + {i18n.translate('xpack.apm.transactionActionMenu.actionsButtonLabel', { + defaultMessage: 'Actions', + })} + + ); +} + +export function TransactionActionMenu({ transaction }: Props) { const license = useLicense(); const hasValidLicense = license?.isActive && license?.hasAtLeast('gold'); @@ -211,4 +211,4 @@ export const TransactionActionMenu: FunctionComponent = ({ ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/TransactionBreakdownGraph/index.tsx b/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/TransactionBreakdownGraph/index.tsx index 2cb3696f88002..209657971620b 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/TransactionBreakdownGraph/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/TransactionBreakdownGraph/index.tsx @@ -29,7 +29,7 @@ const formatTooltipValue = (coordinate: Coordinate) => { : NOT_AVAILABLE_LABEL; }; -const TransactionBreakdownGraph: React.FC = (props) => { +function TransactionBreakdownGraph(props: Props) { const { timeseries } = props; const trackApmEvent = useUiTracker({ app: 'apm' }); const handleHover = useMemo( @@ -49,6 +49,6 @@ const TransactionBreakdownGraph: React.FC = (props) => { onHover={handleHover} /> ); -}; +} export { TransactionBreakdownGraph }; diff --git a/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/TransactionBreakdownKpiList.tsx b/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/TransactionBreakdownKpiList.tsx index 3898679f83537..d3761cf0fe38e 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/TransactionBreakdownKpiList.tsx +++ b/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/TransactionBreakdownKpiList.tsx @@ -31,10 +31,7 @@ const Description = styled.span` } `; -const KpiDescription: React.FC<{ - name: string; - color: string; -}> = ({ name, color }) => { +function KpiDescription({ name, color }: { name: string; color: string }) { return ( ); -}; +} -const TransactionBreakdownKpiList: React.FC = ({ kpis }) => { +function TransactionBreakdownKpiList({ kpis }: Props) { return ( {kpis.map((kpi) => ( @@ -73,6 +70,6 @@ const TransactionBreakdownKpiList: React.FC = ({ kpis }) => { ))} ); -}; +} export { TransactionBreakdownKpiList }; diff --git a/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/index.tsx b/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/index.tsx index 51cad6bc65a85..80ed9163ec08d 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/index.tsx @@ -21,7 +21,7 @@ const emptyMessage = i18n.translate('xpack.apm.transactionBreakdown.noData', { defaultMessage: 'No data within this time range.', }); -const TransactionBreakdown = () => { +function TransactionBreakdown() { const { data, status } = useTransactionBreakdown(); const { kpis, timeseries } = data; const noHits = data.kpis.length === 0 && status === FETCH_STATUS.SUCCESS; @@ -51,6 +51,6 @@ const TransactionBreakdown = () => { ); -}; +} export { TransactionBreakdown }; diff --git a/x-pack/plugins/apm/public/components/shared/charts/CustomPlot/AnnotationsPlot.tsx b/x-pack/plugins/apm/public/components/shared/charts/CustomPlot/AnnotationsPlot.tsx index ed57692d70a65..d02c5a5d08927 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/CustomPlot/AnnotationsPlot.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/CustomPlot/AnnotationsPlot.tsx @@ -26,7 +26,7 @@ interface Props { overlay: Maybe; } -export const AnnotationsPlot = ({ plotValues, annotations }: Props) => { +export function AnnotationsPlot({ plotValues, annotations }: Props) { const theme = useTheme(); const tickValues = annotations.map((annotation) => annotation['@timestamp']); @@ -70,4 +70,4 @@ export const AnnotationsPlot = ({ plotValues, annotations }: Props) => { ))} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/charts/ErroneousTransactionsRateChart/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/ErroneousTransactionsRateChart/index.tsx index f87be32b43fc1..a433b0b507239 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/ErroneousTransactionsRateChart/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/ErroneousTransactionsRateChart/index.tsx @@ -21,7 +21,7 @@ const tickFormatY = (y?: number) => { return asPercent(y || 0, 1); }; -export const ErroneousTransactionsRateChart = () => { +export function ErroneousTransactionsRateChart() { const { urlParams, uiFilters } = useUrlParams(); const syncedChartsProps = useChartsSync(); @@ -105,4 +105,4 @@ export const ErroneousTransactionsRateChart = () => { /> ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/charts/Legend/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/Legend/index.tsx index a00c46bcf324d..1a2a90c9fb3c3 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Legend/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Legend/index.tsx @@ -60,7 +60,7 @@ interface Props { indicator?: () => React.ReactNode; } -export const Legend: React.FC = ({ +export function Legend({ onClick, text, color, @@ -71,7 +71,7 @@ export const Legend: React.FC = ({ shape = Shape.circle, indicator, ...rest -}) => { +}: Props) { const theme = useTheme(); const indicatorColor = color || theme.eui.euiColorVis1; @@ -96,4 +96,4 @@ export const Legend: React.FC = ({ {text} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/AgentMarker.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/AgentMarker.tsx index d2dea39b83d82..64e0fe33c982f 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/AgentMarker.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/AgentMarker.tsx @@ -27,7 +27,7 @@ interface Props { mark: AgentMark; } -export const AgentMarker: React.FC = ({ mark }) => { +export function AgentMarker({ mark }: Props) { const theme = useTheme(); return ( @@ -46,4 +46,4 @@ export const AgentMarker: React.FC = ({ mark }) => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/ErrorMarker.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/ErrorMarker.tsx index d8e056deb769a..4567bc3f0f0b7 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/ErrorMarker.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/ErrorMarker.tsx @@ -53,7 +53,7 @@ function truncateMessage(errorMessage?: string) { } } -export const ErrorMarker: React.FC = ({ mark }) => { +export function ErrorMarker({ mark }: Props) { const theme = useTheme(); const { urlParams } = useUrlParams(); const [isPopoverOpen, showPopover] = useState(false); @@ -123,4 +123,4 @@ export const ErrorMarker: React.FC = ({ mark }) => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/index.tsx index 03124952c3f88..71a1639af6dcc 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/index.tsx @@ -22,7 +22,7 @@ const MarkerContainer = styled.div` bottom: 0; `; -export const Marker: React.FC = ({ mark, x }) => { +export function Marker({ mark, x }: Props) { const legendWidth = 11; return ( @@ -33,4 +33,4 @@ export const Marker: React.FC = ({ mark, x }) => { )} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/TimelineAxis.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/TimelineAxis.tsx index a9c36634381d4..5cbfcc695e012 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/TimelineAxis.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/TimelineAxis.tsx @@ -42,11 +42,11 @@ interface TimelineAxisProps { topTraceDuration: number; } -export const TimelineAxis = ({ +export function TimelineAxis({ plotValues, marks = [], topTraceDuration, -}: TimelineAxisProps) => { +}: TimelineAxisProps) { const theme = useTheme(); const { margins, tickValues, width, xDomain, xMax, xScale } = plotValues; const tickFormatter = getDurationFormatter(xMax); @@ -107,4 +107,4 @@ export const TimelineAxis = ({ }} ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/VerticalLines.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/VerticalLines.tsx index 0753cb318d3a4..5ea2e4cfedf18 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/VerticalLines.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/VerticalLines.tsx @@ -16,11 +16,11 @@ interface VerticalLinesProps { topTraceDuration: number; } -export const VerticalLines = ({ +export function VerticalLines({ topTraceDuration, plotValues, marks = [], -}: VerticalLinesProps) => { +}: VerticalLinesProps) { const { width, height, margins, xDomain, tickValues } = plotValues; const markTimes = marks @@ -63,4 +63,4 @@ export const VerticalLines = ({
); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/ChoroplethMap/ChoroplethToolTip.tsx b/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/ChoroplethMap/ChoroplethToolTip.tsx index 9d13b23904b36..69d4e8109dfbf 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/ChoroplethMap/ChoroplethToolTip.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/ChoroplethMap/ChoroplethToolTip.tsx @@ -9,11 +9,15 @@ import { i18n } from '@kbn/i18n'; import { asDuration, asInteger } from '../../../../../utils/formatters'; import { fontSizes } from '../../../../../style/variables'; -export const ChoroplethToolTip: React.FC<{ +export function ChoroplethToolTip({ + name, + value, + docCount, +}: { name: string; value: number; docCount: number; -}> = ({ name, value, docCount }) => { +}) { return (
{name}
@@ -41,4 +45,4 @@ export const ChoroplethToolTip: React.FC<{
); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/ChoroplethMap/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/ChoroplethMap/index.tsx index a9a9343dde6be..965cb2ae4f50a 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/ChoroplethMap/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/ChoroplethMap/index.tsx @@ -66,7 +66,7 @@ const getMin = (items: ChoroplethItem[]) => const getMax = (items: ChoroplethItem[]) => Math.max(...items.map((item) => item.value)); -export const ChoroplethMap: React.FC = (props) => { +export function ChoroplethMap(props: Props) { const theme = useTheme(); const { items } = props; const containerRef = useRef(null); @@ -267,4 +267,4 @@ export const ChoroplethMap: React.FC = (props) => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/DurationByCountryMap/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/DurationByCountryMap/index.tsx index 61030679f45fd..2dd3d058e98b8 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/DurationByCountryMap/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/DurationByCountryMap/index.tsx @@ -11,7 +11,7 @@ import { useAvgDurationByCountry } from '../../../../../hooks/useAvgDurationByCo import { ChoroplethMap } from '../ChoroplethMap'; -export const DurationByCountryMap: React.FC = () => { +export function DurationByCountryMap() { const { data } = useAvgDurationByCountry(); return ( @@ -30,4 +30,4 @@ export const DurationByCountryMap: React.FC = () => { ); -}; +} diff --git a/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/TransactionLineChart/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/TransactionLineChart/index.tsx index cee74c81325ba..eaad883d2f9f6 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/TransactionLineChart/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/TransactionLineChart/index.tsx @@ -30,7 +30,7 @@ interface Props { onHover?: () => void; } -const TransactionLineChart: React.FC = (props: Props) => { +function TransactionLineChart(props: Props) { const { series, tickFormatY, @@ -68,6 +68,6 @@ const TransactionLineChart: React.FC = (props: Props) => { {...(stacked ? { stackBy: 'y' } : {})} /> ); -}; +} export { TransactionLineChart }; diff --git a/x-pack/plugins/apm/public/context/ChartsSyncContext.tsx b/x-pack/plugins/apm/public/context/ChartsSyncContext.tsx index c00fc95f1f4f2..f93b69a877057 100644 --- a/x-pack/plugins/apm/public/context/ChartsSyncContext.tsx +++ b/x-pack/plugins/apm/public/context/ChartsSyncContext.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useMemo, useState } from 'react'; +import React, { ReactNode, useMemo, useState } from 'react'; import { toQuery, fromQuery } from '../components/shared/Links/url_helpers'; import { history } from '../utils/history'; import { useUrlParams } from '../hooks/useUrlParams'; @@ -17,7 +17,7 @@ const ChartsSyncContext = React.createContext<{ onSelectionEnd: (range: { start: number; end: number }) => void; } | null>(null); -const ChartsSyncContextProvider: React.FC = ({ children }) => { +function ChartsSyncContextProvider({ children }: { children: ReactNode }) { const [time, setTime] = useState(null); const { urlParams, uiFilters } = useUrlParams(); @@ -78,6 +78,6 @@ const ChartsSyncContextProvider: React.FC = ({ children }) => { }, [time, data.annotations]); return ; -}; +} export { ChartsSyncContext, ChartsSyncContextProvider }; diff --git a/x-pack/plugins/apm/public/context/LicenseContext/InvalidLicenseNotification.tsx b/x-pack/plugins/apm/public/context/LicenseContext/InvalidLicenseNotification.tsx index 481e89e09685e..1195038a6b753 100644 --- a/x-pack/plugins/apm/public/context/LicenseContext/InvalidLicenseNotification.tsx +++ b/x-pack/plugins/apm/public/context/LicenseContext/InvalidLicenseNotification.tsx @@ -6,11 +6,10 @@ import { EuiButton, EuiEmptyPrompt } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import { useApmPluginContext } from '../../hooks/useApmPluginContext'; +import { useKibanaUrl } from '../../hooks/useKibanaUrl'; export function InvalidLicenseNotification() { - const { core } = useApmPluginContext(); - const manageLicenseURL = core.http.basePath.prepend( + const manageLicenseURL = useKibanaUrl( '/app/management/stack/license_management' ); diff --git a/x-pack/plugins/apm/public/context/UrlParamsContext/MockUrlParamsContextProvider.tsx b/x-pack/plugins/apm/public/context/UrlParamsContext/MockUrlParamsContextProvider.tsx index 4e4fbabf5571a..fd01e057ac3de 100644 --- a/x-pack/plugins/apm/public/context/UrlParamsContext/MockUrlParamsContextProvider.tsx +++ b/x-pack/plugins/apm/public/context/UrlParamsContext/MockUrlParamsContextProvider.tsx @@ -21,11 +21,11 @@ interface Props { refreshTimeRange?: (time: any) => void; } -export const MockUrlParamsContextProvider = ({ +export function MockUrlParamsContextProvider({ params, children, refreshTimeRange = () => undefined, -}: Props) => { +}: Props) { const urlParams = { ...defaultUrlParams, ...params }; return ( ); -}; +} diff --git a/x-pack/plugins/apm/public/hooks/useKibanaUrl.ts b/x-pack/plugins/apm/public/hooks/useKibanaUrl.ts index 186a752f52487..b4a354c231633 100644 --- a/x-pack/plugins/apm/public/hooks/useKibanaUrl.ts +++ b/x-pack/plugins/apm/public/hooks/useKibanaUrl.ts @@ -9,7 +9,7 @@ import { useApmPluginContext } from './useApmPluginContext'; export function useKibanaUrl( /** The path to the plugin */ path: string, - /** The hash path */ hash: string + /** The hash path */ hash?: string ) { const { core } = useApmPluginContext(); return url.format({ diff --git a/x-pack/plugins/apm/public/hooks/useTransactionList.ts b/x-pack/plugins/apm/public/hooks/useTransactionList.ts index ed6bb9309a557..0ad221b95b4ff 100644 --- a/x-pack/plugins/apm/public/hooks/useTransactionList.ts +++ b/x-pack/plugins/apm/public/hooks/useTransactionList.ts @@ -4,45 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { useMemo } from 'react'; import { IUrlParams } from '../context/UrlParamsContext/types'; import { useUiFilters } from '../context/UrlParamsContext'; import { useFetcher } from './useFetcher'; import { APIReturnType } from '../services/rest/createCallApmApi'; -const getRelativeImpact = ( - impact: number, - impactMin: number, - impactMax: number -) => - Math.max( - ((impact - impactMin) / Math.max(impactMax - impactMin, 1)) * 100, - 1 - ); - type TransactionsAPIResponse = APIReturnType< '/api/apm/services/{serviceName}/transaction_groups' >; -function getWithRelativeImpact(items: TransactionsAPIResponse['items']) { - const impacts = items - .map(({ impact }) => impact) - .filter((impact) => impact !== null) as number[]; - - const impactMin = Math.min(...impacts); - const impactMax = Math.max(...impacts); - - return items.map((item) => { - return { - ...item, - impactRelative: - item.impact !== null - ? getRelativeImpact(item.impact, impactMin, impactMax) - : null, - }; - }); -} - const DEFAULT_RESPONSE: TransactionsAPIResponse = { items: [], isAggregationAccurate: true, @@ -72,16 +42,8 @@ export function useTransactionList(urlParams: IUrlParams) { [serviceName, start, end, transactionType, uiFilters] ); - const memoizedData = useMemo( - () => ({ - items: getWithRelativeImpact(data.items), - isAggregationAccurate: data.isAggregationAccurate, - bucketSize: data.bucketSize, - }), - [data] - ); return { - data: memoizedData, + data, status, error, }; diff --git a/x-pack/plugins/apm/public/utils/getRangeFromTimeSeries.ts b/x-pack/plugins/apm/public/utils/getRangeFromTimeSeries.ts index 8ec81616ccff8..71024edc9815c 100644 --- a/x-pack/plugins/apm/public/utils/getRangeFromTimeSeries.ts +++ b/x-pack/plugins/apm/public/utils/getRangeFromTimeSeries.ts @@ -7,7 +7,7 @@ import { flatten } from 'lodash'; import { TimeSeries } from '../../typings/timeseries'; -export const getRangeFromTimeSeries = (timeseries: TimeSeries[]) => { +export function getRangeFromTimeSeries(timeseries: TimeSeries[]) { const dataPoints = flatten(timeseries.map((series) => series.data)); if (dataPoints.length) { @@ -18,4 +18,4 @@ export const getRangeFromTimeSeries = (timeseries: TimeSeries[]) => { } return null; -}; +} diff --git a/x-pack/plugins/apm/public/utils/testHelpers.tsx b/x-pack/plugins/apm/public/utils/testHelpers.tsx index 8e7f987966783..418312743c324 100644 --- a/x-pack/plugins/apm/public/utils/testHelpers.tsx +++ b/x-pack/plugins/apm/public/utils/testHelpers.tsx @@ -197,9 +197,11 @@ export function mountWithTheme( tree: React.ReactElement, { darkMode = false } = {} ) { - const WrappingThemeProvider = (props: any) => ( - {props.children} - ); + function WrappingThemeProvider(props: any) { + return ( + {props.children} + ); + } return mount(tree, { wrappingComponent: WrappingThemeProvider, diff --git a/x-pack/plugins/apm/scripts/aggregate-latency-metrics/index.ts b/x-pack/plugins/apm/scripts/aggregate-latency-metrics/index.ts index 28b095335e93d..c3cf363cbec05 100644 --- a/x-pack/plugins/apm/scripts/aggregate-latency-metrics/index.ts +++ b/x-pack/plugins/apm/scripts/aggregate-latency-metrics/index.ts @@ -10,7 +10,7 @@ import pLimit from 'p-limit'; import pRetry from 'p-retry'; import { parse, format } from 'url'; import { set } from '@elastic/safer-lodash-set'; -import { unique, without, merge, flatten } from 'lodash'; +import { uniq, without, merge, flatten } from 'lodash'; import * as histogram from 'hdr-histogram-js'; import { ESSearchResponse } from '../../typings/elasticsearch'; import { @@ -114,8 +114,8 @@ export async function aggregateLatencyMetrics() { .filter(Boolean) as string[]; const fields = only.length - ? unique(only) - : without(unique([...include, ...defaultFields]), ...exclude); + ? uniq(only) + : without(uniq([...include, ...defaultFields]), ...exclude); const globalFilter = argv.filter ? JSON.parse(String(argv.filter)) : {}; diff --git a/x-pack/plugins/apm/scripts/shared/read-kibana-config.ts b/x-pack/plugins/apm/scripts/shared/read-kibana-config.ts index bc5f1afc63cac..fe226c8ab27d2 100644 --- a/x-pack/plugins/apm/scripts/shared/read-kibana-config.ts +++ b/x-pack/plugins/apm/scripts/shared/read-kibana-config.ts @@ -6,7 +6,7 @@ import path from 'path'; import fs from 'fs'; import yaml from 'js-yaml'; -import { identity, pick } from 'lodash'; +import { identity, pickBy } from 'lodash'; export type KibanaConfig = ReturnType; @@ -22,7 +22,7 @@ export const readKibanaConfig = () => { ) ) || {}) as {}; - const cliEsCredentials = pick( + const cliEsCredentials = pickBy( { 'elasticsearch.username': process.env.ELASTICSEARCH_USERNAME, 'elasticsearch.password': process.env.ELASTICSEARCH_PASSWORD, diff --git a/x-pack/plugins/apm/scripts/upload-telemetry-data/index.ts b/x-pack/plugins/apm/scripts/upload-telemetry-data/index.ts index a44fad82f20e6..10651d97f3c3d 100644 --- a/x-pack/plugins/apm/scripts/upload-telemetry-data/index.ts +++ b/x-pack/plugins/apm/scripts/upload-telemetry-data/index.ts @@ -87,13 +87,15 @@ async function uploadData() { return client.search(body as any).then((res) => res.body); }, indicesStats: (body) => { - return client.indices.stats(body as any); + return client.indices.stats(body as any).then((res) => res.body); }, transportRequest: ((params) => { - return client.transport.request({ - method: params.method, - path: params.path, - }); + return client.transport + .request({ + method: params.method, + path: params.path, + }) + .then((res) => res.body); }) as CollectTelemetryParams['transportRequest'], }, }); diff --git a/x-pack/plugins/apm/server/feature.ts b/x-pack/plugins/apm/server/feature.ts index 80f722bae0868..971bc96234376 100644 --- a/x-pack/plugins/apm/server/feature.ts +++ b/x-pack/plugins/apm/server/feature.ts @@ -5,6 +5,7 @@ */ import { i18n } from '@kbn/i18n'; +import { AlertType } from '../common/alert_types'; export const APM_FEATURE = { id: 'apm', @@ -16,57 +17,43 @@ export const APM_FEATURE = { navLinkId: 'apm', app: ['apm', 'kibana'], catalogue: ['apm'], + management: { + insightsAndAlerting: ['triggersActions'], + }, + alerting: Object.values(AlertType), // see x-pack/plugins/features/common/feature_kibana_privileges.ts privileges: { all: { app: ['apm', 'kibana'], - api: [ - 'apm', - 'apm_write', - 'actions-read', - 'actions-all', - 'alerting-read', - 'alerting-all', - ], + api: ['apm', 'apm_write'], catalogue: ['apm'], savedObject: { - all: ['alert', 'action', 'action_task_params'], + all: [], read: [], }, - ui: [ - 'show', - 'save', - 'alerting:show', - 'actions:show', - 'alerting:save', - 'actions:save', - 'alerting:delete', - 'actions:delete', - ], + alerting: { + all: Object.values(AlertType), + }, + management: { + insightsAndAlerting: ['triggersActions'], + }, + ui: ['show', 'save', 'alerting:show', 'alerting:save'], }, read: { app: ['apm', 'kibana'], - api: [ - 'apm', - 'actions-read', - 'actions-all', - 'alerting-read', - 'alerting-all', - ], + api: ['apm'], catalogue: ['apm'], savedObject: { - all: ['alert', 'action', 'action_task_params'], + all: [], read: [], }, - ui: [ - 'show', - 'alerting:show', - 'actions:show', - 'alerting:save', - 'actions:save', - 'alerting:delete', - 'actions:delete', - ], + alerting: { + all: Object.values(AlertType), + }, + management: { + insightsAndAlerting: ['triggersActions'], + }, + ui: ['show', 'alerting:show', 'alerting:save'], }, }, }; diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts index 1d14c509274a8..a922457b14cea 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts +++ b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts @@ -157,7 +157,7 @@ export function registerTransactionDurationAlertType({ const { agg } = response.aggregations; - const value = 'values' in agg ? agg.values[0] : agg?.value; + const value = 'values' in agg ? Object.values(agg.values)[0] : agg?.value; if (value && value > alertParams.threshold * 1000) { const alertInstance = services.alertInstanceFactory( diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts index 2836cf100a432..6f4f92c6833f7 100644 --- a/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts +++ b/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts @@ -5,8 +5,12 @@ */ import { Observable } from 'rxjs'; import { take } from 'rxjs/operators'; -import { CoreSetup, Logger } from 'src/core/server'; import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; +import { + CoreSetup, + Logger, + SavedObjectsErrorHelpers, +} from '../../../../../../src/core/server'; import { APMConfig } from '../..'; import { TaskManagerSetupContract, @@ -110,7 +114,7 @@ export async function createApmTelemetry({ return data; } catch (err) { - if (err.output?.statusCode === 404) { + if (SavedObjectsErrorHelpers.isNotFoundError(err)) { // task has not run yet, so no saved object to return return {}; } diff --git a/x-pack/plugins/apm/server/lib/metrics/fetch_and_transform_metrics.ts b/x-pack/plugins/apm/server/lib/metrics/fetch_and_transform_metrics.ts index 6de2728ee4366..895920a9b6c7d 100644 --- a/x-pack/plugins/apm/server/lib/metrics/fetch_and_transform_metrics.ts +++ b/x-pack/plugins/apm/server/lib/metrics/fetch_and_transform_metrics.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Unionize } from 'utility-types'; +import { Unionize, Overwrite } from 'utility-types'; +import { ESSearchRequest } from '../../../typings/elasticsearch'; import { Setup, SetupTimeRange, @@ -17,14 +18,28 @@ import { getMetricsProjection } from '../../../common/projections/metrics'; import { mergeProjection } from '../../../common/projections/util/merge_projection'; import { AggregationOptionsByType } from '../../../typings/elasticsearch/aggregations'; -interface Aggs { - [key: string]: Unionize<{ - min: AggregationOptionsByType['min']; - max: AggregationOptionsByType['max']; - sum: AggregationOptionsByType['sum']; - avg: AggregationOptionsByType['avg']; - }>; -} +type MetricsAggregationMap = Unionize<{ + min: AggregationOptionsByType['min']; + max: AggregationOptionsByType['max']; + sum: AggregationOptionsByType['sum']; + avg: AggregationOptionsByType['avg']; +}>; + +type MetricAggs = Record; + +export type GenericMetricsRequest = Overwrite< + ESSearchRequest, + { + body: { + aggs: { + timeseriesData: { + date_histogram: AggregationOptionsByType['date_histogram']; + aggs: MetricAggs; + }; + } & MetricAggs; + }; + } +>; interface Filter { exists?: { @@ -35,7 +50,7 @@ interface Filter { }; } -export async function fetchAndTransformMetrics({ +export async function fetchAndTransformMetrics({ setup, serviceName, serviceNodeName, @@ -58,7 +73,7 @@ export async function fetchAndTransformMetrics({ serviceNodeName, }); - const params = mergeProjection(projection, { + const params: GenericMetricsRequest = mergeProjection(projection, { body: { size: 0, query: { diff --git a/x-pack/plugins/apm/server/lib/metrics/transform_metrics_chart.ts b/x-pack/plugins/apm/server/lib/metrics/transform_metrics_chart.ts index affb7c2a12075..a191d5400e36c 100644 --- a/x-pack/plugins/apm/server/lib/metrics/transform_metrics_chart.ts +++ b/x-pack/plugins/apm/server/lib/metrics/transform_metrics_chart.ts @@ -4,40 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ import theme from '@elastic/eui/dist/eui_theme_light.json'; -import { Unionize, Overwrite } from 'utility-types'; import { ChartBase } from './types'; -import { - ESSearchResponse, - ESSearchRequest, -} from '../../../typings/elasticsearch'; -import { AggregationOptionsByType } from '../../../typings/elasticsearch/aggregations'; +import { ESSearchResponse } from '../../../typings/elasticsearch'; import { getVizColorForIndex } from '../../../common/viz_colors'; +import { GenericMetricsRequest } from './fetch_and_transform_metrics'; export type GenericMetricsChart = ReturnType< typeof transformDataToMetricsChart >; -interface MetricsAggregationMap { - min: AggregationOptionsByType['min']; - max: AggregationOptionsByType['max']; - sum: AggregationOptionsByType['sum']; - avg: AggregationOptionsByType['avg']; -} - -type GenericMetricsRequest = Overwrite< - ESSearchRequest, - { - body: { - aggs: { - timeseriesData: { - date_histogram: AggregationOptionsByType['date_histogram']; - aggs: Record>; - }; - } & Record>; - }; - } ->; - export function transformDataToMetricsChart( result: ESSearchResponse, chartBase: ChartBase @@ -51,11 +26,7 @@ export function transformDataToMetricsChart( yUnit: chartBase.yUnit, noHits: hits.total.value === 0, series: Object.keys(chartBase.series).map((seriesKey, i) => { - const overallValue = (aggregations?.[seriesKey] as - | { - value: number | null; - } - | undefined)?.value; + const overallValue = aggregations?.[seriesKey]?.value; return { title: chartBase.series[seriesKey].title, @@ -66,7 +37,7 @@ export function transformDataToMetricsChart( overallValue, data: timeseriesData?.buckets.map((bucket) => { - const { value } = bucket[seriesKey] as { value: number | null }; + const { value } = bucket[seriesKey]; const y = value === null || isNaN(value) ? null : value; return { x: bucket.key, diff --git a/x-pack/plugins/apm/server/lib/observability_overview/has_data.ts b/x-pack/plugins/apm/server/lib/observability_overview/has_data.ts index 73cc2d273ec69..fc7445ab4a225 100644 --- a/x-pack/plugins/apm/server/lib/observability_overview/has_data.ts +++ b/x-pack/plugins/apm/server/lib/observability_overview/has_data.ts @@ -3,6 +3,8 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import { PROCESSOR_EVENT } from '../../../common/elasticsearch_fieldnames'; +import { ProcessorEvent } from '../../../common/processor_event'; import { Setup } from '../helpers/setup_request'; export async function hasData({ setup }: { setup: Setup }) { @@ -15,7 +17,24 @@ export async function hasData({ setup }: { setup: Setup }) { indices['apm_oss.metricsIndices'], ], terminateAfter: 1, - size: 0, + body: { + size: 0, + query: { + bool: { + filter: [ + { + terms: { + [PROCESSOR_EVENT]: [ + ProcessorEvent.error, + ProcessorEvent.metric, + ProcessorEvent.transaction, + ], + }, + }, + ], + }, + }, + }, }; const response = await client.search(params); diff --git a/x-pack/plugins/apm/server/lib/services/get_services/get_services_items_stats.ts b/x-pack/plugins/apm/server/lib/services/get_services/get_services_items_stats.ts index c28bcad841ffd..de699028f5675 100644 --- a/x-pack/plugins/apm/server/lib/services/get_services/get_services_items_stats.ts +++ b/x-pack/plugins/apm/server/lib/services/get_services/get_services_items_stats.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { arrayUnionToCallable } from '../../../../common/utils/array_union_to_callable'; import { PROCESSOR_EVENT, TRANSACTION_DURATION, @@ -187,7 +186,7 @@ export const getTransactionRates = async ({ const deltaAsMinutes = getDeltaAsMinutes(setup); - return arrayUnionToCallable(aggregations.services.buckets).map((bucket) => { + return aggregations.services.buckets.map((bucket) => { const transactionsPerMinute = bucket.doc_count / deltaAsMinutes; return { serviceName: bucket.key as string, diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/fetcher.test.ts.snap b/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/fetcher.test.ts.snap deleted file mode 100644 index b354d3ed1f88d..0000000000000 --- a/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/fetcher.test.ts.snap +++ /dev/null @@ -1,228 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`transactionGroupsFetcher type: top_traces should call client.search with correct query 1`] = ` -Array [ - Array [ - Object { - "body": Object { - "aggs": Object { - "transaction_groups": Object { - "aggs": Object { - "avg": Object { - "avg": Object { - "field": "transaction.duration.us", - }, - }, - "p95": Object { - "percentiles": Object { - "field": "transaction.duration.us", - "hdr": Object { - "number_of_significant_value_digits": 2, - }, - "percents": Array [ - 95, - ], - }, - }, - "sample": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "_score": "desc", - }, - Object { - "@timestamp": Object { - "order": "desc", - }, - }, - ], - }, - }, - "sum": Object { - "sum": Object { - "field": "transaction.duration.us", - }, - }, - }, - "composite": Object { - "size": 10000, - "sources": Array [ - Object { - "service": Object { - "terms": Object { - "field": "service.name", - }, - }, - }, - Object { - "transaction": Object { - "terms": Object { - "field": "transaction.name", - }, - }, - }, - ], - }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 1528113600000, - "lte": 1528977600000, - }, - }, - }, - Object { - "term": Object { - "processor.event": "transaction", - }, - }, - Object { - "term": Object { - "service.environment": "test", - }, - }, - ], - "must_not": Array [ - Object { - "exists": Object { - "field": "parent.id", - }, - }, - ], - "should": Array [ - Object { - "term": Object { - "transaction.sampled": true, - }, - }, - ], - }, - }, - "size": 0, - }, - "index": "myIndex", - }, - ], -] -`; - -exports[`transactionGroupsFetcher type: top_transactions should call client.search with correct query 1`] = ` -Array [ - Array [ - Object { - "body": Object { - "aggs": Object { - "transaction_groups": Object { - "aggs": Object { - "avg": Object { - "avg": Object { - "field": "transaction.duration.us", - }, - }, - "p95": Object { - "percentiles": Object { - "field": "transaction.duration.us", - "hdr": Object { - "number_of_significant_value_digits": 2, - }, - "percents": Array [ - 95, - ], - }, - }, - "sample": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "_score": "desc", - }, - Object { - "@timestamp": Object { - "order": "desc", - }, - }, - ], - }, - }, - "sum": Object { - "sum": Object { - "field": "transaction.duration.us", - }, - }, - }, - "composite": Object { - "size": 101, - "sources": Array [ - Object { - "transaction": Object { - "terms": Object { - "field": "transaction.name", - }, - }, - }, - ], - }, - }, - "transactions": Object { - "terms": Object { - "field": "transaction.name", - }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 1528113600000, - "lte": 1528977600000, - }, - }, - }, - Object { - "term": Object { - "processor.event": "transaction", - }, - }, - Object { - "term": Object { - "transaction.type": "request", - }, - }, - Object { - "term": Object { - "service.name": "opbeans-node", - }, - }, - Object { - "term": Object { - "service.environment": "test", - }, - }, - ], - "should": Array [ - Object { - "term": Object { - "transaction.sampled": true, - }, - }, - ], - }, - }, - "size": 0, - }, - "index": "myIndex", - }, - ], -] -`; diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/queries.test.ts.snap index 884a7d18cc4d4..deca46f4ebd0c 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/queries.test.ts.snap +++ b/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/queries.test.ts.snap @@ -1,220 +1,479 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`transaction group queries fetches top traces 1`] = ` -Object { - "body": Object { - "aggs": Object { - "transaction_groups": Object { - "aggs": Object { - "avg": Object { - "avg": Object { - "field": "transaction.duration.us", - }, - }, - "p95": Object { - "percentiles": Object { - "field": "transaction.duration.us", - "hdr": Object { - "number_of_significant_value_digits": 2, +Array [ + Object { + "body": Object { + "aggs": Object { + "transaction_groups": Object { + "aggs": Object { + "sample": Object { + "top_hits": Object { + "size": 1, }, - "percents": Array [ - 95, - ], }, }, - "sample": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "_score": "desc", + "composite": Object { + "size": 10000, + "sources": Array [ + Object { + "service.name": Object { + "terms": Object { + "field": "service.name", + }, }, - Object { - "@timestamp": Object { - "order": "desc", + }, + Object { + "transaction.name": Object { + "terms": Object { + "field": "transaction.name", }, }, - ], + }, + ], + }, + }, + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 1528113600000, + "lte": 1528977600000, + }, + }, + }, + Object { + "term": Object { + "processor.event": "transaction", + }, + }, + Object { + "term": Object { + "my.custom.ui.filter": "foo-bar", + }, + }, + ], + "must_not": Array [ + Object { + "exists": Object { + "field": "parent.id", + }, + }, + ], + "should": Array [ + Object { + "term": Object { + "transaction.sampled": true, + }, }, + ], + }, + }, + "sort": Array [ + Object { + "_score": "desc", + }, + Object { + "@timestamp": Object { + "order": "desc", }, - "sum": Object { - "sum": Object { - "field": "transaction.duration.us", + }, + ], + }, + "index": "myIndex", + "size": 0, + }, + Object { + "body": Object { + "aggs": Object { + "transaction_groups": Object { + "aggs": Object { + "avg": Object { + "avg": Object { + "field": "transaction.duration.us", + }, }, }, + "composite": Object { + "size": 10000, + "sources": Array [ + Object { + "service.name": Object { + "terms": Object { + "field": "service.name", + }, + }, + }, + Object { + "transaction.name": Object { + "terms": Object { + "field": "transaction.name", + }, + }, + }, + ], + }, }, - "composite": Object { - "size": 10000, - "sources": Array [ + }, + "query": Object { + "bool": Object { + "filter": Array [ Object { - "service": Object { - "terms": Object { - "field": "service.name", + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 1528113600000, + "lte": 1528977600000, }, }, }, Object { - "transaction": Object { - "terms": Object { - "field": "transaction.name", - }, + "term": Object { + "processor.event": "transaction", + }, + }, + Object { + "term": Object { + "my.custom.ui.filter": "foo-bar", + }, + }, + ], + "must_not": Array [ + Object { + "exists": Object { + "field": "parent.id", }, }, ], }, }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 1528113600000, - "lte": 1528977600000, + "index": "myIndex", + "size": 0, + }, + Object { + "body": Object { + "aggs": Object { + "transaction_groups": Object { + "aggs": Object { + "sum": Object { + "sum": Object { + "field": "transaction.duration.us", }, }, }, - Object { - "term": Object { - "processor.event": "transaction", - }, + "composite": Object { + "size": 10000, + "sources": Array [ + Object { + "service.name": Object { + "terms": Object { + "field": "service.name", + }, + }, + }, + Object { + "transaction.name": Object { + "terms": Object { + "field": "transaction.name", + }, + }, + }, + ], }, - Object { - "term": Object { - "my.custom.ui.filter": "foo-bar", + }, + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 1528113600000, + "lte": 1528977600000, + }, + }, }, - }, - ], - "must_not": Array [ - Object { - "exists": Object { - "field": "parent.id", + Object { + "term": Object { + "processor.event": "transaction", + }, }, - }, - ], - "should": Array [ - Object { - "term": Object { - "transaction.sampled": true, + Object { + "term": Object { + "my.custom.ui.filter": "foo-bar", + }, }, - }, - ], + ], + "must_not": Array [ + Object { + "exists": Object { + "field": "parent.id", + }, + }, + ], + }, }, }, + "index": "myIndex", "size": 0, }, - "index": "myIndex", -} +] `; exports[`transaction group queries fetches top transactions 1`] = ` -Object { - "body": Object { - "aggs": Object { - "transaction_groups": Object { - "aggs": Object { - "avg": Object { - "avg": Object { - "field": "transaction.duration.us", - }, - }, - "p95": Object { - "percentiles": Object { - "field": "transaction.duration.us", - "hdr": Object { - "number_of_significant_value_digits": 2, +Array [ + Object { + "body": Object { + "aggs": Object { + "transaction_groups": Object { + "aggs": Object { + "sample": Object { + "top_hits": Object { + "size": 1, }, - "percents": Array [ - 95, - ], }, }, - "sample": Object { - "top_hits": Object { - "size": 1, - "sort": Array [ - Object { - "_score": "desc", - }, - Object { - "@timestamp": Object { - "order": "desc", - }, + "terms": Object { + "field": "transaction.name", + "size": 101, + }, + }, + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 1528113600000, + "lte": 1528977600000, }, - ], + }, }, + Object { + "term": Object { + "processor.event": "transaction", + }, + }, + Object { + "term": Object { + "transaction.type": "bar", + }, + }, + Object { + "term": Object { + "service.name": "foo", + }, + }, + Object { + "term": Object { + "my.custom.ui.filter": "foo-bar", + }, + }, + ], + "should": Array [ + Object { + "term": Object { + "transaction.sampled": true, + }, + }, + ], + }, + }, + "sort": Array [ + Object { + "_score": "desc", + }, + Object { + "@timestamp": Object { + "order": "desc", }, - "sum": Object { - "sum": Object { - "field": "transaction.duration.us", + }, + ], + }, + "index": "myIndex", + "size": 0, + }, + Object { + "body": Object { + "aggs": Object { + "transaction_groups": Object { + "aggs": Object { + "avg": Object { + "avg": Object { + "field": "transaction.duration.us", + }, }, }, + "terms": Object { + "field": "transaction.name", + "size": 101, + }, }, - "composite": Object { - "size": 101, - "sources": Array [ + }, + "query": Object { + "bool": Object { + "filter": Array [ Object { - "transaction": Object { - "terms": Object { - "field": "transaction.name", + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 1528113600000, + "lte": 1528977600000, }, }, }, + Object { + "term": Object { + "processor.event": "transaction", + }, + }, + Object { + "term": Object { + "transaction.type": "bar", + }, + }, + Object { + "term": Object { + "service.name": "foo", + }, + }, + Object { + "term": Object { + "my.custom.ui.filter": "foo-bar", + }, + }, ], }, }, - "transactions": Object { - "terms": Object { - "field": "transaction.name", + }, + "index": "myIndex", + "size": 0, + }, + Object { + "body": Object { + "aggs": Object { + "transaction_groups": Object { + "aggs": Object { + "sum": Object { + "sum": Object { + "field": "transaction.duration.us", + }, + }, + }, + "terms": Object { + "field": "transaction.name", + "size": 101, + }, + }, + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 1528113600000, + "lte": 1528977600000, + }, + }, + }, + Object { + "term": Object { + "processor.event": "transaction", + }, + }, + Object { + "term": Object { + "transaction.type": "bar", + }, + }, + Object { + "term": Object { + "service.name": "foo", + }, + }, + Object { + "term": Object { + "my.custom.ui.filter": "foo-bar", + }, + }, + ], }, }, }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "range": Object { - "@timestamp": Object { - "format": "epoch_millis", - "gte": 1528113600000, - "lte": 1528977600000, + "index": "myIndex", + "size": 0, + }, + Object { + "body": Object { + "aggs": Object { + "transaction_groups": Object { + "aggs": Object { + "p95": Object { + "percentiles": Object { + "field": "transaction.duration.us", + "hdr": Object { + "number_of_significant_value_digits": 2, + }, + "percents": Array [ + 95, + ], }, }, }, - Object { - "term": Object { - "processor.event": "transaction", - }, + "terms": Object { + "field": "transaction.name", + "size": 101, }, - Object { - "term": Object { - "transaction.type": "bar", + }, + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@timestamp": Object { + "format": "epoch_millis", + "gte": 1528113600000, + "lte": 1528977600000, + }, + }, }, - }, - Object { - "term": Object { - "service.name": "foo", + Object { + "term": Object { + "processor.event": "transaction", + }, }, - }, - Object { - "term": Object { - "my.custom.ui.filter": "foo-bar", + Object { + "term": Object { + "transaction.type": "bar", + }, }, - }, - ], - "should": Array [ - Object { - "term": Object { - "transaction.sampled": true, + Object { + "term": Object { + "service.name": "foo", + }, }, - }, - ], + Object { + "term": Object { + "my.custom.ui.filter": "foo-bar", + }, + }, + ], + }, }, }, + "index": "myIndex", "size": 0, }, - "index": "myIndex", -} +] `; diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/transform.test.ts.snap b/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/transform.test.ts.snap deleted file mode 100644 index 66b805ab2efc1..0000000000000 --- a/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/transform.test.ts.snap +++ /dev/null @@ -1,2822 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`transactionGroupsTransformer should match snapshot 1`] = ` -Array [ - Object { - "averageResponseTime": 48021.972616494, - "impact": 100, - "name": "GET /api", - "p95": 67138.18364917398, - "sample": Object { - "@timestamp": "2018-11-18T20:53:44.070Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 5176, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3756, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "accept": "*/*", - "accept-encoding": "gzip, deflate", - "connection": "keep-alive", - "elastic-apm-traceparent": "00-86c68779d8a65b06fb78e770ffc436a5-4aaea53dc1791183-01", - "host": "opbeans-node:3000", - "user-agent": "python-requests/2.20.0", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.6", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/types/3", - "hostname": "opbeans-node", - "pathname": "/api/types/3", - "port": "3000", - "protocol": "http:", - "raw": "/api/types/3", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-type": "application/json;charset=UTF-8", - "date": "Sun, 18 Nov 2018 20:53:43 GMT", - "transfer-encoding": "chunked", - "x-powered-by": "Express", - }, - "status_code": 404, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "parent": Object { - "id": "4aaea53dc1791183", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574424070007, - }, - "trace": Object { - "id": "86c68779d8a65b06fb78e770ffc436a5", - }, - "transaction": Object { - "duration": Object { - "us": 8684, - }, - "id": "a78bca581dcd8ff8", - "name": "GET /api", - "result": "HTTP 4xx", - "sampled": true, - "span_count": Object { - "started": 1, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 691926.3157894736, - }, - Object { - "averageResponseTime": 2651.8784461553205, - "impact": 15.770246496477105, - "name": "GET static file", - "p95": 6140.579335038363, - "sample": Object { - "@timestamp": "2018-11-18T20:53:43.304Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3756, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "accept": "*/*", - "host": "opbeans-node:3000", - "user-agent": "curl/7.38.0", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/", - "hostname": "opbeans-node", - "pathname": "/", - "port": "3000", - "protocol": "http:", - "raw": "/", - }, - }, - "response": Object { - "headers": Object { - "accept-ranges": "bytes", - "cache-control": "public, max-age=0", - "connection": "keep-alive", - "content-length": "640", - "content-type": "text/html; charset=UTF-8", - "date": "Sun, 18 Nov 2018 20:53:43 GMT", - "etag": "W/\\"280-1670775e878\\"", - "last-modified": "Mon, 12 Nov 2018 10:27:07 GMT", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574423304006, - }, - "trace": Object { - "id": "b303d2a4a007946b63b9db7fafe639a0", - }, - "transaction": Object { - "duration": Object { - "us": 1801, - }, - "id": "2869c13633534be5", - "name": "GET static file", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 0, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 1977031.5789473683, - }, - Object { - "averageResponseTime": 32554.36257814184, - "impact": 14.344171563678346, - "name": "GET /api/stats", - "p95": 59356.73611111111, - "sample": Object { - "@timestamp": "2018-11-18T20:53:42.560Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 207, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3756, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "accept": "*/*", - "accept-encoding": "gzip, deflate", - "connection": "keep-alive", - "elastic-apm-traceparent": "00-63ccc3b0929dafb7f2fbcabdc7f7af25-821a787e73ab1563-01", - "host": "opbeans-node:3000", - "if-none-match": "W/\\"77-uxKJrX5GSMJJWTKh3orUFAEVxSs\\"", - "referer": "http://opbeans-node:3000/dashboard", - "user-agent": "Chromeless 1.4.0", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.7", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/stats", - "hostname": "opbeans-node", - "pathname": "/api/stats", - "port": "3000", - "protocol": "http:", - "raw": "/api/stats", - }, - }, - "response": Object { - "headers": Object { - "connection": "keep-alive", - "date": "Sun, 18 Nov 2018 20:53:42 GMT", - "etag": "W/\\"77-uxKJrX5GSMJJWTKh3orUFAEVxSs\\"", - "x-powered-by": "Express", - }, - "status_code": 304, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "parent": Object { - "id": "821a787e73ab1563", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574422560002, - }, - "trace": Object { - "id": "63ccc3b0929dafb7f2fbcabdc7f7af25", - }, - "transaction": Object { - "duration": Object { - "us": 28753, - }, - "id": "fb754e7628da2fb5", - "name": "GET /api/stats", - "result": "HTTP 3xx", - "sampled": true, - "span_count": Object { - "started": 7, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 146494.73684210525, - }, - Object { - "averageResponseTime": 32159.926322043968, - "impact": 10.27904952170656, - "name": "GET /api/customers", - "p95": 59845.85714285714, - "sample": Object { - "@timestamp": "2018-11-18T20:53:21.180Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 2531, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3710, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "accept": "*/*", - "accept-encoding": "gzip, deflate", - "connection": "keep-alive", - "elastic-apm-traceparent": "00-541025da8ecc2f51f21c1a4ad6992b77-ca18d9d4c3879519-01", - "host": "opbeans-node:3000", - "user-agent": "python-requests/2.20.0", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.6", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/customers", - "hostname": "opbeans-node", - "pathname": "/api/customers", - "port": "3000", - "protocol": "http:", - "raw": "/api/customers", - }, - }, - "response": Object { - "headers": Object { - "connection": "keep-alive", - "content-length": "186769", - "content-type": "application/json; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:53:21 GMT", - "etag": "W/\\"2d991-yG3J8W/roH7fSxXTudZrO27Ax9s\\"", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "parent": Object { - "id": "ca18d9d4c3879519", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574401180002, - }, - "trace": Object { - "id": "541025da8ecc2f51f21c1a4ad6992b77", - }, - "transaction": Object { - "duration": Object { - "us": 18077, - }, - "id": "94852b9dd1075982", - "name": "GET /api/customers", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 2, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 106294.73684210525, - }, - Object { - "averageResponseTime": 33265.03326147213, - "impact": 10.256357027376065, - "name": "GET /api/orders", - "p95": 58827.489999999976, - "sample": Object { - "@timestamp": "2018-11-18T20:53:40.973Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 408, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3756, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "connection": "close", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/orders", - "hostname": "opbeans-node", - "pathname": "/api/orders", - "port": "3000", - "protocol": "http:", - "raw": "/api/orders", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-length": "103612", - "content-type": "application/json; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:53:40 GMT", - "etag": "W/\\"194bc-cOw6+iRf7XCeqMXHrle3IOig7tY\\"", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574420973006, - }, - "trace": Object { - "id": "0afce85f593cbbdd09949936fe964f0f", - }, - "transaction": Object { - "duration": Object { - "us": 23040, - }, - "id": "89f200353eb50539", - "name": "GET /api/orders", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 2, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 102536.84210526315, - }, - Object { - "averageResponseTime": 27516.89144558744, - "impact": 9.651458992731666, - "name": "GET /api/products/top", - "p95": 56064.679999999986, - "sample": Object { - "@timestamp": "2018-11-18T20:52:57.316Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 5113, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3686, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "accept": "*/*", - "accept-encoding": "gzip, deflate", - "connection": "keep-alive", - "elastic-apm-traceparent": "00-74f12e705936d66350f4741ebeb55189-fcebe94cd2136215-01", - "host": "opbeans-node:3000", - "referer": "http://opbeans-node:3000/dashboard", - "user-agent": "Chromeless 1.4.0", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.7", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/products/top", - "hostname": "opbeans-node", - "pathname": "/api/products/top", - "port": "3000", - "protocol": "http:", - "raw": "/api/products/top", - }, - }, - "response": Object { - "headers": Object { - "connection": "keep-alive", - "content-length": "282", - "content-type": "application/json; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:52:57 GMT", - "etag": "W/\\"11a-lcI9zuMZYYsDRpEZgYqDYr96cKM\\"", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "parent": Object { - "id": "fcebe94cd2136215", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574377316005, - }, - "trace": Object { - "id": "74f12e705936d66350f4741ebeb55189", - }, - "transaction": Object { - "duration": Object { - "us": 48781, - }, - "id": "be4bd5475d5d9e6f", - "name": "GET /api/products/top", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 4, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 116652.63157894736, - }, - Object { - "averageResponseTime": 12683.190864600327, - "impact": 4.4239778504968, - "name": "GET /api/products", - "p95": 35009.67999999999, - "sample": Object { - "@timestamp": "2018-11-18T20:53:43.477Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 2857, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3756, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "connection": "close", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/products", - "hostname": "opbeans-node", - "pathname": "/api/products", - "port": "3000", - "protocol": "http:", - "raw": "/api/products", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-length": "1023", - "content-type": "application/json; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:53:43 GMT", - "etag": "W/\\"3ff-VyOxcDApb+a/lnjkm9FeTOGSDrs\\"", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574423477006, - }, - "trace": Object { - "id": "bee00a8efb523ca4b72adad57f7caba3", - }, - "transaction": Object { - "duration": Object { - "us": 6915, - }, - "id": "d8fc6d3b8707b64c", - "name": "GET /api/products", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 2, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 116147.36842105263, - }, - Object { - "averageResponseTime": 255966.30555555556, - "impact": 4.3693406535517445, - "name": "POST /api/orders", - "p95": 320238.5, - "sample": Object { - "@timestamp": "2018-11-18T20:43:32.010Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 4669, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 2413, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "body": "[REDACTED]", - "headers": Object { - "accept": "application/json", - "connection": "close", - "content-length": "129", - "content-type": "application/json", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "POST", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/orders", - "hostname": "opbeans-node", - "pathname": "/api/orders", - "port": "3000", - "protocol": "http:", - "raw": "/api/orders", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-length": "13", - "content-type": "application/json; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:43:32 GMT", - "etag": "W/\\"d-g9K2iK4ordyN88lGL4LmPlYNfhc\\"", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542573812010006, - }, - "trace": Object { - "id": "2b1252a338249daeecf6afb0c236e31b", - }, - "transaction": Object { - "duration": Object { - "us": 291572, - }, - "id": "2c9f39e9ec4a0111", - "name": "POST /api/orders", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 16, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 5684.210526315789, - }, - Object { - "averageResponseTime": 17189.329210275926, - "impact": 3.424381787142002, - "name": "GET /api/products/:id/customers", - "p95": 39284.79999999999, - "sample": Object { - "@timestamp": "2018-11-18T20:48:24.769Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 1735, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3100, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "accept": "*/*", - "accept-encoding": "gzip, deflate", - "connection": "keep-alive", - "elastic-apm-traceparent": "00-28f178c354d17f400dea04bc4a7b3c57-68f5d1607cac7779-01", - "host": "opbeans-node:3000", - "user-agent": "python-requests/2.20.0", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.6", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/products/2/customers", - "hostname": "opbeans-node", - "pathname": "/api/products/2/customers", - "port": "3000", - "protocol": "http:", - "raw": "/api/products/2/customers", - }, - }, - "response": Object { - "headers": Object { - "connection": "keep-alive", - "content-length": "186570", - "content-type": "application/json; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:48:24 GMT", - "etag": "W/\\"2d8ca-Z9NzuHyGyxwtzpOkcIxBvzm24iw\\"", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "parent": Object { - "id": "68f5d1607cac7779", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574104769029, - }, - "trace": Object { - "id": "28f178c354d17f400dea04bc4a7b3c57", - }, - "transaction": Object { - "duration": Object { - "us": 49338, - }, - "id": "2a87ae20ad04ee0c", - "name": "GET /api/products/:id/customers", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 1, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 66378.94736842105, - }, - Object { - "averageResponseTime": 11257.757916666667, - "impact": 2.558180605569336, - "name": "GET /api/types", - "p95": 35222.944444444445, - "sample": Object { - "@timestamp": "2018-11-18T20:53:44.978Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 2193, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3756, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "connection": "close", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/types", - "hostname": "opbeans-node", - "pathname": "/api/types", - "port": "3000", - "protocol": "http:", - "raw": "/api/types", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-length": "112", - "content-type": "application/json; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:53:44 GMT", - "etag": "W/\\"70-1z6hT7P1WHgBgS/BeUEVeHhOCQU\\"", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574424978005, - }, - "trace": Object { - "id": "0d84126973411c19b470f2d9eea958d3", - }, - "transaction": Object { - "duration": Object { - "us": 7891, - }, - "id": "0f10668e4fb3adc7", - "name": "GET /api/types", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 2, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 75789.47368421052, - }, - Object { - "averageResponseTime": 3504.5108924806746, - "impact": 2.3600993453143766, - "name": "GET *", - "p95": 11431.738095238095, - "sample": Object { - "@timestamp": "2018-11-18T20:53:42.493Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 6446, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3756, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", - "accept-encoding": "gzip, deflate", - "connection": "keep-alive", - "host": "opbeans-node:3000", - "if-modified-since": "Mon, 12 Nov 2018 10:27:07 GMT", - "if-none-match": "W/\\"280-1670775e878\\"", - "upgrade-insecure-requests": "1", - "user-agent": "Chromeless 1.4.0", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.7", - }, - "url": Object { - "full": "http://opbeans-node:3000/dashboard", - "hostname": "opbeans-node", - "pathname": "/dashboard", - "port": "3000", - "protocol": "http:", - "raw": "/dashboard", - }, - }, - "response": Object { - "headers": Object { - "accept-ranges": "bytes", - "cache-control": "public, max-age=0", - "connection": "keep-alive", - "date": "Sun, 18 Nov 2018 20:53:42 GMT", - "etag": "W/\\"280-1670775e878\\"", - "last-modified": "Mon, 12 Nov 2018 10:27:07 GMT", - "x-powered-by": "Express", - }, - "status_code": 304, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574422493006, - }, - "trace": Object { - "id": "7efb6ade88cdea20cd96ca482681cde7", - }, - "transaction": Object { - "duration": Object { - "us": 1901, - }, - "id": "f5fc4621949b63fb", - "name": "GET *", - "result": "HTTP 3xx", - "sampled": true, - "span_count": Object { - "started": 0, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 224684.21052631576, - }, - Object { - "averageResponseTime": 32387.73641304348, - "impact": 2.2558112380477584, - "name": "GET /log-error", - "p95": 40061.1, - "sample": Object { - "@timestamp": "2018-11-18T20:52:51.462Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 4877, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3659, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "connection": "close", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/log-error", - "hostname": "opbeans-node", - "pathname": "/log-error", - "port": "3000", - "protocol": "http:", - "raw": "/log-error", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-length": "24", - "content-type": "text/html; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:52:51 GMT", - "etag": "W/\\"18-MS3VbhH7auHMzO0fUuNF6v14N/M\\"", - "x-powered-by": "Express", - }, - "status_code": 500, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574371462005, - }, - "trace": Object { - "id": "15366d65659b5fc8f67ff127391b3aff", - }, - "transaction": Object { - "duration": Object { - "us": 33367, - }, - "id": "ec9c465c5042ded8", - "name": "GET /log-error", - "result": "HTTP 5xx", - "sampled": true, - "span_count": Object { - "started": 0, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 23242.105263157893, - }, - Object { - "averageResponseTime": 32900.72714285714, - "impact": 2.1791207411745854, - "name": "GET /log-message", - "p95": 40444, - "sample": Object { - "@timestamp": "2018-11-18T20:49:09.225Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 321, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3142, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "connection": "close", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/log-message", - "hostname": "opbeans-node", - "pathname": "/log-message", - "port": "3000", - "protocol": "http:", - "raw": "/log-message", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-length": "24", - "content-type": "text/html; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:49:09 GMT", - "etag": "W/\\"18-MS3VbhH7auHMzO0fUuNF6v14N/M\\"", - "x-powered-by": "Express", - }, - "status_code": 500, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574149225004, - }, - "trace": Object { - "id": "ba18b741cdd3ac83eca89a5fede47577", - }, - "transaction": Object { - "duration": Object { - "us": 32381, - }, - "id": "b9a8f96d7554d09f", - "name": "GET /log-message", - "result": "HTTP 5xx", - "sampled": true, - "span_count": Object { - "started": 0, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 22105.263157894737, - }, - Object { - "averageResponseTime": 10548.218597063622, - "impact": 1.8338763992340905, - "name": "GET /api/products/:id", - "p95": 28413.383333333328, - "sample": Object { - "@timestamp": "2018-11-18T20:52:57.963Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 7184, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3686, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "connection": "close", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/products/3", - "hostname": "opbeans-node", - "pathname": "/api/products/3", - "port": "3000", - "protocol": "http:", - "raw": "/api/products/3", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-length": "231", - "content-type": "application/json; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:52:57 GMT", - "etag": "W/\\"e7-kkuzj37GZDzXDh0CWqh5Gan0VO4\\"", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574377963005, - }, - "trace": Object { - "id": "ca86ec845e412e4b4506a715d51548ec", - }, - "transaction": Object { - "duration": Object { - "us": 6959, - }, - "id": "d324897ffb7ebcdc", - "name": "GET /api/products/:id", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 1, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 58073.68421052631, - }, - Object { - "averageResponseTime": 9868.217894736843, - "impact": 1.7722323960215767, - "name": "GET /api/customers/:id", - "p95": 27486.5, - "sample": Object { - "@timestamp": "2018-11-18T20:52:56.797Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 8225, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3686, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "accept": "*/*", - "accept-encoding": "gzip, deflate", - "connection": "keep-alive", - "elastic-apm-traceparent": "00-e6140d30363f18b585f5d3b753f4d025-aa82e2c847265626-01", - "host": "opbeans-node:3000", - "user-agent": "python-requests/2.20.0", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.6", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/customers/700", - "hostname": "opbeans-node", - "pathname": "/api/customers/700", - "port": "3000", - "protocol": "http:", - "raw": "/api/customers/700", - }, - }, - "response": Object { - "headers": Object { - "connection": "keep-alive", - "content-length": "193", - "content-type": "application/json; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:52:56 GMT", - "etag": "W/\\"c1-LbuhkuLzFyZ0H+7+JQGA5b0kvNs\\"", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "parent": Object { - "id": "aa82e2c847265626", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574376797031, - }, - "trace": Object { - "id": "e6140d30363f18b585f5d3b753f4d025", - }, - "transaction": Object { - "duration": Object { - "us": 9735, - }, - "id": "60e230d12f3f0960", - "name": "GET /api/customers/:id", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 1, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 59999.99999999999, - }, - Object { - "averageResponseTime": 12763.68806073154, - "impact": 1.7479924334286208, - "name": "GET /api/types/:id", - "p95": 30576.749999999996, - "sample": Object { - "@timestamp": "2018-11-18T20:53:35.967Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 5345, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3756, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "connection": "close", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/types/1", - "hostname": "opbeans-node", - "pathname": "/api/types/1", - "port": "3000", - "protocol": "http:", - "raw": "/api/types/1", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-length": "217", - "content-type": "application/json; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:53:35 GMT", - "etag": "W/\\"d9-cebOOHODBQMZd1wt+ZZBaSPgQLQ\\"", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574415967005, - }, - "trace": Object { - "id": "2223b30b5cbaf2e221fcf70ac6d9abbe", - }, - "transaction": Object { - "duration": Object { - "us": 13064, - }, - "id": "053436abacdec0a4", - "name": "GET /api/types/:id", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 2, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 45757.8947368421, - }, - Object { - "averageResponseTime": 10584.05144193297, - "impact": 1.280810614916383, - "name": "GET /api/orders/:id", - "p95": 26555.399999999998, - "sample": Object { - "@timestamp": "2018-11-18T20:51:36.949Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 5999, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3475, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "connection": "close", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/orders/183", - "hostname": "opbeans-node", - "pathname": "/api/orders/183", - "port": "3000", - "protocol": "http:", - "raw": "/api/orders/183", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-length": "0", - "date": "Sun, 18 Nov 2018 20:51:36 GMT", - "x-powered-by": "Express", - }, - "status_code": 404, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574296949004, - }, - "trace": Object { - "id": "dab6421fa44a6869887e0edf32e1ad6f", - }, - "transaction": Object { - "duration": Object { - "us": 5906, - }, - "id": "937ef5588454f74a", - "name": "GET /api/orders/:id", - "result": "HTTP 4xx", - "sampled": true, - "span_count": Object { - "started": 1, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 40515.789473684206, - }, - Object { - "averageResponseTime": 1422.926672899693, - "impact": 1.0027124806135428, - "name": "GET unknown route", - "p95": 2311.885238095238, - "sample": Object { - "@timestamp": "2018-11-18T20:53:42.504Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3756, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "accept": "*/*", - "accept-encoding": "gzip, deflate", - "connection": "keep-alive", - "host": "opbeans-node:3000", - "referer": "http://opbeans-node:3000/dashboard", - "user-agent": "Chromeless 1.4.0", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.7", - }, - "url": Object { - "full": "http://opbeans-node:3000/rum-config.js", - "hostname": "opbeans-node", - "pathname": "/rum-config.js", - "port": "3000", - "protocol": "http:", - "raw": "/rum-config.js", - }, - }, - "response": Object { - "headers": Object { - "connection": "keep-alive", - "content-length": "172", - "content-type": "text/javascript", - "date": "Sun, 18 Nov 2018 20:53:42 GMT", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574422504004, - }, - "trace": Object { - "id": "4399e7233e6e7b77e70c2fff111b8f28", - }, - "transaction": Object { - "duration": Object { - "us": 911, - }, - "id": "107881ae2be1b56d", - "name": "GET unknown route", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 0, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 236431.5789473684, - }, - Object { - "averageResponseTime": 21331.714285714286, - "impact": 0.28817487960409877, - "name": "POST /api", - "p95": 30938, - "sample": Object { - "@timestamp": "2018-11-18T20:29:42.751Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 2927, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 546, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "body": "[REDACTED]", - "headers": Object { - "accept": "application/json", - "connection": "close", - "content-length": "129", - "content-type": "application/json", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "POST", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/api/orders", - "hostname": "opbeans-node", - "pathname": "/api/orders", - "port": "3000", - "protocol": "http:", - "raw": "/api/orders", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-length": "0", - "date": "Sun, 18 Nov 2018 20:29:42 GMT", - "x-powered-by": "Express", - }, - "status_code": 400, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542572982751005, - }, - "trace": Object { - "id": "8ed4d94ec8fc11b1ea1b0aa59c2320ff", - }, - "transaction": Object { - "duration": Object { - "us": 21083, - }, - "id": "d67c2f7aa897110c", - "name": "POST /api", - "result": "HTTP 4xx", - "sampled": true, - "span_count": Object { - "started": 1, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 4642.105263157894, - }, - Object { - "averageResponseTime": 4694.005586592179, - "impact": 0.1498515000753004, - "name": "GET /is-it-coffee-time", - "p95": 11022.99999999992, - "sample": Object { - "@timestamp": "2018-11-18T20:46:19.317Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 8593, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 2760, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "connection": "close", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/is-it-coffee-time", - "hostname": "opbeans-node", - "pathname": "/is-it-coffee-time", - "port": "3000", - "protocol": "http:", - "raw": "/is-it-coffee-time", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-length": "148", - "content-security-policy": "default-src 'self'", - "content-type": "text/html; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:46:19 GMT", - "x-content-type-options": "nosniff", - "x-powered-by": "Express", - }, - "status_code": 500, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542573979317007, - }, - "trace": Object { - "id": "821812b416de4c73ced87f8777fa46a6", - }, - "transaction": Object { - "duration": Object { - "us": 4253, - }, - "id": "319a5c555a1ab207", - "name": "GET /is-it-coffee-time", - "result": "HTTP 5xx", - "sampled": true, - "span_count": Object { - "started": 0, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 11305.263157894737, - }, - Object { - "averageResponseTime": 4549.889880952381, - "impact": 0.13543365054509587, - "name": "GET /throw-error", - "p95": 7719.700000000001, - "sample": Object { - "@timestamp": "2018-11-18T20:47:10.714Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 7220, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 2895, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "connection": "close", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "GET", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/throw-error", - "hostname": "opbeans-node", - "pathname": "/throw-error", - "port": "3000", - "protocol": "http:", - "raw": "/throw-error", - }, - }, - "response": Object { - "headers": Object { - "connection": "close", - "content-length": "148", - "content-security-policy": "default-src 'self'", - "content-type": "text/html; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:47:10 GMT", - "x-content-type-options": "nosniff", - "x-powered-by": "Express", - }, - "status_code": 500, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574030714012, - }, - "trace": Object { - "id": "6c0ef23e1f963f304ce440a909914d35", - }, - "transaction": Object { - "duration": Object { - "us": 4458, - }, - "id": "ecd187dc53f09fbd", - "name": "GET /throw-error", - "result": "HTTP 5xx", - "sampled": true, - "span_count": Object { - "started": 0, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 10610.526315789473, - }, - Object { - "averageResponseTime": 2742.4615384615386, - "impact": 0.08501028923348058, - "name": "OPTIONS unknown route", - "p95": 4370.000000000002, - "sample": Object { - "@timestamp": "2018-11-18T20:49:00.707Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 3775, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 3142, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "headers": Object { - "connection": "close", - "content-length": "0", - "host": "opbeans-node:3000", - "user-agent": "workload/2.4.3", - }, - "http_version": "1.1", - "method": "OPTIONS", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.10", - }, - "url": Object { - "full": "http://opbeans-node:3000/", - "hostname": "opbeans-node", - "pathname": "/", - "port": "3000", - "protocol": "http:", - "raw": "/", - }, - }, - "response": Object { - "headers": Object { - "allow": "GET,HEAD", - "connection": "close", - "content-length": "8", - "content-type": "text/html; charset=utf-8", - "date": "Sun, 18 Nov 2018 20:49:00 GMT", - "etag": "W/\\"8-ZRAf8oNBS3Bjb/SU2GYZCmbtmXg\\"", - "x-powered-by": "Express", - }, - "status_code": 200, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542574140707006, - }, - "trace": Object { - "id": "469e3e5f91ffe3195a8e58cdd1cdefa8", - }, - "transaction": Object { - "duration": Object { - "us": 2371, - }, - "id": "a8c87ebc7ec68bc0", - "name": "OPTIONS unknown route", - "result": "HTTP 2xx", - "sampled": true, - "span_count": Object { - "started": 0, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 11494.736842105262, - }, - Object { - "averageResponseTime": 5192.9, - "impact": 0, - "name": "POST unknown route", - "p95": 13230.5, - "sample": Object { - "@timestamp": "2018-11-18T18:43:50.994Z", - "agent": Object { - "hostname": "b359e3afece8", - "type": "apm-server", - "version": "7.0.0-alpha1", - }, - "context": Object { - "custom": Object { - "containerId": 6102, - }, - "process": Object { - "argv": Array [ - "/usr/local/bin/node", - "/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js", - ], - "pid": 19196, - "ppid": 1, - "title": "node /app/server.js", - }, - "request": Object { - "body": "[REDACTED]", - "headers": Object { - "accept": "*/*", - "accept-encoding": "gzip, deflate", - "content-length": "380", - "content-type": "multipart/form-data; boundary=2b2e40be188a4cb5a56c05a0c182f6c9", - "elastic-apm-traceparent": "00-19688959ea6cbccda8013c11566ea329-1fc3665eef2dcdfc-01", - "host": "172.18.0.9:3000", - "user-agent": "Python/3.7 aiohttp/3.3.2", - "x-forwarded-for": "172.18.0.11", - }, - "http_version": "1.1", - "method": "POST", - "socket": Object { - "encrypted": false, - "remote_address": "::ffff:172.18.0.9", - }, - "url": Object { - "full": "http://172.18.0.9:3000/api/orders/csv", - "hostname": "172.18.0.9", - "pathname": "/api/orders/csv", - "port": "3000", - "protocol": "http:", - "raw": "/api/orders/csv", - }, - }, - "response": Object { - "headers": Object { - "connection": "keep-alive", - "content-length": "154", - "content-security-policy": "default-src 'self'", - "content-type": "text/html; charset=utf-8", - "date": "Sun, 18 Nov 2018 18:43:50 GMT", - "x-content-type-options": "nosniff", - "x-powered-by": "Express", - }, - "status_code": 404, - }, - "service": Object { - "agent": Object { - "name": "nodejs", - "version": "1.14.2", - }, - "language": Object { - "name": "javascript", - }, - "name": "opbeans-node", - "runtime": Object { - "name": "node", - "version": "8.12.0", - }, - "version": "1.0.0", - }, - "system": Object { - "architecture": "x64", - "hostname": "98195610c255", - "ip": "172.18.0.10", - "platform": "linux", - }, - "tags": Object { - "foo": "bar", - "lorem": "ipsum dolor sit amet, consectetur adipiscing elit. Nulla finibus, ipsum id scelerisque consequat, enim leo vulputate massa, vel ultricies ante neque ac risus. Curabitur tincidunt vitae sapien id pulvinar. Mauris eu vestibulum tortor. Integer sit amet lorem fringilla, egestas tellus vitae, vulputate purus. Nulla feugiat blandit nunc et semper. Morbi purus libero, mattis sed mauris non, euismod iaculis lacus. Curabitur eleifend ante eros, non faucibus velit lacinia id. Duis posuere libero augue, at dignissim urna consectetur eget. Praesent eu congue est, iaculis finibus augue.", - "multi-line": "foo -bar -baz", - "this-is-a-very-long-tag-name-without-any-spaces": "test", - }, - "user": Object { - "email": "kimchy@elastic.co", - "id": "42", - "username": "kimchy", - }, - }, - "host": Object { - "name": "b359e3afece8", - }, - "parent": Object { - "id": "1fc3665eef2dcdfc", - }, - "processor": Object { - "event": "transaction", - "name": "transaction", - }, - "timestamp": Object { - "us": 1542566630994005, - }, - "trace": Object { - "id": "19688959ea6cbccda8013c11566ea329", - }, - "transaction": Object { - "duration": Object { - "us": 3467, - }, - "id": "92c3ceea57899061", - "name": "POST unknown route", - "result": "HTTP 4xx", - "sampled": true, - "span_count": Object { - "started": 0, - }, - "type": "request", - }, - }, - "transactionsPerMinute": 631.578947368421, - }, -] -`; diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.test.ts b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.test.ts deleted file mode 100644 index a26c3d85a3fc4..0000000000000 --- a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { transactionGroupsFetcher } from './fetcher'; -import { APMConfig } from '../..'; - -function getSetup() { - return { - start: 1528113600000, - end: 1528977600000, - client: { - search: jest.fn(), - } as any, - internalClient: { - search: jest.fn(), - } as any, - config: { - 'xpack.apm.ui.transactionGroupBucketSize': 100, - } as APMConfig, - uiFiltersES: [{ term: { 'service.environment': 'test' } }], - indices: { - 'apm_oss.sourcemapIndices': 'myIndex', - 'apm_oss.errorIndices': 'myIndex', - 'apm_oss.onboardingIndices': 'myIndex', - 'apm_oss.spanIndices': 'myIndex', - 'apm_oss.transactionIndices': 'myIndex', - 'apm_oss.metricsIndices': 'myIndex', - apmAgentConfigurationIndex: 'myIndex', - apmCustomLinkIndex: 'myIndex', - }, - dynamicIndexPattern: null as any, - }; -} - -describe('transactionGroupsFetcher', () => { - describe('type: top_traces', () => { - it('should call client.search with correct query', async () => { - const setup = getSetup(); - const bucketSize = 100; - await transactionGroupsFetcher({ type: 'top_traces' }, setup, bucketSize); - expect(setup.client.search.mock.calls).toMatchSnapshot(); - }); - }); - - describe('type: top_transactions', () => { - it('should call client.search with correct query', async () => { - const setup = getSetup(); - const bucketSize = 100; - await transactionGroupsFetcher( - { - type: 'top_transactions', - serviceName: 'opbeans-node', - transactionType: 'request', - }, - setup, - bucketSize - ); - expect(setup.client.search.mock.calls).toMatchSnapshot(); - }); - }); -}); diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts index a5cc74b18a7ef..73bf1d01924e7 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts +++ b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts @@ -3,23 +3,31 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - +import { take, sortBy } from 'lodash'; +import { Unionize } from 'utility-types'; +import moment from 'moment'; +import { joinByKey } from '../../../common/utils/join_by_key'; +import { ESSearchRequest } from '../../../typings/elasticsearch'; import { SERVICE_NAME, - TRANSACTION_DURATION, - TRANSACTION_SAMPLED, TRANSACTION_NAME, } from '../../../common/elasticsearch_fieldnames'; import { getTransactionGroupsProjection } from '../../../common/projections/transaction_groups'; import { mergeProjection } from '../../../common/projections/util/merge_projection'; import { PromiseReturnType } from '../../../../observability/typings/common'; -import { SortOptions } from '../../../typings/elasticsearch/aggregations'; +import { AggregationOptionsByType } from '../../../typings/elasticsearch/aggregations'; import { Transaction } from '../../../typings/es_schemas/ui/transaction'; import { Setup, SetupTimeRange, SetupUIFilters, } from '../helpers/setup_request'; +import { + getSamples, + getAverages, + getSums, + getPercentiles, +} from './get_transaction_group_stats'; interface TopTransactionOptions { type: 'top_transactions'; @@ -36,68 +44,149 @@ interface TopTraceOptions { export type Options = TopTransactionOptions | TopTraceOptions; export type ESResponse = PromiseReturnType; + +export type TransactionGroupRequestBase = ESSearchRequest & { + body: { + aggs: { + transaction_groups: Unionize< + Pick + >; + }; + }; +}; + +export type TransactionGroupSetup = Setup & SetupTimeRange & SetupUIFilters; + +function getItemsWithRelativeImpact( + setup: TransactionGroupSetup, + items: Array<{ + sum?: number | null; + key: string | Record; + avg?: number | null; + count?: number | null; + p95?: number; + sample?: Transaction; + }> +) { + const values = items + .map(({ sum }) => sum) + .filter((value) => value !== null) as number[]; + + const max = Math.max(...values); + const min = Math.min(...values); + + const duration = moment.duration(setup.end - setup.start); + const minutes = duration.asMinutes(); + + const itemsWithRelativeImpact: TransactionGroup[] = items + .map((item) => { + return { + key: item.key, + averageResponseTime: item.avg, + transactionsPerMinute: (item.count ?? 0) / minutes, + impact: + item.sum !== null && item.sum !== undefined + ? ((item.sum - min) / (max - min)) * 100 || 0 + : 0, + p95: item.p95, + sample: item.sample!, + }; + }) + .filter((item) => item.sample); + + return itemsWithRelativeImpact; +} + export async function transactionGroupsFetcher( options: Options, - setup: Setup & SetupTimeRange & SetupUIFilters, + setup: TransactionGroupSetup, bucketSize: number ) { - const { client } = setup; - const projection = getTransactionGroupsProjection({ setup, options, }); - const sort: SortOptions = [ - { _score: 'desc' as const }, // sort by _score to ensure that buckets with sampled:true ends up on top - { '@timestamp': { order: 'desc' as const } }, - ]; - const isTopTraces = options.type === 'top_traces'; - if (isTopTraces) { - // Delete the projection aggregation when searching for traces, as it should use the combined aggregation instead - delete projection.body.aggs; - } + delete projection.body.aggs; + + // traces overview is hardcoded to 10000 + // transactions overview: 1 extra bucket is added to check whether the total number of buckets exceed the specified bucket size. + const expectedBucketSize = isTopTraces ? 10000 : bucketSize; + const size = isTopTraces ? 10000 : expectedBucketSize + 1; - const params = mergeProjection(projection, { + const request = mergeProjection(projection, { + size: 0, body: { - size: 0, - query: { - bool: { - // prefer sampled transactions - should: [{ term: { [TRANSACTION_SAMPLED]: true } }], - }, - }, aggs: { transaction_groups: { - composite: { - // traces overview is hardcoded to 10000 - // transactions overview: 1 extra bucket is added to check whether the total number of buckets exceed the specified bucket size. - size: isTopTraces ? 10000 : bucketSize + 1, - sources: [ - ...(isTopTraces - ? [{ service: { terms: { field: SERVICE_NAME } } }] - : []), - { transaction: { terms: { field: TRANSACTION_NAME } } }, - ], - }, - aggs: { - sample: { top_hits: { size: 1, sort } }, - avg: { avg: { field: TRANSACTION_DURATION } }, - p95: { - percentiles: { - field: TRANSACTION_DURATION, - percents: [95], - hdr: { number_of_significant_value_digits: 2 }, - }, - }, - sum: { sum: { field: TRANSACTION_DURATION } }, - }, + ...(isTopTraces + ? { + composite: { + sources: [ + { [SERVICE_NAME]: { terms: { field: SERVICE_NAME } } }, + { + [TRANSACTION_NAME]: { + terms: { field: TRANSACTION_NAME }, + }, + }, + ], + size, + }, + } + : { + terms: { + field: TRANSACTION_NAME, + size, + }, + }), }, }, }, }); - return client.search(params); + const params = { + request, + setup, + }; + + const [samples, averages, sums, percentiles] = await Promise.all([ + getSamples(params), + getAverages(params), + getSums(params), + !isTopTraces ? getPercentiles(params) : Promise.resolve(undefined), + ]); + + const stats = [ + ...samples, + ...averages, + ...sums, + ...(percentiles ? percentiles : []), + ]; + + const items = joinByKey(stats, 'key'); + + const itemsWithRelativeImpact = getItemsWithRelativeImpact(setup, items); + + return { + items: take( + // sort by impact by default so most impactful services are not cut off + sortBy(itemsWithRelativeImpact, 'impact').reverse(), + expectedBucketSize + ), + // The aggregation is considered accurate if the configured bucket size is larger or equal to the number of buckets returned + // the actual number of buckets retrieved are `bucketsize + 1` to detect whether it's above the limit + isAggregationAccurate: expectedBucketSize >= itemsWithRelativeImpact.length, + bucketSize, + }; +} + +export interface TransactionGroup { + key: Record | string; + averageResponseTime: number | null | undefined; + transactionsPerMinute: number; + p95: number | undefined; + impact: number; + sample: Transaction; } diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts b/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts new file mode 100644 index 0000000000000..59fb370113ec2 --- /dev/null +++ b/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts @@ -0,0 +1,144 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { merge } from 'lodash'; +import { arrayUnionToCallable } from '../../../common/utils/array_union_to_callable'; +import { Transaction } from '../../../typings/es_schemas/ui/transaction'; +import { + TRANSACTION_SAMPLED, + TRANSACTION_DURATION, +} from '../../../common/elasticsearch_fieldnames'; +import { + AggregationInputMap, + SortOptions, +} from '../../../typings/elasticsearch/aggregations'; +import { TransactionGroupRequestBase, TransactionGroupSetup } from './fetcher'; + +interface MetricParams { + request: TransactionGroupRequestBase; + setup: TransactionGroupSetup; +} + +type BucketKey = string | Record; + +function mergeRequestWithAggs< + TRequestBase extends TransactionGroupRequestBase, + TInputMap extends AggregationInputMap +>(request: TRequestBase, aggs: TInputMap) { + return merge({}, request, { + body: { + aggs: { + transaction_groups: { + aggs, + }, + }, + }, + }); +} + +export async function getSamples({ request, setup }: MetricParams) { + const params = mergeRequestWithAggs(request, { + sample: { + top_hits: { + size: 1, + }, + }, + }); + + const sort: SortOptions = [ + { _score: 'desc' as const }, // sort by _score to ensure that buckets with sampled:true ends up on top + { '@timestamp': { order: 'desc' as const } }, + ]; + + const response = await setup.client.search({ + ...params, + body: { + ...params.body, + query: { + ...params.body.query, + bool: { + ...params.body.query.bool, + should: [{ term: { [TRANSACTION_SAMPLED]: true } }], + }, + }, + sort, + }, + }); + + return arrayUnionToCallable( + response.aggregations?.transaction_groups.buckets ?? [] + ).map((bucket) => { + return { + key: bucket.key as BucketKey, + count: bucket.doc_count, + sample: bucket.sample.hits.hits[0]._source as Transaction, + }; + }); +} + +export async function getAverages({ request, setup }: MetricParams) { + const params = mergeRequestWithAggs(request, { + avg: { + avg: { + field: TRANSACTION_DURATION, + }, + }, + }); + + const response = await setup.client.search(params); + + return arrayUnionToCallable( + response.aggregations?.transaction_groups.buckets ?? [] + ).map((bucket) => { + return { + key: bucket.key as BucketKey, + avg: bucket.avg.value, + }; + }); +} + +export async function getSums({ request, setup }: MetricParams) { + const params = mergeRequestWithAggs(request, { + sum: { + sum: { + field: TRANSACTION_DURATION, + }, + }, + }); + + const response = await setup.client.search(params); + + return arrayUnionToCallable( + response.aggregations?.transaction_groups.buckets ?? [] + ).map((bucket) => { + return { + key: bucket.key as BucketKey, + sum: bucket.sum.value, + }; + }); +} + +export async function getPercentiles({ request, setup }: MetricParams) { + const params = mergeRequestWithAggs(request, { + p95: { + percentiles: { + field: TRANSACTION_DURATION, + hdr: { number_of_significant_value_digits: 2 }, + percents: [95], + }, + }, + }); + + const response = await setup.client.search(params); + + return arrayUnionToCallable( + response.aggregations?.transaction_groups.buckets ?? [] + ).map((bucket) => { + return { + key: bucket.key as BucketKey, + p95: Object.values(bucket.p95.values)[0], + }; + }); +} diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/index.ts b/x-pack/plugins/apm/server/lib/transaction_groups/index.ts index 893e586b351a8..6e0d619268d44 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/index.ts +++ b/x-pack/plugins/apm/server/lib/transaction_groups/index.ts @@ -10,19 +10,11 @@ import { SetupUIFilters, } from '../helpers/setup_request'; import { transactionGroupsFetcher, Options } from './fetcher'; -import { transactionGroupsTransformer } from './transform'; export async function getTransactionGroupList( options: Options, setup: Setup & SetupTimeRange & SetupUIFilters ) { - const { start, end } = setup; const bucketSize = setup.config['xpack.apm.ui.transactionGroupBucketSize']; - const response = await transactionGroupsFetcher(options, setup, bucketSize); - return transactionGroupsTransformer({ - response, - start, - end, - bucketSize, - }); + return await transactionGroupsFetcher(options, setup, bucketSize); } diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/queries.test.ts b/x-pack/plugins/apm/server/lib/transaction_groups/queries.test.ts index 2c5aa79bb3483..0b2ff3a72975b 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/queries.test.ts +++ b/x-pack/plugins/apm/server/lib/transaction_groups/queries.test.ts @@ -31,7 +31,9 @@ describe('transaction group queries', () => { ) ); - expect(mock.params).toMatchSnapshot(); + const allParams = mock.spy.mock.calls.map((call) => call[0]); + + expect(allParams).toMatchSnapshot(); }); it('fetches top traces', async () => { @@ -46,6 +48,8 @@ describe('transaction group queries', () => { ) ); - expect(mock.params).toMatchSnapshot(); + const allParams = mock.spy.mock.calls.map((call) => call[0]); + + expect(allParams).toMatchSnapshot(); }); }); diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/transform.test.ts b/x-pack/plugins/apm/server/lib/transaction_groups/transform.test.ts deleted file mode 100644 index 0bb29e27f0219..0000000000000 --- a/x-pack/plugins/apm/server/lib/transaction_groups/transform.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { ESResponse } from './fetcher'; -import { transactionGroupsResponse } from './mock_responses/transaction_groups_response'; -import { transactionGroupsTransformer } from './transform'; - -describe('transactionGroupsTransformer', () => { - it('should match snapshot', () => { - const { - bucketSize, - isAggregationAccurate, - items, - } = transactionGroupsTransformer({ - response: transactionGroupsResponse, - start: 100, - end: 2000, - bucketSize: 100, - }); - - expect(bucketSize).toBe(100); - expect(isAggregationAccurate).toBe(true); - expect(items).toMatchSnapshot(); - }); - - it('should transform response correctly', () => { - const bucket = { - key: { transaction: 'POST /api/orders' }, - doc_count: 180, - avg: { value: 255966.30555555556 }, - p95: { values: { '95.0': 320238.5 } }, - sum: { value: 3000000000 }, - sample: { - hits: { - total: 180, - hits: [{ _source: 'sample source' }], - }, - }, - }; - - const response = ({ - aggregations: { - transaction_groups: { - buckets: [bucket], - }, - }, - } as unknown) as ESResponse; - - expect( - transactionGroupsTransformer({ - response, - start: 100, - end: 20000, - bucketSize: 100, - }) - ).toEqual({ - bucketSize: 100, - isAggregationAccurate: true, - items: [ - { - averageResponseTime: 255966.30555555556, - impact: 0, - name: 'POST /api/orders', - p95: 320238.5, - sample: 'sample source', - transactionsPerMinute: 542.713567839196, - }, - ], - }); - }); - - it('`isAggregationAccurate` should be false if number of bucket is higher than `bucketSize`', () => { - const bucket = { - key: { transaction: 'POST /api/orders' }, - doc_count: 180, - avg: { value: 255966.30555555556 }, - p95: { values: { '95.0': 320238.5 } }, - sum: { value: 3000000000 }, - sample: { - hits: { - total: 180, - hits: [{ _source: 'sample source' }], - }, - }, - }; - - const response = ({ - aggregations: { - transaction_groups: { - buckets: [bucket, bucket, bucket, bucket], // four buckets returned - }, - }, - } as unknown) as ESResponse; - - const { isAggregationAccurate } = transactionGroupsTransformer({ - response, - start: 100, - end: 20000, - bucketSize: 3, // bucket size of three - }); - - expect(isAggregationAccurate).toEqual(false); - }); - - it('should calculate impact from sum', () => { - const getBucket = (sum: number) => ({ - key: { transaction: 'POST /api/orders' }, - doc_count: 180, - avg: { value: 300000 }, - p95: { values: { '95.0': 320000 } }, - sum: { value: sum }, - sample: { hits: { total: 180, hits: [{ _source: 'sample source' }] } }, - }); - - const response = ({ - aggregations: { - transaction_groups: { - buckets: [getBucket(10), getBucket(20), getBucket(50)], - }, - }, - } as unknown) as ESResponse; - - const { items } = transactionGroupsTransformer({ - response, - start: 100, - end: 20000, - bucketSize: 100, - }); - - expect(items.map((bucket) => bucket.impact)).toEqual([100, 25, 0]); - }); -}); diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/transform.ts b/x-pack/plugins/apm/server/lib/transaction_groups/transform.ts deleted file mode 100644 index b04ff6764675d..0000000000000 --- a/x-pack/plugins/apm/server/lib/transaction_groups/transform.ts +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import moment from 'moment'; -import { orderBy } from 'lodash'; -import { ESResponse } from './fetcher'; - -function calculateRelativeImpacts(items: ITransactionGroup[]) { - const values = items - .map(({ impact }) => impact) - .filter((value) => value !== null) as number[]; - - const max = Math.max(...values); - const min = Math.min(...values); - - return items.map((bucket) => ({ - ...bucket, - impact: - bucket.impact !== null - ? ((bucket.impact - min) / (max - min)) * 100 || 0 - : 0, - })); -} - -const getBuckets = (response: ESResponse) => { - if (response.aggregations) { - return orderBy( - response.aggregations.transaction_groups.buckets, - ['sum.value'], - ['desc'] - ); - } - return []; -}; - -export type ITransactionGroup = ReturnType; -function getTransactionGroup( - bucket: ReturnType[0], - minutes: number -) { - const averageResponseTime = bucket.avg.value; - const transactionsPerMinute = bucket.doc_count / minutes; - const impact = bucket.sum.value; - const sample = bucket.sample.hits.hits[0]._source; - - return { - name: bucket.key.transaction, - sample, - p95: bucket.p95.values['95.0'], - averageResponseTime, - transactionsPerMinute, - impact, - }; -} - -export function transactionGroupsTransformer({ - response, - start, - end, - bucketSize, -}: { - response: ESResponse; - start: number; - end: number; - bucketSize: number; -}): { - items: ITransactionGroup[]; - isAggregationAccurate: boolean; - bucketSize: number; -} { - const buckets = getBuckets(response); - const duration = moment.duration(end - start); - const minutes = duration.asMinutes(); - const items = buckets.map((bucket) => getTransactionGroup(bucket, minutes)); - - const itemsWithRelativeImpact = calculateRelativeImpacts(items); - - return { - items: itemsWithRelativeImpact, - - // The aggregation is considered accurate if the configured bucket size is larger or equal to the number of buckets returned - // the actual number of buckets retrieved are `bucketsize + 1` to detect whether it's above the limit - isAggregationAccurate: bucketSize >= buckets.length, - bucketSize, - }; -} diff --git a/x-pack/plugins/apm/server/lib/transactions/avg_duration_by_browser/fetcher.ts b/x-pack/plugins/apm/server/lib/transactions/avg_duration_by_browser/fetcher.ts index e3d688b694380..b4d98ec41fc2d 100644 --- a/x-pack/plugins/apm/server/lib/transactions/avg_duration_by_browser/fetcher.ts +++ b/x-pack/plugins/apm/server/lib/transactions/avg_duration_by_browser/fetcher.ts @@ -12,6 +12,7 @@ import { TRANSACTION_TYPE, USER_AGENT_NAME, TRANSACTION_DURATION, + TRANSACTION_NAME, } from '../../../../common/elasticsearch_fieldnames'; import { rangeFilter } from '../../../../common/utils/range_filter'; import { getBucketSize } from '../../helpers/get_bucket_size'; @@ -23,15 +24,20 @@ export type ESResponse = PromiseReturnType; export function fetcher(options: Options) { const { end, client, indices, start, uiFiltersES } = options.setup; - const { serviceName } = options; + const { serviceName, transactionName } = options; const { intervalString } = getBucketSize(start, end, 'auto'); + const transactionNameFilter = transactionName + ? [{ term: { [TRANSACTION_NAME]: transactionName } }] + : []; + const filter: ESFilter[] = [ { term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, { term: { [SERVICE_NAME]: serviceName } }, { term: { [TRANSACTION_TYPE]: TRANSACTION_PAGE_LOAD } }, { range: rangeFilter(start, end) }, ...uiFiltersES, + ...transactionNameFilter, ]; const params = { diff --git a/x-pack/plugins/apm/server/lib/transactions/avg_duration_by_browser/index.ts b/x-pack/plugins/apm/server/lib/transactions/avg_duration_by_browser/index.ts index 000890f52ebe6..e3a0d9e26142a 100644 --- a/x-pack/plugins/apm/server/lib/transactions/avg_duration_by_browser/index.ts +++ b/x-pack/plugins/apm/server/lib/transactions/avg_duration_by_browser/index.ts @@ -16,6 +16,7 @@ import { transformer } from './transformer'; export interface Options { serviceName: string; setup: Setup & SetupTimeRange & SetupUIFilters; + transactionName?: string; } export type AvgDurationByBrowserAPIResponse = Array<{ diff --git a/x-pack/plugins/apm/server/lib/ui_filters/local_ui_filters/get_local_filter_query.ts b/x-pack/plugins/apm/server/lib/ui_filters/local_ui_filters/get_local_filter_query.ts index 1cecf14f2eeb8..e892284fd87cd 100644 --- a/x-pack/plugins/apm/server/lib/ui_filters/local_ui_filters/get_local_filter_query.ts +++ b/x-pack/plugins/apm/server/lib/ui_filters/local_ui_filters/get_local_filter_query.ts @@ -35,7 +35,7 @@ export const getLocalFilterQuery = ({ }, }, } - : {}; + : null; return mergeProjection(projection, { body: { diff --git a/x-pack/plugins/apm/server/lib/ui_filters/local_ui_filters/index.ts b/x-pack/plugins/apm/server/lib/ui_filters/local_ui_filters/index.ts index 588d5c7896db9..3833b93c8d1f7 100644 --- a/x-pack/plugins/apm/server/lib/ui_filters/local_ui_filters/index.ts +++ b/x-pack/plugins/apm/server/lib/ui_filters/local_ui_filters/index.ts @@ -43,6 +43,7 @@ export async function getLocalUIFilters({ const response = await client.search(query); const filter = localUIFilters[name]; + const buckets = response?.aggregations?.by_terms?.buckets ?? []; return { diff --git a/x-pack/plugins/apm/server/routes/transaction_groups.ts b/x-pack/plugins/apm/server/routes/transaction_groups.ts index 813d757c7c33e..c667ce4f07e93 100644 --- a/x-pack/plugins/apm/server/routes/transaction_groups.ts +++ b/x-pack/plugins/apm/server/routes/transaction_groups.ts @@ -164,7 +164,6 @@ export const transactionGroupsAvgDurationByBrowser = createRoute(() => ({ }), query: t.intersection([ t.partial({ - transactionType: t.string, transactionName: t.string, }), uiFiltersRt, @@ -174,10 +173,12 @@ export const transactionGroupsAvgDurationByBrowser = createRoute(() => ({ handler: async ({ context, request }) => { const setup = await setupRequest(context, request); const { serviceName } = context.params.path; + const { transactionName } = context.params.query; return getTransactionAvgDurationByBrowser({ serviceName, setup, + transactionName, }); }, })); diff --git a/x-pack/plugins/apm/typings/elasticsearch/aggregations.ts b/x-pack/plugins/apm/typings/elasticsearch/aggregations.ts index ac7499c23e926..d25ec8709e3be 100644 --- a/x-pack/plugins/apm/typings/elasticsearch/aggregations.ts +++ b/x-pack/plugins/apm/typings/elasticsearch/aggregations.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Unionize } from 'utility-types'; +import { Unionize, UnionToIntersection } from 'utility-types'; type SortOrder = 'asc' | 'desc'; type SortInstruction = Record; @@ -288,10 +288,13 @@ interface AggregationResponsePart< } | undefined; composite: { - after_key: Record, number>; + after_key: Record< + GetCompositeKeys, + string | number + >; buckets: Array< { - key: Record, number>; + key: Record, string | number>; doc_count: number; } & BucketSubAggregationResponse< TAggregationOptionsMap['aggs'], @@ -337,6 +340,15 @@ interface AggregationResponsePart< // keyof AggregationResponsePart<{}, unknown> // >; +// ensures aggregations work with requests where aggregation options are a union type, +// e.g. { transaction_groups: { composite: any } | { terms: any } }. +// Union keys are not included in keyof. The type will fall back to keyof T if +// UnionToIntersection fails, which happens when there are conflicts between the union +// types, e.g. { foo: string; bar?: undefined } | { foo?: undefined; bar: string }; +export type ValidAggregationKeysOf< + T extends Record +> = keyof (UnionToIntersection extends never ? T : UnionToIntersection); + export type AggregationResponseMap< TAggregationInputMap extends AggregationInputMap | undefined, TDocument @@ -345,6 +357,6 @@ export type AggregationResponseMap< [TName in keyof TAggregationInputMap]: AggregationResponsePart< TAggregationInputMap[TName], TDocument - >[AggregationType & keyof TAggregationInputMap[TName]]; + >[AggregationType & ValidAggregationKeysOf]; } : undefined; diff --git a/x-pack/plugins/canvas/public/application.tsx b/x-pack/plugins/canvas/public/application.tsx index b2c836fe4805f..0bbf449ce11f9 100644 --- a/x-pack/plugins/canvas/public/application.tsx +++ b/x-pack/plugins/canvas/public/application.tsx @@ -31,7 +31,7 @@ import { init as initStatsReporter } from './lib/ui_metric'; import { CapabilitiesStrings } from '../i18n'; -import { startServices, services } from './services'; +import { startServices, services, ServicesProvider } from './services'; // @ts-expect-error untyped local import { createHistory, destroyHistory } from './lib/history_provider'; // @ts-expect-error untyped local @@ -52,19 +52,16 @@ export const renderApp = ( ) => { element.classList.add('canvas'); element.classList.add('canvasContainerWrapper'); - const canvasServices = Object.entries(services).reduce((reduction, [key, provider]) => { - reduction[key] = provider.getService(); - - return reduction; - }, {} as Record); ReactDOM.render( - - - - - - + + + + + + + + , element ); diff --git a/x-pack/plugins/canvas/public/components/alignment_guide/alignment_guide.js b/x-pack/plugins/canvas/public/components/alignment_guide/alignment_guide.js deleted file mode 100644 index d5a76efaf3d49..0000000000000 --- a/x-pack/plugins/canvas/public/components/alignment_guide/alignment_guide.js +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import PropTypes from 'prop-types'; -import { matrixToCSS } from '../../lib/dom'; - -export const AlignmentGuide = ({ transformMatrix, width, height }) => { - const newStyle = { - width, - height, - marginLeft: -width / 2, - marginTop: -height / 2, - background: 'magenta', - position: 'absolute', - transform: matrixToCSS(transformMatrix), - }; - return ( -
- ); -}; - -AlignmentGuide.propTypes = { - transformMatrix: PropTypes.arrayOf(PropTypes.number).isRequired, - width: PropTypes.number.isRequired, - height: PropTypes.number.isRequired, -}; diff --git a/x-pack/plugins/canvas/public/components/alignment_guide/alignment_guide.scss b/x-pack/plugins/canvas/public/components/alignment_guide/alignment_guide.scss deleted file mode 100644 index 27f06b42df453..0000000000000 --- a/x-pack/plugins/canvas/public/components/alignment_guide/alignment_guide.scss +++ /dev/null @@ -1,4 +0,0 @@ -.canvasAlignmentGuide { - transform-origin: center center; /* the default, only for clarity */ - transform-style: preserve-3d; -} diff --git a/x-pack/plugins/canvas/public/components/app/index.js b/x-pack/plugins/canvas/public/components/app/index.js index a1e3b9c09554a..9a6e8719e7f40 100644 --- a/x-pack/plugins/canvas/public/components/app/index.js +++ b/x-pack/plugins/canvas/public/components/app/index.js @@ -8,7 +8,7 @@ import { connect } from 'react-redux'; import { compose, withProps } from 'recompose'; import { getAppReady, getBasePath } from '../../state/selectors/app'; import { appReady, appError } from '../../state/actions/app'; -import { withKibana } from '../../../../../../src/plugins/kibana_react/public'; +import { withServices } from '../../services'; import { App as Component } from './app'; @@ -45,8 +45,8 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { export const App = compose( connect(mapStateToProps, mapDispatchToProps, mergeProps), - withKibana, + withServices, withProps((props) => ({ - onRouteChange: props.kibana.services.canvas.navLink.updatePath, + onRouteChange: props.services.navLink.updatePath, })) )(Component); diff --git a/x-pack/plugins/canvas/public/components/app/track_route_change.js b/x-pack/plugins/canvas/public/components/app/track_route_change.js deleted file mode 100644 index 2886aa868eb9e..0000000000000 --- a/x-pack/plugins/canvas/public/components/app/track_route_change.js +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { get } from 'lodash'; -import { getWindow } from '../../lib/get_window'; -import { CANVAS_APP } from '../../../common/lib/constants'; -import { platformService } from '../../services'; - -export function trackRouteChange() { - const basePath = platformService.getService().coreStart.http.basePath.get(); - - platformService - .getService() - .startPlugins.__LEGACY.trackSubUrlForApp( - CANVAS_APP, - platformService - .getService() - .startPlugins.__LEGACY.absoluteToParsedUrl(get(getWindow(), 'location.href'), basePath) - ); -} diff --git a/x-pack/plugins/canvas/public/components/arg_add/arg_add.js b/x-pack/plugins/canvas/public/components/arg_add/arg_add.tsx similarity index 71% rename from x-pack/plugins/canvas/public/components/arg_add/arg_add.js rename to x-pack/plugins/canvas/public/components/arg_add/arg_add.tsx index 2d6d7d1046fdd..e85a2915a82b1 100644 --- a/x-pack/plugins/canvas/public/components/arg_add/arg_add.js +++ b/x-pack/plugins/canvas/public/components/arg_add/arg_add.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { FC, ReactEventHandler } from 'react'; import PropTypes from 'prop-types'; import { EuiDescriptionList, @@ -12,7 +12,13 @@ import { EuiDescriptionListDescription, } from '@elastic/eui'; -export const ArgAdd = ({ onValueAdd, displayName, help }) => { +interface Props { + displayName: string; + help: string; + onValueAdd?: ReactEventHandler; +} + +export const ArgAdd: FC = ({ onValueAdd = () => {}, displayName, help }) => { return ( -
-
-
- Manage workpad assets -
-
-
-
-
- -
- -
-
-
-
-
-
-
-
-
-

- Below are the image assets in this workpad. Any assets that are currently in use cannot be determined at this time. To reclaim space, delete assets. -

-
-
-
-
-
-
-
-
- Asset thumbnail -
-
-
-
-

- - airplane - -
- - - ( - 1 - kb) - - -

-
-
-
-
- - - -
-
- -
- -
-
-
-
- -
- -
-
-
-
- - - -
-
-
-
-
-
-
-
- Asset thumbnail -
-
-
-
-

- - marker - -
- - - ( - 1 - kb) - - -

-
-
-
-
- - - -
-
- -
- -
-
-
-
- -
- -
-
-
-
- - - -
-
-
-
-
-
-
-
-
-
- -
-
-
- 0% space used -
-
-
- -
-
-
-
, -
, -] -`; - exports[`Storyshots components/Assets/AssetManager two assets 1`] = ` Array [
{ - const newStyle = { - width, - height, - marginLeft: -width / 2, - marginTop: -height / 2, - position: 'absolute', - transform: matrixToCSS(transformMatrix), - }; - return
; -}; - -BorderConnection.propTypes = { - width: PropTypes.number.isRequired, - height: PropTypes.number.isRequired, - transformMatrix: PropTypes.arrayOf(PropTypes.number).isRequired, -}; diff --git a/x-pack/plugins/canvas/public/components/border_connection/border_connection.scss b/x-pack/plugins/canvas/public/components/border_connection/border_connection.scss deleted file mode 100644 index ba09edd1090db..0000000000000 --- a/x-pack/plugins/canvas/public/components/border_connection/border_connection.scss +++ /dev/null @@ -1,9 +0,0 @@ -.canvasBorder--connection { - position: absolute; - top: 0; - width: 100%; - height: 100%; - pointer-events: none; - border-top: 1px dashed $euiColorLightShade; - border-left: 1px dashed $euiColorLightShade; -} diff --git a/x-pack/plugins/canvas/public/components/border_resize_handle/border_resize_handle.scss b/x-pack/plugins/canvas/public/components/border_resize_handle/border_resize_handle.scss deleted file mode 100644 index 4913a599b07f7..0000000000000 --- a/x-pack/plugins/canvas/public/components/border_resize_handle/border_resize_handle.scss +++ /dev/null @@ -1,13 +0,0 @@ -.canvasBorderResizeHandle { - @include euiSlightShadow; - transform-origin: center center; /* the default, only for clarity */ - transform-style: preserve-3d; - display: block; - position: absolute; - height: 8px; - width: 8px; - margin-left: -4px; - margin-top: -4px; - background-color: $euiColorEmptyShade; - border: 1px solid $euiColorDarkShade; -} diff --git a/x-pack/plugins/canvas/public/components/color_dot/color_dot.tsx b/x-pack/plugins/canvas/public/components/color_dot/color_dot.tsx index f6afd11d405ca..478b501dcd5ec 100644 --- a/x-pack/plugins/canvas/public/components/color_dot/color_dot.tsx +++ b/x-pack/plugins/canvas/public/components/color_dot/color_dot.tsx @@ -4,18 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ +import React, { FC, ReactNode } from 'react'; import PropTypes from 'prop-types'; -import React, { FunctionComponent, ReactNode } from 'react'; import tinycolor from 'tinycolor2'; -export interface Props { - /** Any valid CSS color. If not a valid CSS string, the dot will be transparent and checkered */ - value?: string; +interface Props { /** Nodes to display within the dot. Should fit within the constraints. */ children?: ReactNode; + /** Any valid CSS color. If not a valid CSS string, the dot will be transparent and checkered */ + value?: string; } -export const ColorDot: FunctionComponent = ({ value, children }) => { +export const ColorDot: FC = ({ value, children }) => { const tc = tinycolor(value); let style = {}; @@ -34,6 +34,6 @@ export const ColorDot: FunctionComponent = ({ value, children }) => { }; ColorDot.propTypes = { - value: PropTypes.string, children: PropTypes.node, + value: PropTypes.string, }; diff --git a/x-pack/plugins/canvas/public/components/color_dot/index.ts b/x-pack/plugins/canvas/public/components/color_dot/index.ts index aacfdf4e0cc74..72936f6133886 100644 --- a/x-pack/plugins/canvas/public/components/color_dot/index.ts +++ b/x-pack/plugins/canvas/public/components/color_dot/index.ts @@ -4,9 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; - -import { ColorDot as Component } from './color_dot'; - -export { Props } from './color_dot'; -export const ColorDot = pure(Component); +export { ColorDot } from './color_dot'; diff --git a/x-pack/plugins/canvas/public/components/color_manager/color_manager.tsx b/x-pack/plugins/canvas/public/components/color_manager/color_manager.tsx index 8855bffc5e771..88bf93a3ca84a 100644 --- a/x-pack/plugins/canvas/public/components/color_manager/color_manager.tsx +++ b/x-pack/plugins/canvas/public/components/color_manager/color_manager.tsx @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiButtonIcon, EuiFieldText, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; -import React, { FunctionComponent } from 'react'; +import { EuiButtonIcon, EuiFieldText, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import tinycolor from 'tinycolor2'; import { ColorDot } from '../color_dot/color_dot'; @@ -15,17 +15,17 @@ import { ComponentStrings } from '../../../i18n/components'; const { ColorManager: strings } = ComponentStrings; export interface Props { + /** + * Determines if the add/remove buttons are displayed. + * @default false + */ + hasButtons?: boolean; /** The function to call when the Add Color button is clicked. The button will be disabled if there is no handler. */ onAddColor?: (value: string) => void; /** The function to call when the value is changed */ onChange: (value: string) => void; /** The function to call when the Remove Color button is clicked. The button will be disabled if there is no handler. */ onRemoveColor?: (value: string) => void; - /** - * Determines if the add/remove buttons are displayed. - * @default false - */ - hasButtons?: boolean; /** * The value of the color manager. Only honors valid CSS values. * @default '' @@ -33,12 +33,12 @@ export interface Props { value?: string; } -export const ColorManager: FunctionComponent = ({ - value = '', +export const ColorManager: FC = ({ + hasButtons = false, onAddColor, - onRemoveColor, onChange, - hasButtons = false, + onRemoveColor, + value = '', }) => { const tc = tinycolor(value); const validColor = tc.isValid(); diff --git a/x-pack/plugins/canvas/public/components/color_manager/index.ts b/x-pack/plugins/canvas/public/components/color_manager/index.ts index d7f59b38a74c5..9958c17cf1941 100644 --- a/x-pack/plugins/canvas/public/components/color_manager/index.ts +++ b/x-pack/plugins/canvas/public/components/color_manager/index.ts @@ -4,9 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; - -import { ColorManager as Component } from './color_manager'; - -export { Props } from './color_manager'; -export const ColorManager = pure(Component); +export { ColorManager, Props } from './color_manager'; diff --git a/x-pack/plugins/canvas/public/components/color_palette/color_palette.tsx b/x-pack/plugins/canvas/public/components/color_palette/color_palette.tsx index 09bc08f9ae541..d3b1936d4c365 100644 --- a/x-pack/plugins/canvas/public/components/color_palette/color_palette.tsx +++ b/x-pack/plugins/canvas/public/components/color_palette/color_palette.tsx @@ -4,15 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiIcon, EuiLink } from '@elastic/eui'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; -import React, { FunctionComponent } from 'react'; +import { EuiIcon, EuiLink } from '@elastic/eui'; import tinycolor from 'tinycolor2'; import { readableColor } from '../../lib/readable_color'; import { ColorDot } from '../color_dot'; import { ItemGrid } from '../item_grid'; -export interface Props { +interface Props { /** * An array of hexadecimal color values. Non-hex will be ignored. * @default [] @@ -32,7 +32,7 @@ export interface Props { value?: string; } -export const ColorPalette: FunctionComponent = ({ +export const ColorPalette: FC = ({ colors = [], colorsPerRow = 6, onChange, diff --git a/x-pack/plugins/canvas/public/components/color_palette/index.ts b/x-pack/plugins/canvas/public/components/color_palette/index.ts index fa71bc8b3b9b0..2605868b94279 100644 --- a/x-pack/plugins/canvas/public/components/color_palette/index.ts +++ b/x-pack/plugins/canvas/public/components/color_palette/index.ts @@ -4,8 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; -import { ColorPalette as Component } from './color_palette'; - -export { Props } from './color_palette'; -export const ColorPalette = pure(Component); +export { ColorPalette } from './color_palette'; diff --git a/x-pack/plugins/canvas/public/components/color_picker/color_picker.tsx b/x-pack/plugins/canvas/public/components/color_picker/color_picker.tsx index 2bf17301b7b38..8de3ddb3d03a4 100644 --- a/x-pack/plugins/canvas/public/components/color_picker/color_picker.tsx +++ b/x-pack/plugins/canvas/public/components/color_picker/color_picker.tsx @@ -4,9 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ +import React, { FC } from 'react'; import PropTypes from 'prop-types'; -import React, { FunctionComponent } from 'react'; import tinycolor from 'tinycolor2'; + import { ColorManager, Props as ColorManagerProps } from '../color_manager'; import { ColorPalette } from '../color_palette'; @@ -18,7 +19,7 @@ export interface Props extends ColorManagerProps { colors?: string[]; } -export const ColorPicker: FunctionComponent = ({ +export const ColorPicker: FC = ({ colors = [], hasButtons = false, onAddColor, diff --git a/x-pack/plugins/canvas/public/components/color_picker/index.ts b/x-pack/plugins/canvas/public/components/color_picker/index.ts index 88968d11a665c..35dd067ab6d39 100644 --- a/x-pack/plugins/canvas/public/components/color_picker/index.ts +++ b/x-pack/plugins/canvas/public/components/color_picker/index.ts @@ -4,9 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; - -import { ColorPicker as Component } from './color_picker'; - -export { Props } from './color_picker'; -export const ColorPicker = pure(Component); +export { ColorPicker, Props } from './color_picker'; diff --git a/x-pack/plugins/canvas/public/components/color_picker_popover/color_picker_popover.tsx b/x-pack/plugins/canvas/public/components/color_picker_popover/color_picker_popover.tsx index 9e8a6e88b649b..143e1a7cee6ac 100644 --- a/x-pack/plugins/canvas/public/components/color_picker_popover/color_picker_popover.tsx +++ b/x-pack/plugins/canvas/public/components/color_picker_popover/color_picker_popover.tsx @@ -4,20 +4,21 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiLink, PopoverAnchorPosition } from '@elastic/eui'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; -import React, { FunctionComponent } from 'react'; +import { EuiLink, PopoverAnchorPosition } from '@elastic/eui'; import tinycolor from 'tinycolor2'; + import { ColorDot } from '../color_dot'; import { ColorPicker, Props as ColorPickerProps } from '../color_picker'; import { Popover } from '../popover'; export interface Props extends ColorPickerProps { - anchorPosition: PopoverAnchorPosition; + anchorPosition?: PopoverAnchorPosition; ariaLabel?: string; } -export const ColorPickerPopover: FunctionComponent = (props: Props) => { +export const ColorPickerPopover: FC = (props: Props) => { const { value, anchorPosition, ariaLabel, ...rest } = props; const button = (handleClick: React.MouseEventHandler) => ( { +const getIcon = (type: IconType) => { if (type === null) { return; } @@ -36,19 +39,31 @@ const getIcon = (type) => { return ; }; -const getColumnName = (col) => (typeof col === 'string' ? col : col.name); +const getColumnName = (col: DatatableColumn) => (typeof col === 'string' ? col : col.name); -const getColumnType = (col) => col.type || null; +const getColumnType = (col: DatatableColumn) => col.type || null; -const getFormattedValue = (val, type) => { +const getFormattedValue = (val: any, type: any) => { if (type === 'date') { return moment(val).format(); } return String(val); }; -export const Datatable = ({ datatable, perPage, paginate, showHeader }) => ( - +interface Props { + datatable: DatatableType; + paginate?: boolean; + perPage?: number; + showHeader?: boolean; +} + +export const Datatable: FC = ({ + datatable, + paginate = false, + perPage = 10, + showHeader = false, +}) => ( + {({ rows, setPage, pageNumber, totalPages }) => (
@@ -91,7 +106,7 @@ export const Datatable = ({ datatable, perPage, paginate, showHeader }) => ( Datatable.propTypes = { datatable: PropTypes.object.isRequired, - perPage: PropTypes.number, paginate: PropTypes.bool, + perPage: PropTypes.number, showHeader: PropTypes.bool, }; diff --git a/x-pack/plugins/canvas/public/components/datatable/index.js b/x-pack/plugins/canvas/public/components/datatable/index.js deleted file mode 100644 index c7837005368e5..0000000000000 --- a/x-pack/plugins/canvas/public/components/datatable/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { pure } from 'recompose'; -import { Datatable as Component } from './datatable'; - -export const Datatable = pure(Component); diff --git a/x-pack/plugins/uptime/public/apps/index.ts b/x-pack/plugins/canvas/public/components/datatable/index.ts similarity index 85% rename from x-pack/plugins/uptime/public/apps/index.ts rename to x-pack/plugins/canvas/public/components/datatable/index.ts index 65b80d08d4f20..e39b909c53460 100644 --- a/x-pack/plugins/uptime/public/apps/index.ts +++ b/x-pack/plugins/canvas/public/components/datatable/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { UptimePlugin } from './plugin'; +export { Datatable } from './datatable'; diff --git a/x-pack/plugins/canvas/public/components/dragbox_annotation/dragbox_annotation.js b/x-pack/plugins/canvas/public/components/dragbox_annotation/dragbox_annotation.js deleted file mode 100644 index 8c67404cb9b7d..0000000000000 --- a/x-pack/plugins/canvas/public/components/dragbox_annotation/dragbox_annotation.js +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import PropTypes from 'prop-types'; -import { matrixToCSS } from '../../lib/dom'; - -export const DragBoxAnnotation = ({ transformMatrix, width, height }) => { - const newStyle = { - width, - height, - marginLeft: -width / 2, - marginTop: -height / 2, - transform: matrixToCSS(transformMatrix), - }; - return
; -}; - -DragBoxAnnotation.propTypes = { - transformMatrix: PropTypes.arrayOf(PropTypes.number).isRequired, - width: PropTypes.number.isRequired, - height: PropTypes.number.isRequired, -}; diff --git a/x-pack/plugins/canvas/public/components/dragbox_annotation/dragbox_annotation.scss b/x-pack/plugins/canvas/public/components/dragbox_annotation/dragbox_annotation.scss deleted file mode 100644 index bd14ced586dbd..0000000000000 --- a/x-pack/plugins/canvas/public/components/dragbox_annotation/dragbox_annotation.scss +++ /dev/null @@ -1,8 +0,0 @@ -.canvasDragBoxAnnotation { - position: absolute; - background: none; - transform-origin: center center; /* the default, only for clarity */ - transform-style: preserve-3d; - outline: dashed 1px $euiColorDarkShade; - pointer-events: none; -} diff --git a/x-pack/plugins/canvas/public/components/dragbox_annotation/index.js b/x-pack/plugins/canvas/public/components/dragbox_annotation/index.js deleted file mode 100644 index 85c97e90776c6..0000000000000 --- a/x-pack/plugins/canvas/public/components/dragbox_annotation/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { pure } from 'recompose'; -import { DragBoxAnnotation as Component } from './dragbox_annotation'; - -export const DragBoxAnnotation = pure(Component); diff --git a/x-pack/plugins/canvas/public/components/element_content/index.js b/x-pack/plugins/canvas/public/components/element_content/index.js index a138c3acb8ec7..63ece6ac32812 100644 --- a/x-pack/plugins/canvas/public/components/element_content/index.js +++ b/x-pack/plugins/canvas/public/components/element_content/index.js @@ -8,8 +8,8 @@ import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { compose, withProps } from 'recompose'; import { get } from 'lodash'; +import { withServices } from '../../services'; import { getSelectedPage, getPageById } from '../../state/selectors/workpad'; -import { withKibana } from '../../../../../../src/plugins/kibana_react/public'; import { ElementContent as Component } from './element_content'; const mapStateToProps = (state) => ({ @@ -18,9 +18,9 @@ const mapStateToProps = (state) => ({ export const ElementContent = compose( connect(mapStateToProps), - withKibana, - withProps(({ renderable, kibana }) => ({ - renderFunction: kibana.services.expressions.getRenderer(get(renderable, 'as')), + withServices, + withProps(({ renderable, services }) => ({ + renderFunction: services.expressions.getRenderer(get(renderable, 'as')), })) )(Component); diff --git a/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.tsx b/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.tsx index df9dad3e7f678..0b5bd8adf8cb9 100644 --- a/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.tsx +++ b/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.tsx @@ -4,15 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { FC } from 'react'; import { EuiFlyout, EuiFlyoutHeader, EuiFlyoutBody, EuiTitle } from '@elastic/eui'; import { SavedObjectFinderUi, SavedObjectMetaData, } from '../../../../../../src/plugins/saved_objects/public/'; import { ComponentStrings } from '../../../i18n'; -import { CoreStart } from '../../../../../../src/core/public'; -import { CanvasStartDeps } from '../../plugin'; +import { useServices } from '../../services'; const { AddEmbeddableFlyout: strings } = ComponentStrings; @@ -20,14 +19,16 @@ export interface Props { onClose: () => void; onSelect: (id: string, embeddableType: string) => void; availableEmbeddables: string[]; - savedObjects: CoreStart['savedObjects']; - uiSettings: CoreStart['uiSettings']; - getEmbeddableFactories: CanvasStartDeps['embeddable']['getEmbeddableFactories']; } -export class AddEmbeddableFlyout extends React.Component { - onAddPanel = (id: string, savedObjectType: string, name: string) => { - const embeddableFactories = this.props.getEmbeddableFactories(); +export const AddEmbeddableFlyout: FC = ({ onSelect, availableEmbeddables, onClose }) => { + const services = useServices(); + const { embeddables, platform } = services; + const { getEmbeddableFactories } = embeddables; + const { getSavedObjects, getUISettings } = platform; + + const onAddPanel = (id: string, savedObjectType: string, name: string) => { + const embeddableFactories = getEmbeddableFactories(); // Find the embeddable type from the saved object type const found = Array.from(embeddableFactories).find((embeddableFactory) => { @@ -39,41 +40,39 @@ export class AddEmbeddableFlyout extends React.Component { const foundEmbeddableType = found ? found.type : 'unknown'; - this.props.onSelect(id, foundEmbeddableType); + onSelect(id, foundEmbeddableType); }; - render() { - const embeddableFactories = this.props.getEmbeddableFactories(); + const embeddableFactories = getEmbeddableFactories(); - const availableSavedObjects = Array.from(embeddableFactories) - .filter((factory) => { - return this.props.availableEmbeddables.includes(factory.type); - }) - .map((factory) => factory.savedObjectMetaData) - .filter>(function ( - maybeSavedObjectMetaData - ): maybeSavedObjectMetaData is SavedObjectMetaData<{}> { - return maybeSavedObjectMetaData !== undefined; - }); + const availableSavedObjects = Array.from(embeddableFactories) + .filter((factory) => { + return availableEmbeddables.includes(factory.type); + }) + .map((factory) => factory.savedObjectMetaData) + .filter>(function ( + maybeSavedObjectMetaData + ): maybeSavedObjectMetaData is SavedObjectMetaData<{}> { + return maybeSavedObjectMetaData !== undefined; + }); - return ( - - - -

{strings.getTitleText()}

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

{strings.getTitleText()}

+
+
+ + + +
+ ); +}; diff --git a/x-pack/plugins/canvas/public/components/embeddable_flyout/index.tsx b/x-pack/plugins/canvas/public/components/embeddable_flyout/index.tsx index 9462ba0411de4..62a073daf4c59 100644 --- a/x-pack/plugins/canvas/public/components/embeddable_flyout/index.tsx +++ b/x-pack/plugins/canvas/public/components/embeddable_flyout/index.tsx @@ -14,8 +14,6 @@ import { AddEmbeddableFlyout, Props } from './flyout'; import { addElement } from '../../state/actions/elements'; import { getSelectedPage } from '../../state/selectors/workpad'; import { EmbeddableTypes } from '../../../canvas_plugin_src/expression_types/embeddable'; -import { WithKibanaProps } from '../../index'; -import { withKibana } from '../../../../../../src/plugins/kibana_react/public'; const allowedEmbeddables = { [EmbeddableTypes.map]: (id: string) => { @@ -74,10 +72,10 @@ const mergeProps = ( }; }; -export class EmbeddableFlyoutPortal extends React.Component { +export class EmbeddableFlyoutPortal extends React.Component { el?: HTMLElement; - constructor(props: Props & WithKibanaProps) { + constructor(props: Props) { super(props); this.el = document.createElement('div'); @@ -103,9 +101,6 @@ export class EmbeddableFlyoutPortal extends React.Component, this.el ); @@ -113,7 +108,6 @@ export class EmbeddableFlyoutPortal extends React.Component void }>( - connect(mapStateToProps, mapDispatchToProps, mergeProps), - withKibana +export const AddEmbeddablePanel = compose void }>( + connect(mapStateToProps, mapDispatchToProps, mergeProps) )(EmbeddableFlyoutPortal); diff --git a/x-pack/plugins/canvas/public/components/expression/index.js b/x-pack/plugins/canvas/public/components/expression/index.js index 4480169dd037d..146acbcd6c6ee 100644 --- a/x-pack/plugins/canvas/public/components/expression/index.js +++ b/x-pack/plugins/canvas/public/components/expression/index.js @@ -15,7 +15,7 @@ import { renderComponent, } from 'recompose'; import { fromExpression } from '@kbn/interpreter/common'; -import { withKibana } from '../../../../../../src/plugins/kibana_react/public'; +import { withServices } from '../../services'; import { getSelectedPage, getSelectedElement } from '../../state/selectors/workpad'; import { setExpression, flushContext } from '../../state/actions/elements'; import { ElementNotSelected } from './element_not_selected'; @@ -46,7 +46,7 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { const { expression } = element; - const functions = Object.values(allProps.kibana.services.expressions.getFunctions()); + const functions = Object.values(allProps.services.expressions.getFunctions()); return { ...allProps, @@ -71,7 +71,7 @@ const expressionLifecycle = lifecycle({ }); export const Expression = compose( - withKibana, + withServices, connect(mapStateToProps, mapDispatchToProps, mergeProps), withState('formState', 'setFormState', ({ expression }) => ({ expression, diff --git a/x-pack/plugins/canvas/public/components/font_picker/__snapshots__/font_picker.stories.storyshot b/x-pack/plugins/canvas/public/components/font_picker/__stories__/__snapshots__/font_picker.stories.storyshot similarity index 100% rename from x-pack/plugins/canvas/public/components/font_picker/__snapshots__/font_picker.stories.storyshot rename to x-pack/plugins/canvas/public/components/font_picker/__stories__/__snapshots__/font_picker.stories.storyshot diff --git a/x-pack/plugins/canvas/public/components/font_picker/font_picker.stories.tsx b/x-pack/plugins/canvas/public/components/font_picker/__stories__/font_picker.stories.tsx similarity index 84% rename from x-pack/plugins/canvas/public/components/font_picker/font_picker.stories.tsx rename to x-pack/plugins/canvas/public/components/font_picker/__stories__/font_picker.stories.tsx index 0ad1e01252002..34cb3d644cccb 100644 --- a/x-pack/plugins/canvas/public/components/font_picker/font_picker.stories.tsx +++ b/x-pack/plugins/canvas/public/components/font_picker/__stories__/font_picker.stories.tsx @@ -7,8 +7,8 @@ import { action } from '@storybook/addon-actions'; import { storiesOf } from '@storybook/react'; import React from 'react'; -import { americanTypewriter } from '../../../common/lib/fonts'; -import { FontPicker } from './font_picker'; +import { americanTypewriter } from '../../../../common/lib/fonts'; +import { FontPicker } from '../font_picker'; storiesOf('components/FontPicker', module) .add('default', () => ) diff --git a/x-pack/plugins/canvas/public/components/font_picker/font_picker.tsx b/x-pack/plugins/canvas/public/components/font_picker/font_picker.tsx index 556a3c5452160..2b75841e1b7a5 100644 --- a/x-pack/plugins/canvas/public/components/font_picker/font_picker.tsx +++ b/x-pack/plugins/canvas/public/components/font_picker/font_picker.tsx @@ -4,14 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiSuperSelect } from '@elastic/eui'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; -import React, { FunctionComponent } from 'react'; +import { EuiSuperSelect } from '@elastic/eui'; import { fonts, FontValue } from '../../../common/lib/fonts'; interface DisplayedFont { - value: string; label: string; + value: string; } interface Props { @@ -19,9 +19,7 @@ interface Props { value?: FontValue; } -export const FontPicker: FunctionComponent = (props) => { - const { value, onSelect } = props; - +export const FontPicker: FC = ({ value, onSelect }) => { // While fonts are strongly-typed, we also support custom fonts someone might type in. // So let's cast the fonts and allow for additions. const displayedFonts: DisplayedFont[] = fonts; @@ -46,10 +44,10 @@ export const FontPicker: FunctionComponent = (props) => { }; FontPicker.propTypes = { - /** Initial value of the Font Picker. */ - value: PropTypes.string, /** Function to execute when a Font is selected. */ onSelect: PropTypes.func, + /** Initial value of the Font Picker. */ + value: PropTypes.string, }; FontPicker.displayName = 'FontPicker'; diff --git a/x-pack/plugins/canvas/scripts/test_browser.js b/x-pack/plugins/canvas/public/components/font_picker/index.ts similarity index 81% rename from x-pack/plugins/canvas/scripts/test_browser.js rename to x-pack/plugins/canvas/public/components/font_picker/index.ts index e04fac0615284..339021a7e5712 100644 --- a/x-pack/plugins/canvas/scripts/test_browser.js +++ b/x-pack/plugins/canvas/public/components/font_picker/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -require('./_helpers').runGulpTask('canvas:test:karma'); +export { FontPicker } from './font_picker'; diff --git a/x-pack/plugins/canvas/public/components/hover_annotation/hover_annotation.scss b/x-pack/plugins/canvas/public/components/hover_annotation/hover_annotation.scss deleted file mode 100644 index 4771bbb6134be..0000000000000 --- a/x-pack/plugins/canvas/public/components/hover_annotation/hover_annotation.scss +++ /dev/null @@ -1,8 +0,0 @@ -.canvasHoverAnnotation { - position: absolute; - background: none; - transform-origin: center center; /* the default, only for clarity */ - transform-style: preserve-3d; - outline: solid 1px $euiColorVis0; - pointer-events: none; -} diff --git a/x-pack/plugins/canvas/public/components/hover_annotation/index.js b/x-pack/plugins/canvas/public/components/hover_annotation/index.js deleted file mode 100644 index 71c57a25d7960..0000000000000 --- a/x-pack/plugins/canvas/public/components/hover_annotation/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { pure } from 'recompose'; -import { HoverAnnotation as Component } from './hover_annotation'; - -export const HoverAnnotation = pure(Component); diff --git a/x-pack/plugins/canvas/public/components/layout_annotations/alignment_guide.tsx b/x-pack/plugins/canvas/public/components/layout_annotations/alignment_guide.tsx new file mode 100644 index 0000000000000..5ac23ab41f7c0 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/layout_annotations/alignment_guide.tsx @@ -0,0 +1,37 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { FC } from 'react'; +import PropTypes from 'prop-types'; +import { matrixToCSS } from '../../lib/dom'; +import { TransformMatrix3d } from '../../lib/aeroelastic'; + +interface Props { + height: number; + transformMatrix: TransformMatrix3d; + width: number; +} + +export const AlignmentGuide: FC = ({ transformMatrix, width, height }) => ( +
+); + +AlignmentGuide.propTypes = { + height: PropTypes.number.isRequired, + transformMatrix: PropTypes.arrayOf(PropTypes.number).isRequired, + width: PropTypes.number.isRequired, +}; diff --git a/x-pack/plugins/canvas/public/components/layout_annotations/border_connection.tsx b/x-pack/plugins/canvas/public/components/layout_annotations/border_connection.tsx new file mode 100644 index 0000000000000..e47ec3cc89e7b --- /dev/null +++ b/x-pack/plugins/canvas/public/components/layout_annotations/border_connection.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, { FC } from 'react'; +import PropTypes from 'prop-types'; +import { matrixToCSS } from '../../lib/dom'; +import { TransformMatrix3d } from '../../lib/aeroelastic'; + +interface Props { + height: number; + transformMatrix: TransformMatrix3d; + width: number; +} + +export const BorderConnection: FC = ({ transformMatrix, width, height }) => ( +
+); + +BorderConnection.propTypes = { + height: PropTypes.number.isRequired, + transformMatrix: PropTypes.arrayOf(PropTypes.number).isRequired, + width: PropTypes.number.isRequired, +}; diff --git a/x-pack/plugins/canvas/public/components/border_resize_handle/border_resize_handle.js b/x-pack/plugins/canvas/public/components/layout_annotations/border_resize_handle.tsx similarity index 68% rename from x-pack/plugins/canvas/public/components/border_resize_handle/border_resize_handle.js rename to x-pack/plugins/canvas/public/components/layout_annotations/border_resize_handle.tsx index de9d573724836..f7c49205568fe 100644 --- a/x-pack/plugins/canvas/public/components/border_resize_handle/border_resize_handle.js +++ b/x-pack/plugins/canvas/public/components/layout_annotations/border_resize_handle.tsx @@ -4,11 +4,17 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; import { matrixToCSS } from '../../lib/dom'; +import { TransformMatrix3d } from '../../lib/aeroelastic'; -export const BorderResizeHandle = ({ transformMatrix, zoomScale }) => ( +interface Props { + transformMatrix: TransformMatrix3d; + zoomScale?: number; +} + +export const BorderResizeHandle: FC = ({ transformMatrix, zoomScale = 1 }) => (
( BorderResizeHandle.propTypes = { transformMatrix: PropTypes.arrayOf(PropTypes.number).isRequired, + zoomScale: PropTypes.number, }; diff --git a/x-pack/plugins/canvas/public/components/layout_annotations/dragbox_annotation.tsx b/x-pack/plugins/canvas/public/components/layout_annotations/dragbox_annotation.tsx new file mode 100644 index 0000000000000..16a2a626b7975 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/layout_annotations/dragbox_annotation.tsx @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { FC } from 'react'; +import PropTypes from 'prop-types'; +import { matrixToCSS } from '../../lib/dom'; +import { TransformMatrix3d } from '../../lib/aeroelastic'; + +interface Props { + height: number; + transformMatrix: TransformMatrix3d; + width: number; +} + +export const DragBoxAnnotation: FC = ({ transformMatrix, width, height }) => ( +
+); + +DragBoxAnnotation.propTypes = { + transformMatrix: PropTypes.arrayOf(PropTypes.number).isRequired, + width: PropTypes.number.isRequired, + height: PropTypes.number.isRequired, +}; diff --git a/x-pack/plugins/canvas/public/components/hover_annotation/hover_annotation.js b/x-pack/plugins/canvas/public/components/layout_annotations/hover_annotation.tsx similarity index 50% rename from x-pack/plugins/canvas/public/components/hover_annotation/hover_annotation.js rename to x-pack/plugins/canvas/public/components/layout_annotations/hover_annotation.tsx index 7337c0446e31c..a8d73f8bf9ec7 100644 --- a/x-pack/plugins/canvas/public/components/hover_annotation/hover_annotation.js +++ b/x-pack/plugins/canvas/public/components/layout_annotations/hover_annotation.tsx @@ -4,23 +4,32 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; import { matrixToCSS } from '../../lib/dom'; +import { TransformMatrix3d } from '../../lib/aeroelastic'; -export const HoverAnnotation = ({ transformMatrix, width, height }) => { - const newStyle = { - width, - height, - marginLeft: -width / 2, - marginTop: -height / 2, - transform: matrixToCSS(transformMatrix), - }; - return
; -}; +interface Props { + height: number; + transformMatrix: TransformMatrix3d; + width: number; +} + +export const HoverAnnotation: FC = ({ transformMatrix, width, height }) => ( +
+); HoverAnnotation.propTypes = { + height: PropTypes.number.isRequired, transformMatrix: PropTypes.arrayOf(PropTypes.number).isRequired, width: PropTypes.number.isRequired, - height: PropTypes.number.isRequired, }; diff --git a/x-pack/plugins/canvas/public/components/layout_annotations/index.ts b/x-pack/plugins/canvas/public/components/layout_annotations/index.ts new file mode 100644 index 0000000000000..d2334c6a225fe --- /dev/null +++ b/x-pack/plugins/canvas/public/components/layout_annotations/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { AlignmentGuide } from './alignment_guide'; +export { DragBoxAnnotation } from './dragbox_annotation'; +export { HoverAnnotation } from './hover_annotation'; +export { TooltipAnnotation } from './tooltip_annotation'; +export { RotationHandle } from './rotation_handle'; +export { BorderConnection } from './border_connection'; +export { BorderResizeHandle } from './border_resize_handle'; diff --git a/x-pack/plugins/canvas/public/components/layout_annotations/layout_annotations.scss b/x-pack/plugins/canvas/public/components/layout_annotations/layout_annotations.scss new file mode 100644 index 0000000000000..363aa1f241b9d --- /dev/null +++ b/x-pack/plugins/canvas/public/components/layout_annotations/layout_annotations.scss @@ -0,0 +1,81 @@ +.canvasAlignmentGuide { + transform-origin: center center; /* the default, only for clarity */ + transform-style: preserve-3d; +} + +.canvasBorderConnection { + position: absolute; + top: 0; + width: 100%; + height: 100%; + pointer-events: none; + border-top: 1px dashed $euiColorLightShade; + border-left: 1px dashed $euiColorLightShade; +} + +.canvasBorderResizeHandle { + @include euiSlightShadow; + transform-origin: center center; /* the default, only for clarity */ + transform-style: preserve-3d; + display: block; + position: absolute; + height: $euiSizeS; + width: $euiSizeS; + margin-left: -4px; + margin-top: -4px; + background-color: $euiColorEmptyShade; + border: 1px solid $euiColorDarkShade; +} + +.canvasDragBoxAnnotation { + position: absolute; + background: none; + transform-origin: center center; /* the default, only for clarity */ + transform-style: preserve-3d; + outline: dashed 1px $euiColorDarkShade; + pointer-events: none; +} + +.canvasHoverAnnotation { + position: absolute; + background: none; + transform-origin: center center; /* the default, only for clarity */ + transform-style: preserve-3d; + outline: solid 1px $euiColorVis0; + pointer-events: none; +} + +.canvasRotationHandle { + transform-origin: center center; /* the default, only for clarity */ + transform-style: preserve-3d; + display: block; + position: absolute; + height: $euiSizeL; + width: 0; + margin-left: -1px; + margin-top: -12px; + border-top: 1px dashed $euiColorLightShade; + border-left: 1px dashed $euiColorLightShade; +} + +.canvasRotationHandle__handle { + transform-origin: center center; /* the default, only for clarity */ + transform-style: preserve-3d; + display: block; + position: absolute; + height: 9px; + width: 9px; + margin-left: -5px; + margin-top: -6px; + border-radius: 50%; + background-color: $euiColorMediumShade; +} + +.tooltipAnnotation { + @include euiToolTipStyle($size: 's'); + position: absolute; + transform-origin: center center; /* the default, only for clarity */ + transform-style: preserve-3d; + outline: none; + pointer-events: none; +} diff --git a/x-pack/plugins/canvas/public/components/rotation_handle/rotation_handle.js b/x-pack/plugins/canvas/public/components/layout_annotations/rotation_handle.tsx similarity index 60% rename from x-pack/plugins/canvas/public/components/rotation_handle/rotation_handle.js rename to x-pack/plugins/canvas/public/components/layout_annotations/rotation_handle.tsx index dfadbbc39c547..e2a3f57efc672 100644 --- a/x-pack/plugins/canvas/public/components/rotation_handle/rotation_handle.js +++ b/x-pack/plugins/canvas/public/components/layout_annotations/rotation_handle.tsx @@ -4,19 +4,25 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; import { matrixToCSS } from '../../lib/dom'; +import { TransformMatrix3d } from '../../lib/aeroelastic'; -export const RotationHandle = ({ transformMatrix, zoomScale }) => ( +interface Props { + transformMatrix: TransformMatrix3d; + zoomScale?: number; +} + +export const RotationHandle: FC = ({ transformMatrix, zoomScale = 1 }) => (
@@ -24,4 +30,5 @@ export const RotationHandle = ({ transformMatrix, zoomScale }) => ( RotationHandle.propTypes = { transformMatrix: PropTypes.arrayOf(PropTypes.number).isRequired, + zoomScale: PropTypes.number, }; diff --git a/x-pack/plugins/canvas/public/components/tooltip_annotation/tooltip_annotation.js b/x-pack/plugins/canvas/public/components/layout_annotations/tooltip_annotation.tsx similarity index 70% rename from x-pack/plugins/canvas/public/components/tooltip_annotation/tooltip_annotation.js rename to x-pack/plugins/canvas/public/components/layout_annotations/tooltip_annotation.tsx index 1836bfd0162f3..84c527bf7af27 100644 --- a/x-pack/plugins/canvas/public/components/tooltip_annotation/tooltip_annotation.js +++ b/x-pack/plugins/canvas/public/components/layout_annotations/tooltip_annotation.tsx @@ -4,11 +4,17 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; import { matrixToCSS } from '../../lib/dom'; +import { TransformMatrix3d } from '../../lib/aeroelastic'; -export const HoverAnnotation = ({ transformMatrix, text }) => { +interface Props { + transformMatrix: TransformMatrix3d; + text: string; +} + +export const TooltipAnnotation: FC = ({ transformMatrix, text }) => { const newStyle = { transform: `${matrixToCSS(transformMatrix)} translate(1em, -1em)`, }; @@ -19,7 +25,7 @@ export const HoverAnnotation = ({ transformMatrix, text }) => { ); }; -HoverAnnotation.propTypes = { +TooltipAnnotation.propTypes = { transformMatrix: PropTypes.arrayOf(PropTypes.number).isRequired, text: PropTypes.string.isRequired, }; diff --git a/x-pack/plugins/canvas/public/components/loading/__tests__/loading.js b/x-pack/plugins/canvas/public/components/loading/__tests__/loading.js deleted file mode 100644 index c159f478766ce..0000000000000 --- a/x-pack/plugins/canvas/public/components/loading/__tests__/loading.js +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import expect from '@kbn/expect'; -import { shallow } from 'enzyme'; -import { EuiLoadingSpinner, EuiIcon } from '@elastic/eui'; -import { Loading } from '../loading'; - -describe('', () => { - it('uses EuiIcon by default', () => { - const wrapper = shallow(); - expect(wrapper.contains()).to.be.ok; - expect(wrapper.contains()).to.not.be.ok; - }); - - it('uses EuiLoadingSpinner when animating', () => { - const wrapper = shallow(); - expect(wrapper.contains()).to.not.be.ok; - expect(wrapper.contains()).to.be.ok; - }); -}); diff --git a/x-pack/plugins/canvas/public/components/loading/index.ts b/x-pack/plugins/canvas/public/components/loading/index.ts index 81fedf3287184..745639955dcba 100644 --- a/x-pack/plugins/canvas/public/components/loading/index.ts +++ b/x-pack/plugins/canvas/public/components/loading/index.ts @@ -4,7 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; -import { Loading as Component } from './loading'; - -export const Loading = pure(Component); +export { Loading } from './loading'; diff --git a/x-pack/plugins/canvas/public/components/loading/loading.test.tsx b/x-pack/plugins/canvas/public/components/loading/loading.test.tsx new file mode 100644 index 0000000000000..004ecc19c42e2 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/loading/loading.test.tsx @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { shallow } from 'enzyme'; +import { Loading } from './loading'; + +describe('', () => { + it('uses EuiIcon by default', () => { + expect(shallow()).toMatchInlineSnapshot(` +
+ +
+ `); + }); + + it('uses EuiLoadingSpinner when animating', () => { + expect(shallow()).toMatchInlineSnapshot(` +
+ +
+ `); + }); +}); diff --git a/x-pack/plugins/canvas/public/components/loading/loading.tsx b/x-pack/plugins/canvas/public/components/loading/loading.tsx index 67db16d40d426..403be84295312 100644 --- a/x-pack/plugins/canvas/public/components/loading/loading.tsx +++ b/x-pack/plugins/canvas/public/components/loading/loading.tsx @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiIcon, EuiLoadingSpinner, isColorDark } from '@elastic/eui'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; -import React, { FunctionComponent } from 'react'; +import { EuiIcon, EuiLoadingSpinner, isColorDark } from '@elastic/eui'; import { hexToRgb } from '../../../common/lib/hex_to_rgb'; interface Props { @@ -15,7 +15,7 @@ interface Props { text?: string; } -export const Loading: FunctionComponent = ({ +export const Loading: FC = ({ animated = false, text = '', backgroundColor = '#000000', diff --git a/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.tsx b/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.tsx index bc51128cf0c87..7939c1d04631a 100644 --- a/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.tsx +++ b/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.tsx @@ -7,7 +7,7 @@ import React, { useState, useEffect, useRef, FC, useCallback } from 'react'; import { useDebounce } from 'react-use'; -import { useKibana } from '../../../../../../src/plugins/kibana_react/public'; +import { useNotifyService } from '../../services'; import { RenderToDom } from '../render_to_dom'; import { ErrorStrings } from '../../../i18n'; import { RendererHandlers } from '../../../types'; @@ -39,8 +39,7 @@ export const RenderWithFn: FC = ({ width, height, }) => { - const { services } = useKibana(); - const onError = services.canvas.notify.error; + const { error: onError } = useNotifyService(); const [domNode, setDomNode] = useState(null); diff --git a/x-pack/plugins/canvas/public/components/rotation_handle/index.js b/x-pack/plugins/canvas/public/components/rotation_handle/index.js deleted file mode 100644 index 86c99ce12a04e..0000000000000 --- a/x-pack/plugins/canvas/public/components/rotation_handle/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { pure } from 'recompose'; -import { RotationHandle as Component } from './rotation_handle'; - -export const RotationHandle = pure(Component); diff --git a/x-pack/plugins/canvas/public/components/rotation_handle/rotation_handle.scss b/x-pack/plugins/canvas/public/components/rotation_handle/rotation_handle.scss deleted file mode 100644 index 233a86199c483..0000000000000 --- a/x-pack/plugins/canvas/public/components/rotation_handle/rotation_handle.scss +++ /dev/null @@ -1,25 +0,0 @@ -.canvasRotationHandle--connector { - transform-origin: center center; /* the default, only for clarity */ - transform-style: preserve-3d; - display: block; - position: absolute; - height: 24px; - width: 0; - margin-left: -1px; - margin-top: -12px; - border-top: 1px dashed $euiColorLightShade; - border-left: 1px dashed $euiColorLightShade; -} - -.canvasRotationHandle--handle { - transform-origin: center center; /* the default, only for clarity */ - transform-style: preserve-3d; - display: block; - position: absolute; - height: 9px; - width: 9px; - margin-left: -5px; - margin-top: -6px; - border-radius: 50%; - background-color: $euiColorMediumShade; -} diff --git a/x-pack/plugins/canvas/public/components/saved_elements_modal/index.ts b/x-pack/plugins/canvas/public/components/saved_elements_modal/index.ts index c5c1dbc2fdd6e..da2955c146193 100644 --- a/x-pack/plugins/canvas/public/components/saved_elements_modal/index.ts +++ b/x-pack/plugins/canvas/public/components/saved_elements_modal/index.ts @@ -10,8 +10,7 @@ import { compose, withState } from 'recompose'; import { camelCase } from 'lodash'; import { cloneSubgraphs } from '../../lib/clone_subgraphs'; import * as customElementService from '../../lib/custom_element_service'; -import { withKibana } from '../../../../../../src/plugins/kibana_react/public'; -import { WithKibanaProps } from '../../'; +import { withServices, WithServicesProps } from '../../services'; // @ts-expect-error untyped local import { selectToplevelNodes } from '../../state/actions/transient'; // @ts-expect-error untyped local @@ -63,7 +62,7 @@ const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => ({ const mergeProps = ( stateProps: StateProps, dispatchProps: DispatchProps, - ownProps: OwnPropsWithState & WithKibanaProps + ownProps: OwnPropsWithState & WithServicesProps ): ComponentProps => { const { pageId } = stateProps; const { onClose, search, setCustomElements } = ownProps; @@ -91,7 +90,7 @@ const mergeProps = ( try { await findCustomElements(); } catch (err) { - ownProps.kibana.services.canvas.notify.error(err, { + ownProps.services.notify.error(err, { title: `Couldn't find custom elements`, }); } @@ -102,7 +101,7 @@ const mergeProps = ( await customElementService.remove(id); await findCustomElements(); } catch (err) { - ownProps.kibana.services.canvas.notify.error(err, { + ownProps.services.notify.error(err, { title: `Couldn't delete custom elements`, }); } @@ -118,7 +117,7 @@ const mergeProps = ( }); await findCustomElements(); } catch (err) { - ownProps.kibana.services.canvas.notify.error(err, { + ownProps.services.notify.error(err, { title: `Couldn't update custom elements`, }); } @@ -127,7 +126,7 @@ const mergeProps = ( }; export const SavedElementsModal = compose( - withKibana, + withServices, withState('search', 'setSearch', ''), withState('customElements', 'setCustomElements', []), connect(mapStateToProps, mapDispatchToProps, mergeProps) diff --git a/x-pack/plugins/canvas/public/components/shape_picker/index.ts b/x-pack/plugins/canvas/public/components/shape_picker/index.ts index d3ed85831cbe2..3ec86e45af236 100644 --- a/x-pack/plugins/canvas/public/components/shape_picker/index.ts +++ b/x-pack/plugins/canvas/public/components/shape_picker/index.ts @@ -4,8 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; - -import { ShapePicker as Component } from './shape_picker'; - -export const ShapePicker = pure(Component); +export { ShapePicker } from './shape_picker'; diff --git a/x-pack/plugins/canvas/public/components/shape_picker/shape_picker.tsx b/x-pack/plugins/canvas/public/components/shape_picker/shape_picker.tsx index 56874fd3080f7..263654522c059 100644 --- a/x-pack/plugins/canvas/public/components/shape_picker/shape_picker.tsx +++ b/x-pack/plugins/canvas/public/components/shape_picker/shape_picker.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; import { EuiFlexGrid, EuiFlexItem, EuiLink } from '@elastic/eui'; import { ShapePreview } from '../shape_preview'; @@ -16,7 +16,7 @@ interface Props { onChange?: (key: string) => void; } -export const ShapePicker = ({ shapes, onChange = () => {} }: Props) => { +export const ShapePicker: FC = ({ shapes, onChange = () => {} }) => { return ( {Object.keys(shapes) @@ -33,6 +33,6 @@ export const ShapePicker = ({ shapes, onChange = () => {} }: Props) => { }; ShapePicker.propTypes = { - shapes: PropTypes.object.isRequired, onChange: PropTypes.func, + shapes: PropTypes.object.isRequired, }; diff --git a/x-pack/plugins/canvas/public/components/shape_picker_popover/index.tsx b/x-pack/plugins/canvas/public/components/shape_picker_popover/index.tsx index 1d4ae25a38fa2..06619c0626daf 100644 --- a/x-pack/plugins/canvas/public/components/shape_picker_popover/index.tsx +++ b/x-pack/plugins/canvas/public/components/shape_picker_popover/index.tsx @@ -4,8 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; - -import { ShapePickerPopover as Component } from './shape_picker_popover'; - -export const ShapePickerPopover = pure(Component); +export { ShapePickerPopover } from './shape_picker_popover'; diff --git a/x-pack/plugins/canvas/public/components/shape_picker_popover/shape_picker_popover.tsx b/x-pack/plugins/canvas/public/components/shape_picker_popover/shape_picker_popover.tsx index d42e08d2bc852..d61d9e47a3a78 100644 --- a/x-pack/plugins/canvas/public/components/shape_picker_popover/shape_picker_popover.tsx +++ b/x-pack/plugins/canvas/public/components/shape_picker_popover/shape_picker_popover.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; import { EuiLink, EuiPanel } from '@elastic/eui'; import { Popover } from '../popover'; @@ -20,7 +20,7 @@ interface Props { ariaLabel?: string; } -export const ShapePickerPopover = ({ shapes, onChange, value, ariaLabel }: Props) => { +export const ShapePickerPopover: FC = ({ shapes, onChange, value, ariaLabel }) => { const button = (handleClick: React.MouseEventHandler) => ( @@ -37,7 +37,8 @@ export const ShapePickerPopover = ({ shapes, onChange, value, ariaLabel }: Props }; ShapePickerPopover.propTypes = { + ariaLabel: PropTypes.string, + onChange: PropTypes.func, shapes: PropTypes.object.isRequired, value: PropTypes.string, - onChange: PropTypes.func, }; diff --git a/x-pack/plugins/canvas/public/components/shape_preview/index.ts b/x-pack/plugins/canvas/public/components/shape_preview/index.ts index 4320a10d97a85..6027b1227a99a 100644 --- a/x-pack/plugins/canvas/public/components/shape_preview/index.ts +++ b/x-pack/plugins/canvas/public/components/shape_preview/index.ts @@ -4,8 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; - -import { ShapePreview as Component } from './shape_preview'; - -export const ShapePreview = pure(Component); +export { ShapePreview } from './shape_preview'; diff --git a/x-pack/plugins/canvas/public/components/shape_preview/shape_preview.tsx b/x-pack/plugins/canvas/public/components/shape_preview/shape_preview.tsx index 4f67945e9ce13..3ff18f3aa4bc4 100644 --- a/x-pack/plugins/canvas/public/components/shape_preview/shape_preview.tsx +++ b/x-pack/plugins/canvas/public/components/shape_preview/shape_preview.tsx @@ -4,14 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; interface Props { shape?: string; } -export const ShapePreview = ({ shape }: Props) => { +export const ShapePreview: FC = ({ shape }) => { if (!shape) { return
; } diff --git a/x-pack/plugins/canvas/public/components/text_style_picker/__stories__/__snapshots__/text_style_picker.stories.storyshot b/x-pack/plugins/canvas/public/components/text_style_picker/__stories__/__snapshots__/text_style_picker.stories.storyshot new file mode 100644 index 0000000000000..ad236e701ceb0 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/text_style_picker/__stories__/__snapshots__/text_style_picker.stories.storyshot @@ -0,0 +1,975 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Storyshots components/TextStylePicker default 1`] = ` +
+
+
+
+
+
+ +
+
+ + Select an option: + , is selected + +
+
+
+
+
+
+ +
+ +
+ + +
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+ + +
+
+ + +
+
+ + +
+
+
+
+
+
+
+
+ + +
+
+ + +
+
+ + +
+
+
+
+
+
+
+`; + +exports[`Storyshots components/TextStylePicker interactive 1`] = ` +
+
+
+
+
+
+ +
+
+ + Select an option: + , is selected + +
+
+
+
+
+
+ +
+ +
+ + +
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+ + +
+
+ + +
+
+ + +
+
+
+
+
+
+
+
+ + +
+
+ + +
+
+ + +
+
+
+
+
+
+
+`; diff --git a/x-pack/plugins/canvas/public/components/text_style_picker/__stories__/text_style_picker.stories.tsx b/x-pack/plugins/canvas/public/components/text_style_picker/__stories__/text_style_picker.stories.tsx new file mode 100644 index 0000000000000..b33a34fcd5e65 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/text_style_picker/__stories__/text_style_picker.stories.tsx @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useState } from 'react'; +import { storiesOf } from '@storybook/react'; +import { action } from '@storybook/addon-actions'; + +import { TextStylePicker } from '../text_style_picker'; + +const Interactive = () => { + const [props, setProps] = useState({}); + return ; +}; + +storiesOf('components/TextStylePicker', module) + .addDecorator((fn) =>
{fn()}
) + .add('default', () => ) + .add('interactive', () => ); diff --git a/x-pack/plugins/canvas/public/components/text_style_picker/font_sizes.js b/x-pack/plugins/canvas/public/components/text_style_picker/font_sizes.ts similarity index 100% rename from x-pack/plugins/canvas/public/components/text_style_picker/font_sizes.js rename to x-pack/plugins/canvas/public/components/text_style_picker/font_sizes.ts diff --git a/x-pack/plugins/canvas/public/components/text_style_picker/index.js b/x-pack/plugins/canvas/public/components/text_style_picker/index.js deleted file mode 100644 index 79bde95723682..0000000000000 --- a/x-pack/plugins/canvas/public/components/text_style_picker/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { pure } from 'recompose'; -import { TextStylePicker as Component } from './text_style_picker'; - -export const TextStylePicker = pure(Component); diff --git a/x-pack/plugins/canvas/scripts/test_dev.js b/x-pack/plugins/canvas/public/components/text_style_picker/index.ts similarity index 81% rename from x-pack/plugins/canvas/scripts/test_dev.js rename to x-pack/plugins/canvas/public/components/text_style_picker/index.ts index 8b03d7930d473..16fb39b660a0c 100644 --- a/x-pack/plugins/canvas/scripts/test_dev.js +++ b/x-pack/plugins/canvas/public/components/text_style_picker/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -require('./_helpers').runGulpTask('canvas:karma:debug'); +export { TextStylePicker } from './text_style_picker'; diff --git a/x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.js b/x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.tsx similarity index 54% rename from x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.js rename to x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.tsx index 48d52abb03125..3dfc55919395d 100644 --- a/x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.js +++ b/x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.tsx @@ -4,9 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { FC, useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { EuiFlexGroup, EuiFlexItem, EuiSelect, EuiSpacer, EuiButtonGroup } from '@elastic/eui'; +import { FontValue } from 'src/plugins/expressions'; import { ComponentStrings } from '../../../i18n'; import { FontPicker } from '../font_picker'; import { ColorPickerPopover } from '../color_picker_popover'; @@ -14,54 +15,75 @@ import { fontSizes } from './font_sizes'; const { TextStylePicker: strings } = ComponentStrings; -export const TextStylePicker = ({ - family, - size, - align, - color, - weight, - underline, - italic, - onChange, - colors, -}) => { - const alignmentButtons = [ - { - id: 'left', - label: strings.getAlignLeftOption(), - iconType: 'editorAlignLeft', - }, - { - id: 'center', - label: strings.getAlignCenterOption(), - iconType: 'editorAlignCenter', - }, - { - id: 'right', - label: strings.getAlignRightOption(), - iconType: 'editorAlignRight', - }, - ]; - - const styleButtons = [ - { - id: 'bold', - label: strings.getStyleBoldOption(), - iconType: 'editorBold', - }, - { - id: 'italic', - label: strings.getStyleItalicOption(), - iconType: 'editorItalic', - }, - { - id: 'underline', - label: strings.getStyleUnderlineOption(), - iconType: 'editorUnderline', - }, - ]; - - const stylesSelectedMap = { +interface BaseProps { + family?: FontValue; + size?: number; + align?: 'left' | 'center' | 'right'; + color?: string; + weight?: 'bold' | 'normal'; + underline?: boolean; + italic?: boolean; +} + +interface Props extends BaseProps { + colors?: string[]; + onChange: (props: BaseProps) => void; +} + +type StyleType = 'bold' | 'italic' | 'underline'; + +const alignmentButtons = [ + { + id: 'left', + label: strings.getAlignLeftOption(), + iconType: 'editorAlignLeft', + }, + { + id: 'center', + label: strings.getAlignCenterOption(), + iconType: 'editorAlignCenter', + }, + { + id: 'right', + label: strings.getAlignRightOption(), + iconType: 'editorAlignRight', + }, +]; + +const styleButtons = [ + { + id: 'bold', + label: strings.getStyleBoldOption(), + iconType: 'editorBold', + }, + { + id: 'italic', + label: strings.getStyleItalicOption(), + iconType: 'editorItalic', + }, + { + id: 'underline', + label: strings.getStyleUnderlineOption(), + iconType: 'editorUnderline', + }, +]; + +export const TextStylePicker: FC = (props) => { + const [style, setStyle] = useState(props); + + const { + align = 'left', + color, + colors, + family, + italic = false, + onChange, + size = 14, + underline = false, + weight = 'normal', + } = style; + + const stylesSelectedMap: Record = { ['bold']: weight === 'bold', ['italic']: Boolean(italic), ['underline']: Boolean(underline), @@ -72,31 +94,22 @@ export const TextStylePicker = ({ fontSizes.sort((a, b) => a - b); } - const doChange = (propName, value) => { - onChange({ - family, - size, - align, - color, - weight: weight || 'normal', - underline: underline || false, - italic: italic || false, - [propName]: value, - }); - }; + useEffect(() => onChange(style), [onChange, style]); - const onAlignmentChange = (optionId) => doChange('align', optionId); + const doChange = (propName: keyof Props, value: string | boolean | number) => { + setStyle({ ...style, [propName]: value }); + }; - const onStyleChange = (optionId) => { - let prop; + const onStyleChange = (optionId: string) => { + let prop: 'weight' | 'italic' | 'underline'; let value; if (optionId === 'bold') { prop = 'weight'; value = !stylesSelectedMap[optionId] ? 'bold' : 'normal'; } else { - prop = optionId; - value = !stylesSelectedMap[optionId]; + prop = optionId as 'italic' | 'underline'; + value = !stylesSelectedMap[prop]; } doChange(prop, value); @@ -106,14 +119,18 @@ export const TextStylePicker = ({
- doChange('family', value)} /> + {family ? ( + doChange('family', value)} /> + ) : ( + doChange('family', value)} /> + )} doChange('size', Number(e.target.value))} - options={fontSizes.map((size) => ({ text: String(size), value: size }))} + options={fontSizes.map((fontSize) => ({ text: String(fontSize), value: fontSize }))} prepend="Size" /> @@ -147,7 +164,7 @@ export const TextStylePicker = ({ buttonSize="compressed" isIconOnly idSelected={align} - onChange={onAlignmentChange} + onChange={(optionId: string) => doChange('align', optionId)} className="canvasSidebar__buttonGroup" /> @@ -159,9 +176,9 @@ export const TextStylePicker = ({ TextStylePicker.propTypes = { family: PropTypes.string, size: PropTypes.number, - align: PropTypes.string, + align: PropTypes.oneOf(['left', 'center', 'right']), color: PropTypes.string, - weight: PropTypes.string, + weight: PropTypes.oneOf(['normal', 'bold']), underline: PropTypes.bool, italic: PropTypes.bool, onChange: PropTypes.func.isRequired, @@ -171,4 +188,5 @@ TextStylePicker.propTypes = { TextStylePicker.defaultProps = { align: 'left', size: 14, + weight: 'normal', }; diff --git a/x-pack/plugins/canvas/public/components/tooltip_annotation/index.js b/x-pack/plugins/canvas/public/components/tooltip_annotation/index.js deleted file mode 100644 index c6d545be560ce..0000000000000 --- a/x-pack/plugins/canvas/public/components/tooltip_annotation/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { pure } from 'recompose'; -import { HoverAnnotation as Component } from './tooltip_annotation'; - -export const TooltipAnnotation = pure(Component); diff --git a/x-pack/plugins/canvas/public/components/tooltip_annotation/tooltip_annotation.scss b/x-pack/plugins/canvas/public/components/tooltip_annotation/tooltip_annotation.scss deleted file mode 100644 index d91e49c0c628f..0000000000000 --- a/x-pack/plugins/canvas/public/components/tooltip_annotation/tooltip_annotation.scss +++ /dev/null @@ -1,8 +0,0 @@ -.tooltipAnnotation { - @include euiToolTipStyle($size: 's'); - position: absolute; - transform-origin: center center; /* the default, only for clarity */ - transform-style: preserve-3d; - outline: none; - pointer-events: none; -} diff --git a/x-pack/plugins/canvas/public/components/tooltip_icon/index.ts b/x-pack/plugins/canvas/public/components/tooltip_icon/index.ts index 6e71baa364785..55c2f7090629c 100644 --- a/x-pack/plugins/canvas/public/components/tooltip_icon/index.ts +++ b/x-pack/plugins/canvas/public/components/tooltip_icon/index.ts @@ -4,8 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; -import { TooltipIcon as Component } from './tooltip_icon'; -export { IconType } from './tooltip_icon'; - -export const TooltipIcon = pure(Component); +export { TooltipIcon, IconType } from './tooltip_icon'; diff --git a/x-pack/plugins/canvas/public/components/tooltip_icon/tooltip_icon.tsx b/x-pack/plugins/canvas/public/components/tooltip_icon/tooltip_icon.tsx index 78c2b0ec53c9f..d91bb4bc9add9 100644 --- a/x-pack/plugins/canvas/public/components/tooltip_icon/tooltip_icon.tsx +++ b/x-pack/plugins/canvas/public/components/tooltip_icon/tooltip_icon.tsx @@ -5,7 +5,7 @@ */ /* eslint react/forbid-elements: 0 */ -import React from 'react'; +import React, { FC } from 'react'; import PropTypes from 'prop-types'; import { EuiIconTip, PropsOf } from '@elastic/eui'; @@ -21,7 +21,7 @@ interface Props extends Omit { icon: IconType; } -export const TooltipIcon = ({ icon = IconType.info, ...rest }: Props) => { +export const TooltipIcon: FC = ({ icon = IconType.info, ...rest }) => { const icons = { [IconType.error]: { type: 'alert', color: 'danger' }, [IconType.warning]: { type: 'alert', color: 'warning' }, diff --git a/x-pack/plugins/canvas/public/components/var_config/index.tsx b/x-pack/plugins/canvas/public/components/var_config/index.tsx index 526037b79e0e0..ca40bd07877f0 100644 --- a/x-pack/plugins/canvas/public/components/var_config/index.tsx +++ b/x-pack/plugins/canvas/public/components/var_config/index.tsx @@ -7,27 +7,19 @@ import React, { FC } from 'react'; import copy from 'copy-to-clipboard'; import { VarConfig as ChildComponent } from './var_config'; -import { - withKibana, - KibanaReactContextValue, - KibanaServices, -} from '../../../../../../src/plugins/kibana_react/public'; -import { CanvasServices } from '../../services'; - +import { useNotifyService } from '../../services'; import { ComponentStrings } from '../../../i18n'; - import { CanvasVariable } from '../../../types'; const { VarConfig: strings } = ComponentStrings; interface Props { - kibana: KibanaReactContextValue<{ canvas: CanvasServices } & KibanaServices>; - variables: CanvasVariable[]; setVariables: (variables: CanvasVariable[]) => void; } -const WrappedComponent: FC = ({ kibana, variables, setVariables }) => { +export const VarConfig: FC = ({ variables, setVariables }) => { + const { success } = useNotifyService(); const onDeleteVar = (v: CanvasVariable) => { const index = variables.findIndex((targetVar: CanvasVariable) => { return targetVar.name === v.name; @@ -36,15 +28,14 @@ const WrappedComponent: FC = ({ kibana, variables, setVariables }) => { const newVars = [...variables]; newVars.splice(index, 1); setVariables(newVars); - - kibana.services.canvas.notify.success(strings.getDeleteNotificationDescription()); + success(strings.getDeleteNotificationDescription()); } }; const onCopyVar = (v: CanvasVariable) => { const snippetStr = `{var "${v.name}"}`; copy(snippetStr, { debug: true }); - kibana.services.canvas.notify.success(strings.getCopyNotificationDescription()); + success(strings.getCopyNotificationDescription()); }; const onAddVar = (v: CanvasVariable) => { @@ -62,5 +53,3 @@ const WrappedComponent: FC = ({ kibana, variables, setVariables }) => { return ; }; - -export const VarConfig = withKibana(WrappedComponent); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/element_menu/index.tsx b/x-pack/plugins/canvas/public/components/workpad_header/element_menu/index.tsx index 13b2cace13a40..264873fc994dd 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/element_menu/index.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/element_menu/index.tsx @@ -8,7 +8,6 @@ import React from 'react'; import { connect } from 'react-redux'; import { compose, withProps } from 'recompose'; import { Dispatch } from 'redux'; -import { withKibana } from '../../../../../../../src/plugins/kibana_react/public/'; import { State, ElementSpec } from '../../../../types'; // @ts-expect-error untyped local import { elementsRegistry } from '../../../lib/elements_registry'; @@ -44,6 +43,5 @@ const mergeProps = (stateProps: StateProps, dispatchProps: DispatchProps) => ({ export const ElementMenu = compose( connect(mapStateToProps, mapDispatchToProps, mergeProps), - withKibana, withProps(() => ({ elements: elementsRegistry.toJS() })) )(Component); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/index.ts b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/index.ts index 17fcc50334a8f..01bcfebc0dba9 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/index.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/index.ts @@ -13,8 +13,7 @@ import { downloadWorkpad } from '../../../lib/download_workpad'; import { ShareMenu as Component, Props as ComponentProps } from './share_menu'; import { getPdfUrl, createPdf } from './utils'; import { State, CanvasWorkpad } from '../../../../types'; -import { withKibana } from '../../../../../../../src/plugins/kibana_react/public/'; -import { WithKibanaProps } from '../../../index'; +import { withServices, WithServicesProps } from '../../../services'; import { ComponentStrings } from '../../../../i18n'; @@ -43,12 +42,16 @@ interface Props { export const ShareMenu = compose( connect(mapStateToProps), - withKibana, + withServices, withProps( - ({ workpad, pageCount, kibana }: Props & WithKibanaProps): ComponentProps => ({ + ({ workpad, pageCount, services }: Props & WithServicesProps): ComponentProps => ({ getExportUrl: (type) => { if (type === 'pdf') { - const pdfUrl = getPdfUrl(workpad, { pageCount }, kibana.services.http.basePath); + const pdfUrl = getPdfUrl( + workpad, + { pageCount }, + services.platform.getBasePathInterface() + ); return getAbsoluteUrl(pdfUrl); } @@ -57,10 +60,10 @@ export const ShareMenu = compose( onCopy: (type) => { switch (type) { case 'pdf': - kibana.services.canvas.notify.info(strings.getCopyPDFMessage()); + services.notify.info(strings.getCopyPDFMessage()); break; case 'reportingConfig': - kibana.services.canvas.notify.info(strings.getCopyReportingConfigMessage()); + services.notify.info(strings.getCopyReportingConfigMessage()); break; default: throw new Error(strings.getUnknownExportErrorMessage(type)); @@ -69,9 +72,9 @@ export const ShareMenu = compose( onExport: (type) => { switch (type) { case 'pdf': - return createPdf(workpad, { pageCount }, kibana.services.http.basePath) + return createPdf(workpad, { pageCount }, services.platform.getBasePathInterface()) .then(({ data }: { data: { job: { id: string } } }) => { - kibana.services.canvas.notify.info(strings.getExportPDFMessage(), { + services.notify.info(strings.getExportPDFMessage(), { title: strings.getExportPDFTitle(workpad.name), }); @@ -79,7 +82,7 @@ export const ShareMenu = compose( jobCompletionNotifications.add(data.job.id); }) .catch((err: Error) => { - kibana.services.canvas.notify.error(err, { + services.notify.error(err, { title: strings.getExportPDFErrorTitle(workpad.name), }); }); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/index.ts b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/index.ts index ddf1a12775cae..e2a05d13b017e 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/index.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/index.ts @@ -7,7 +7,6 @@ import { connect } from 'react-redux'; import { compose, withHandlers } from 'recompose'; import { Dispatch } from 'redux'; -import { withKibana } from '../../../../../../../src/plugins/kibana_react/public/'; import { zoomHandlerCreators } from '../../../lib/app_handler_creators'; import { State, CanvasWorkpadBoundingBox } from '../../../../types'; // @ts-expect-error untyped local @@ -97,6 +96,5 @@ const mergeProps = ( export const ViewMenu = compose( connect(mapStateToProps, mapDispatchToProps, mergeProps), - withKibana, withHandlers(zoomHandlerCreators) )(Component); diff --git a/x-pack/plugins/canvas/public/components/workpad_loader/index.js b/x-pack/plugins/canvas/public/components/workpad_loader/index.js index ab07d5d722405..f747cb677a576 100644 --- a/x-pack/plugins/canvas/public/components/workpad_loader/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_loader/index.js @@ -14,7 +14,7 @@ import { getWorkpad } from '../../state/selectors/workpad'; import { getId } from '../../lib/get_id'; import { downloadWorkpad } from '../../lib/download_workpad'; import { ComponentStrings, ErrorStrings } from '../../../i18n'; -import { withKibana } from '../../../../../../src/plugins/kibana_react/public'; +import { withServices } from '../../services'; import { WorkpadLoader as Component } from './workpad_loader'; const { WorkpadLoader: strings } = ComponentStrings; @@ -31,11 +31,11 @@ export const WorkpadLoader = compose( }), connect(mapStateToProps), withState('workpads', 'setWorkpads', null), - withKibana, - withProps(({ kibana }) => ({ - notify: kibana.services.canvas.notify, + withServices, + withProps(({ services }) => ({ + notify: services.notify, })), - withHandlers(({ kibana }) => ({ + withHandlers(({ services }) => ({ // Workpad creation via navigation createWorkpad: (props) => async (workpad) => { // workpad data uploaded, create and load it @@ -44,7 +44,7 @@ export const WorkpadLoader = compose( await workpadService.create(workpad); props.router.navigateTo('loadWorkpad', { id: workpad.id, page: 1 }); } catch (err) { - kibana.services.canvas.notify.error(err, { + services.notify.error(err, { title: errors.getUploadFailureErrorMessage(), }); } @@ -60,7 +60,7 @@ export const WorkpadLoader = compose( const workpads = await workpadService.find(text); setWorkpads(workpads); } catch (err) { - kibana.services.canvas.notify.error(err, { title: errors.getFindFailureErrorMessage() }); + services.notify.error(err, { title: errors.getFindFailureErrorMessage() }); } }, @@ -76,7 +76,7 @@ export const WorkpadLoader = compose( await workpadService.create(workpad); props.router.navigateTo('loadWorkpad', { id: workpad.id, page: 1 }); } catch (err) { - kibana.services.canvas.notify.error(err, { title: errors.getCloneFailureErrorMessage() }); + services.notify.error(err, { title: errors.getCloneFailureErrorMessage() }); } }, @@ -122,7 +122,7 @@ export const WorkpadLoader = compose( }; if (errored.length > 0) { - kibana.services.canvas.notify.error(errors.getDeleteFailureErrorMessage()); + services.notify.error(errors.getDeleteFailureErrorMessage()); } setWorkpads(workpadState); @@ -137,7 +137,7 @@ export const WorkpadLoader = compose( })), withProps((props) => ({ formatDate: (date) => { - const dateFormat = props.kibana.services.uiSettings.get('dateFormat'); + const dateFormat = props.services.platform.getUISetting('dateFormat'); return date && moment(date).format(dateFormat); }, })) diff --git a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/index.js b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/index.js index 41f78165a7394..632ec1ad5e004 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/index.js @@ -127,7 +127,7 @@ const componentLayoutState = ({ gestureState: aeroStore ? aeroStore.getCurrentState().currentScene.gestureState : { - cursor: { x: 0, y: 0 }, + cursor: { x: Infinity, y: Infinity }, mouseIsDown: false, mouseButtonState: { buttonState: 'up', downX: null, downY: null }, }, diff --git a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/interactive_workpad_page.js b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/interactive_workpad_page.js index 152da323e89ea..4089a1d709299 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/interactive_workpad_page.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/interactive_workpad_page.js @@ -6,13 +6,15 @@ import React, { PureComponent } from 'react'; import { ElementWrapper } from '../../element_wrapper'; -import { AlignmentGuide } from '../../alignment_guide'; -import { DragBoxAnnotation } from '../../dragbox_annotation'; -import { HoverAnnotation } from '../../hover_annotation'; -import { TooltipAnnotation } from '../../tooltip_annotation'; -import { RotationHandle } from '../../rotation_handle'; -import { BorderConnection } from '../../border_connection'; -import { BorderResizeHandle } from '../../border_resize_handle'; +import { + AlignmentGuide, + DragBoxAnnotation, + HoverAnnotation, + TooltipAnnotation, + RotationHandle, + BorderConnection, + BorderResizeHandle, +} from '../../layout_annotations'; import { WorkpadShortcuts } from '../../workpad_shortcuts'; import { interactiveWorkpadPagePropTypes } from '../prop_types'; import { InteractionBoundary } from './interaction_boundary'; diff --git a/x-pack/plugins/canvas/public/components/workpad_templates/index.tsx b/x-pack/plugins/canvas/public/components/workpad_templates/index.tsx index f35bba3fd598d..35b0e2bb19e3e 100644 --- a/x-pack/plugins/canvas/public/components/workpad_templates/index.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_templates/index.tsx @@ -10,12 +10,11 @@ import { RouterContext } from '../router'; import { ComponentStrings } from '../../../i18n/components'; // @ts-expect-error import * as workpadService from '../../lib/workpad_service'; -import { useKibana } from '../../../../../../src/plugins/kibana_react/public'; import { WorkpadTemplates as Component } from './workpad_templates'; import { CanvasTemplate } from '../../../types'; -import { UseKibanaProps } from '../../'; import { list } from '../../lib/template_service'; import { applyTemplateStrings } from '../../../i18n/templates/apply_strings'; +import { useNotifyService } from '../../services'; interface WorkpadTemplatesProps { onClose: () => void; @@ -33,7 +32,7 @@ export const WorkpadTemplates: FunctionComponent = ({ onC const [creatingFromTemplateName, setCreatingFromTemplateName] = useState( undefined ); - const kibana = useKibana(); + const { error } = useNotifyService(); useEffect(() => { if (!templates) { @@ -60,9 +59,9 @@ export const WorkpadTemplates: FunctionComponent = ({ onC if (router) { router.navigateTo('loadWorkpad', { id: result.data.id, page: 1 }); } - } catch (error) { + } catch (e) { setCreatingFromTemplateName(undefined); - kibana.services.canvas.notify.error(error, { + error(e, { title: `Couldn't create workpad from template`, }); } diff --git a/x-pack/plugins/canvas/public/functions/__tests__/asset.js b/x-pack/plugins/canvas/public/functions/__tests__/asset.js deleted file mode 100644 index c21faf9a2e227..0000000000000 --- a/x-pack/plugins/canvas/public/functions/__tests__/asset.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import { functionWrapper } from '../../../__tests__/helpers/function_wrapper'; -import { asset } from '../asset'; - -// TODO: restore this test -// will require the ability to mock the store, or somehow remove the function's dependency on getState -describe.skip('asset', () => { - const fn = functionWrapper(asset); - - it('throws if asset could not be retrieved by ID', () => { - const throwsErr = () => { - return fn(null, { id: 'boo' }); - }; - expect(throwsErr).to.throwException((err) => { - expect(err.message).to.be('Could not get the asset by ID: boo'); - }); - }); - - it('returns the asset for found asset ID', () => { - expect(fn(null, { id: 'yay' })).to.be('here is your image'); - }); -}); diff --git a/x-pack/plugins/canvas/public/lib/__tests__/find_expression_type.js b/x-pack/plugins/canvas/public/lib/__tests__/find_expression_type.js deleted file mode 100644 index 58f5c5eb303bd..0000000000000 --- a/x-pack/plugins/canvas/public/lib/__tests__/find_expression_type.js +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -// import expect from 'expect.js'; -// import proxyquire from 'proxyquire'; -// import { Registry } from '../../../common/lib/registry'; - -// const registries = { -// datasource: new Registry(), -// transform: new Registry(), -// model: new Registry(), -// view: new Registry(), -// }; - -// const { findExpressionType } = proxyquire.noCallThru().load('../find_expression_type', { -// '../expression_types/datasource': { -// datasourceRegistry: registries.datasource, -// }, -// '../expression_types/transform': { -// transformRegistry: registries.transform, -// }, -// '../expression_types/model': { -// modelRegistry: registries.model, -// }, -// '../expression_types/view': { -// viewRegistry: registries.view, -// }, -// }); - -// describe('findExpressionType', () => { -// let expTypes; - -// beforeEach(() => { -// expTypes = []; -// const keys = Object.keys(registries); -// keys.forEach(key => { -// const reg = registries[key]; -// reg.reset(); - -// const expObj = () => ({ -// name: `__test_${key}`, -// key, -// }); -// expTypes.push(expObj); -// reg.register(expObj); -// }); -// }); - -// describe('all types', () => { -// it('returns the matching item, by name', () => { -// const match = findExpressionType('__test_model'); -// expect(match).to.eql(expTypes[2]()); -// }); - -// it('returns null when nothing is found', () => { -// const match = findExpressionType('@@nope_nope_nope'); -// expect(match).to.equal(null); -// }); - -// it('throws with multiple matches', () => { -// const commonName = 'commonName'; -// registries.transform.register(() => ({ -// name: commonName, -// })); -// registries.model.register(() => ({ -// name: commonName, -// })); - -// const check = () => { -// findExpressionType(commonName); -// }; -// expect(check).to.throwException(/Found multiple expressions/i); -// }); -// }); - -// describe('specific type', () => { -// it('return the match item, by name and type', () => { -// const match = findExpressionType('__test_view', 'view'); -// expect(match).to.eql(expTypes[3]()); -// }); - -// it('returns null with no match by name and type', () => { -// const match = findExpressionType('__test_view', 'datasource'); -// expect(match).to.equal(null); -// }); -// }); -// }); - -// TODO: restore this test -// proxyquire can not be used to inject mock registries - -describe.skip('findExpressionType', () => {}); diff --git a/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js b/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js deleted file mode 100644 index 99d8305768240..0000000000000 --- a/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import lzString from 'lz-string'; -import { historyProvider } from '../history_provider'; - -function createState() { - return { - transient: { - selectedPage: 'page-f3ce-4bb7-86c8-0417606d6592', - selectedToplevelNodes: ['element-d88c-4bbd-9453-db22e949b92e'], - resolvedArgs: {}, - }, - persistent: { - schemaVersion: 0, - time: new Date().getTime(), - }, - }; -} - -describe.skip('historyProvider', () => { - let history; - let state; - - beforeEach(() => { - history = historyProvider(); - state = createState(); - }); - - describe('instances', () => { - it('should return the same instance for the same window object', () => { - expect(historyProvider()).to.equal(history); - }); - - it('should return different instance for different window object', () => { - const newWindow = {}; - expect(historyProvider(newWindow)).not.to.be(history); - }); - }); - - describe('push updates', () => { - beforeEach(() => { - history.push(state); - }); - - afterEach(() => { - // reset state back to initial after each test - history.undo(); - }); - - describe('push', () => { - it('should add state to location', () => { - expect(history.getLocation().state).to.eql(state); - }); - - it('should push compressed state into history', () => { - const hist = history.historyInstance; - expect(hist.location.state).to.equal(lzString.compress(JSON.stringify(state))); - }); - }); - - describe.skip('undo', () => { - it('should move history back', () => { - // pushed location has state value - expect(history.getLocation().state).to.eql(state); - - // back to initial location with null state - history.undo(); - expect(history.getLocation().state).to.be(null); - }); - }); - - describe.skip('redo', () => { - it('should move history forward', () => { - // back to initial location, with null state - history.undo(); - expect(history.getLocation().state).to.be(null); - - // return to pushed location, with state value - history.redo(); - expect(history.getLocation().state).to.eql(state); - }); - }); - }); - - describe.skip('replace updates', () => { - beforeEach(() => { - history.replace(state); - }); - - afterEach(() => { - // reset history to default after each test - history.replace(null); - }); - - describe('replace', () => { - it('should replace state in window history', () => { - expect(history.getLocation().state).to.eql(state); - }); - - it('should replace compressed state into history', () => { - const hist = history.historyInstance; - expect(hist.location.state).to.equal(lzString.compress(JSON.stringify(state))); - }); - }); - }); - - describe('onChange', () => { - const createOnceHandler = (history, done, fn) => { - const teardown = history.onChange((location, prevLocation) => { - if (typeof fn === 'function') { - fn(location, prevLocation); - } - teardown(); - done(); - }); - }; - - it('should return a method to remove the listener', () => { - const handler = () => 'hello world'; - const teardownFn = history.onChange(handler); - - expect(teardownFn).to.be.a('function'); - - // teardown the listener - teardownFn(); - }); - - it('should call handler on state change', (done) => { - createOnceHandler(history, done, (loc) => { - expect(loc).to.be.a('object'); - }); - - history.push({}); - }); - - it('should pass location object to handler', (done) => { - createOnceHandler(history, done, (location) => { - expect(location.pathname).to.be.a('string'); - expect(location.hash).to.be.a('string'); - expect(location.state).to.be.an('object'); - expect(location.action).to.equal('push'); - }); - - history.push(state); - }); - - it('should pass decompressed state to handler', (done) => { - createOnceHandler(history, done, ({ state: curState }) => { - expect(curState).to.eql(state); - }); - - history.push(state); - }); - - it('should pass in the previous location object to handler', (done) => { - createOnceHandler(history, done, (location, prevLocation) => { - expect(prevLocation.pathname).to.be.a('string'); - expect(prevLocation.hash).to.be.a('string'); - expect(prevLocation.state).to.be(null); - expect(prevLocation.action).to.equal('push'); - }); - - history.push(state); - }); - }); - - describe('resetOnChange', () => { - // the history onChange handler was made async and now there's no way to know when the handler was called - // TODO: restore these tests. - it.skip('removes listeners', () => { - const createHandler = () => { - let callCount = 0; - - function handlerFn() { - callCount += 1; - } - handlerFn.getCallCount = () => callCount; - - return handlerFn; - }; - - const handler1 = createHandler(); - const handler2 = createHandler(); - - // attach and test the first handler - history.onChange(handler1); - - expect(handler1.getCallCount()).to.equal(0); - history.push({}); - expect(handler1.getCallCount()).to.equal(1); - - // attach and test the second handler - history.onChange(handler2); - - expect(handler2.getCallCount()).to.equal(0); - history.push({}); - expect(handler1.getCallCount()).to.equal(2); - expect(handler2.getCallCount()).to.equal(1); - - // remove all handlers - history.resetOnChange(); - history.push({}); - expect(handler1.getCallCount()).to.equal(2); - expect(handler2.getCallCount()).to.equal(1); - }); - }); - - describe('parse', () => { - it('returns the decompressed object', () => { - history.push(state); - - const hist = history.historyInstance; - const rawState = hist.location.state; - - expect(rawState).to.be.a('string'); - expect(history.parse(rawState)).to.eql(state); - }); - - it('returns null with invalid JSON', () => { - expect(history.parse('hello')).to.be(null); - }); - }); - - describe('encode', () => { - it('returns the compressed string', () => { - history.push(state); - - const hist = history.historyInstance; - const rawState = hist.location.state; - - expect(rawState).to.be.a('string'); - expect(history.encode(state)).to.eql(rawState); - }); - }); -}); diff --git a/x-pack/plugins/canvas/public/lib/__tests__/modify_path.js b/x-pack/plugins/canvas/public/lib/__tests__/modify_path.js deleted file mode 100644 index 75454890f9717..0000000000000 --- a/x-pack/plugins/canvas/public/lib/__tests__/modify_path.js +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import { prepend, append } from '../modify_path'; - -describe('modify paths', () => { - describe('prepend', () => { - it('prepends a string path', () => { - expect(prepend('a.b.c', '0')).to.eql([0, 'a', 'b', 'c']); - expect(prepend('a.b.c', ['0', '1'])).to.eql([0, 1, 'a', 'b', 'c']); - }); - - it('prepends an array path', () => { - expect(prepend(['a', 1, 'last'], '0')).to.eql([0, 'a', 1, 'last']); - expect(prepend(['a', 1, 'last'], [0, 1])).to.eql([0, 1, 'a', 1, 'last']); - }); - }); - - describe('append', () => { - it('appends to a string path', () => { - expect(append('one.2.3', 'zero')).to.eql(['one', 2, 3, 'zero']); - expect(append('one.2.3', ['zero', 'one'])).to.eql(['one', 2, 3, 'zero', 'one']); - }); - - it('appends to an array path', () => { - expect(append(['testString'], 'huzzah')).to.eql(['testString', 'huzzah']); - expect(append(['testString'], ['huzzah', 'yosh'])).to.eql(['testString', 'huzzah', 'yosh']); - }); - }); -}); diff --git a/x-pack/plugins/canvas/public/lib/breadcrumbs.ts b/x-pack/plugins/canvas/public/lib/breadcrumbs.ts index 96412ef50c79d..b613bb7fcdaf1 100644 --- a/x-pack/plugins/canvas/public/lib/breadcrumbs.ts +++ b/x-pack/plugins/canvas/public/lib/breadcrumbs.ts @@ -24,6 +24,5 @@ export const getWorkpadBreadcrumb = ({ }; export const setBreadcrumb = (paths: ChromeBreadcrumb | ChromeBreadcrumb[]) => { - const setBreadCrumbs = platformService.getService().coreStart.chrome.setBreadcrumbs; - setBreadCrumbs(Array.isArray(paths) ? paths : [paths]); + platformService.getService().setBreadcrumbs(Array.isArray(paths) ? paths : [paths]); }; diff --git a/x-pack/plugins/canvas/public/lib/custom_element_service.ts b/x-pack/plugins/canvas/public/lib/custom_element_service.ts index 25c3b78a2746e..f240df93d0387 100644 --- a/x-pack/plugins/canvas/public/lib/custom_element_service.ts +++ b/x-pack/plugins/canvas/public/lib/custom_element_service.ts @@ -11,7 +11,7 @@ import { CustomElement } from '../../types'; import { platformService } from '../services'; const getApiPath = function () { - const basePath = platformService.getService().coreStart.http.basePath.get(); + const basePath = platformService.getService().getBasePath(); return `${basePath}${API_ROUTE_CUSTOM_ELEMENT}`; }; diff --git a/x-pack/plugins/canvas/public/lib/documentation_links.ts b/x-pack/plugins/canvas/public/lib/documentation_links.ts index 6430f7d87d4f7..cb19389291028 100644 --- a/x-pack/plugins/canvas/public/lib/documentation_links.ts +++ b/x-pack/plugins/canvas/public/lib/documentation_links.ts @@ -7,10 +7,14 @@ import { platformService } from '../services'; export const getDocumentationLinks = () => ({ - canvas: `${platformService.getService().coreStart.docLinks.ELASTIC_WEBSITE_URL}guide/en/kibana/${ - platformService.getService().coreStart.docLinks.DOC_LINK_VERSION - }/canvas.html`, - numeral: `${platformService.getService().coreStart.docLinks.ELASTIC_WEBSITE_URL}guide/en/kibana/${ - platformService.getService().coreStart.docLinks.DOC_LINK_VERSION - }/guide/numeral.html`, + canvas: `${platformService + .getService() + .getElasticWebsiteUrl()}guide/en/kibana/${platformService + .getService() + .getDocLinkVersion()}/canvas.html`, + numeral: `${platformService + .getService() + .getElasticWebsiteUrl()}guide/en/kibana/${platformService + .getService() + .getDocLinkVersion()}/guide/numeral.html`, }); diff --git a/x-pack/plugins/canvas/public/lib/es_service.ts b/x-pack/plugins/canvas/public/lib/es_service.ts index 5c1131d5fbe35..fee66c71636c8 100644 --- a/x-pack/plugins/canvas/public/lib/es_service.ts +++ b/x-pack/plugins/canvas/public/lib/es_service.ts @@ -15,16 +15,16 @@ import { platformService } from '../services'; const { esService: strings } = ErrorStrings; const getApiPath = function () { - const basePath = platformService.getService().coreStart.http.basePath.get(); + const basePath = platformService.getService().getBasePath(); return basePath + API_ROUTE; }; const getSavedObjectsClient = function () { - return platformService.getService().coreStart.savedObjects.client; + return platformService.getService().getSavedObjectsClient(); }; const getAdvancedSettings = function () { - return platformService.getService().coreStart.uiSettings; + return platformService.getService().getUISettings(); }; export const getFields = (index = '_all') => { diff --git a/x-pack/plugins/canvas/public/lib/__tests__/get_pretty_shortcut.test.ts b/x-pack/plugins/canvas/public/lib/get_pretty_shortcut.test.ts similarity index 98% rename from x-pack/plugins/canvas/public/lib/__tests__/get_pretty_shortcut.test.ts rename to x-pack/plugins/canvas/public/lib/get_pretty_shortcut.test.ts index 783b085f3da7e..95cffefde7b1c 100644 --- a/x-pack/plugins/canvas/public/lib/__tests__/get_pretty_shortcut.test.ts +++ b/x-pack/plugins/canvas/public/lib/get_pretty_shortcut.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getPrettyShortcut } from '../get_pretty_shortcut'; +import { getPrettyShortcut } from './get_pretty_shortcut'; describe('getPrettyShortcut', () => { test('uppercases shortcuts', () => { diff --git a/x-pack/plugins/canvas/public/lib/modify_path.test.ts b/x-pack/plugins/canvas/public/lib/modify_path.test.ts new file mode 100644 index 0000000000000..245b91ca4ccd4 --- /dev/null +++ b/x-pack/plugins/canvas/public/lib/modify_path.test.ts @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { prepend, append } from './modify_path'; + +describe('modify paths', () => { + describe('prepend', () => { + it('prepends a string path', () => { + expect(prepend('a.b.c', '0')).toEqual(['0', 'a', 'b', 'c']); + expect(prepend('a.b.c', ['0', '1'])).toEqual(['0', '1', 'a', 'b', 'c']); + }); + + it('prepends an array path', () => { + expect(prepend(['a', 1, 'last'], '0')).toEqual(['0', 'a', '1', 'last']); + expect(prepend(['a', 1, 'last'], [0, 1])).toEqual(['0', '1', 'a', '1', 'last']); + }); + }); + + describe('append', () => { + it('appends to a string path', () => { + expect(append('one.2.3', 'zero')).toEqual(['one', '2', '3', 'zero']); + expect(append('one.2.3', ['zero', 'one'])).toEqual(['one', '2', '3', 'zero', 'one']); + }); + + it('appends to an array path', () => { + expect(append(['testString'], 'huzzah')).toEqual(['testString', 'huzzah']); + expect(append(['testString'], ['huzzah', 'yosh'])).toEqual(['testString', 'huzzah', 'yosh']); + }); + }); +}); diff --git a/x-pack/plugins/canvas/public/lib/modify_path.js b/x-pack/plugins/canvas/public/lib/modify_path.ts similarity index 61% rename from x-pack/plugins/canvas/public/lib/modify_path.js rename to x-pack/plugins/canvas/public/lib/modify_path.ts index 714a616679bc9..a5b8f0316d23e 100644 --- a/x-pack/plugins/canvas/public/lib/modify_path.js +++ b/x-pack/plugins/canvas/public/lib/modify_path.ts @@ -6,14 +6,16 @@ import { toPath } from 'lodash'; -export function prepend(path, value) { +export type Path = Array; + +export function prepend(path: string | Path, value: string | Path): Path { return toPath(value).concat(toPath(path)); } -export function append(path, value) { +export function append(path: string | Path, value: string | Path): Path { return toPath(path).concat(toPath(value)); } -export function convert(path) { +export function convert(path: string | Path): Path { return toPath(path); } diff --git a/x-pack/plugins/canvas/public/lib/__tests__/readable_color.test.ts b/x-pack/plugins/canvas/public/lib/readable_color.test.ts similarity index 94% rename from x-pack/plugins/canvas/public/lib/__tests__/readable_color.test.ts rename to x-pack/plugins/canvas/public/lib/readable_color.test.ts index bd79655ca727b..ce7cf03c2889c 100644 --- a/x-pack/plugins/canvas/public/lib/__tests__/readable_color.test.ts +++ b/x-pack/plugins/canvas/public/lib/readable_color.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { readableColor } from '../readable_color'; +import { readableColor } from './readable_color'; describe('readableColor', () => { test('light', () => { diff --git a/x-pack/plugins/canvas/public/lib/__tests__/resolved_arg.js b/x-pack/plugins/canvas/public/lib/resolved_arg.test.ts similarity index 57% rename from x-pack/plugins/canvas/public/lib/__tests__/resolved_arg.js rename to x-pack/plugins/canvas/public/lib/resolved_arg.test.ts index 9e582ddd1858b..fac2023fb2ce5 100644 --- a/x-pack/plugins/canvas/public/lib/__tests__/resolved_arg.js +++ b/x-pack/plugins/canvas/public/lib/resolved_arg.test.ts @@ -4,39 +4,38 @@ * you may not use this file except in compliance with the Elastic License. */ -import expect from '@kbn/expect'; -import { getState, getValue, getError } from '../resolved_arg'; +import { getState, getValue, getError } from './resolved_arg'; describe('resolved arg helper', () => { describe('getState', () => { it('returns pending by default', () => { - expect(getState()).to.be(null); + expect(getState()).toBe(null); }); it('returns the state', () => { - expect(getState({ state: 'pending' })).to.equal('pending'); - expect(getState({ state: 'ready' })).to.equal('ready'); - expect(getState({ state: 'error' })).to.equal('error'); + expect(getState({ state: 'pending' })).toEqual('pending'); + expect(getState({ state: 'ready' })).toEqual('ready'); + expect(getState({ state: 'error' })).toEqual('error'); }); }); describe('getValue', () => { it('returns null by default', () => { - expect(getValue()).to.be(null); + expect(getValue()).toBe(null); }); it('returns the value', () => { - expect(getValue({ value: 'hello test' })).to.equal('hello test'); + expect(getValue({ value: 'hello test' })).toEqual('hello test'); }); }); describe('getError', () => { it('returns null by default', () => { - expect(getError()).to.be(null); + expect(getError()).toBe(null); }); it('returns null when state is not error', () => { - expect(getError({ state: 'pending', error: 'nope' })).to.be(null); + expect(getError({ state: 'pending', error: 'nope' })).toBe(null); }); it('returns the error', () => { @@ -46,8 +45,7 @@ describe('resolved arg helper', () => { error: new Error('i failed'), }; - expect(getError(arg)).to.be.an(Error); - expect(getError(arg).toString()).to.match(/i failed/); + expect(getError(arg)).toMatchInlineSnapshot(`[Error: i failed]`); }); }); }); diff --git a/x-pack/plugins/canvas/public/lib/resolved_arg.js b/x-pack/plugins/canvas/public/lib/resolved_arg.ts similarity index 75% rename from x-pack/plugins/canvas/public/lib/resolved_arg.js rename to x-pack/plugins/canvas/public/lib/resolved_arg.ts index 8a9da8e466f7e..77f8a6cf8e5e0 100644 --- a/x-pack/plugins/canvas/public/lib/resolved_arg.js +++ b/x-pack/plugins/canvas/public/lib/resolved_arg.ts @@ -6,15 +6,15 @@ import { get } from 'lodash'; -export function getState(resolvedArg) { +export function getState(resolvedArg?: any): any { return get(resolvedArg, 'state', null); } -export function getValue(resolvedArg) { +export function getValue(resolvedArg?: any): any { return get(resolvedArg, 'value', null); } -export function getError(resolvedArg) { +export function getError(resolvedArg?: any): any { if (getState(resolvedArg) !== 'error') { return null; } diff --git a/x-pack/plugins/canvas/public/lib/template_service.ts b/x-pack/plugins/canvas/public/lib/template_service.ts index 98d582c854e36..185b2ec37ba95 100644 --- a/x-pack/plugins/canvas/public/lib/template_service.ts +++ b/x-pack/plugins/canvas/public/lib/template_service.ts @@ -10,7 +10,7 @@ import { platformService } from '../services'; import { CanvasTemplate } from '../../types'; const getApiPath = function () { - const basePath = platformService.getService().coreStart.http.basePath.get(); + const basePath = platformService.getService().getBasePath(); return `${basePath}${API_ROUTE_TEMPLATES}`; }; diff --git a/x-pack/plugins/canvas/public/lib/__tests__/time_interval.test.ts b/x-pack/plugins/canvas/public/lib/time_interval.test.ts similarity index 98% rename from x-pack/plugins/canvas/public/lib/__tests__/time_interval.test.ts rename to x-pack/plugins/canvas/public/lib/time_interval.test.ts index 2dab00631cce1..8a057793ead79 100644 --- a/x-pack/plugins/canvas/public/lib/__tests__/time_interval.test.ts +++ b/x-pack/plugins/canvas/public/lib/time_interval.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getTimeInterval, createTimeInterval, isValidTimeInterval } from '../time_interval'; +import { getTimeInterval, createTimeInterval, isValidTimeInterval } from './time_interval'; describe('time_interval', () => { test('getTimeInterval', () => { diff --git a/x-pack/plugins/canvas/public/lib/workpad_service.js b/x-pack/plugins/canvas/public/lib/workpad_service.js index 2047e20424acc..27efe25405fd7 100644 --- a/x-pack/plugins/canvas/public/lib/workpad_service.js +++ b/x-pack/plugins/canvas/public/lib/workpad_service.js @@ -12,6 +12,7 @@ import { } from '../../common/lib/constants'; import { fetch } from '../../common/lib/fetch'; import { platformService } from '../services'; + /* Remove any top level keys from the workpad which will be rejected by validation */ @@ -44,17 +45,17 @@ const sanitizeWorkpad = function (workpad) { }; const getApiPath = function () { - const basePath = platformService.getService().coreStart.http.basePath.get(); + const basePath = platformService.getService().getBasePath(); return `${basePath}${API_ROUTE_WORKPAD}`; }; const getApiPathStructures = function () { - const basePath = platformService.getService().coreStart.http.basePath.get(); + const basePath = platformService.getService().getBasePath(); return `${basePath}${API_ROUTE_WORKPAD_STRUCTURES}`; }; const getApiPathAssets = function () { - const basePath = platformService.getService().coreStart.http.basePath.get(); + const basePath = platformService.getService().getBasePath(); return `${basePath}${API_ROUTE_WORKPAD_ASSETS}`; }; diff --git a/x-pack/plugins/canvas/public/services/context.tsx b/x-pack/plugins/canvas/public/services/context.tsx new file mode 100644 index 0000000000000..9bd86ef98f1e3 --- /dev/null +++ b/x-pack/plugins/canvas/public/services/context.tsx @@ -0,0 +1,58 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { + useContext, + createElement, + createContext, + ComponentType, + FC, + ReactElement, +} from 'react'; +import { CanvasServices, CanvasServiceProviders } from '.'; + +export interface WithServicesProps { + services: CanvasServices; +} + +const defaultContextValue = { + embeddables: {}, + expressions: {}, + notify: {}, + platform: {}, + navLink: {}, +}; + +const context = createContext(defaultContextValue as CanvasServices); + +export const useServices = () => useContext(context); +export const usePlatformService = () => useServices().platform; +export const useEmbeddablesService = () => useServices().embeddables; +export const useExpressionsService = () => useServices().expressions; +export const useNotifyService = () => useServices().notify; +export const useNavLinkService = () => useServices().navLink; + +export const withServices = (type: ComponentType) => { + const EnhancedType: FC = (props) => { + const services = useServices(); + return createElement(type, { ...props, services }); + }; + return EnhancedType; +}; + +export const ServicesProvider: FC<{ + providers: CanvasServiceProviders; + children: ReactElement; +}> = ({ providers, children }) => { + const value = { + embeddables: providers.embeddables.getService(), + expressions: providers.expressions.getService(), + notify: providers.notify.getService(), + platform: providers.platform.getService(), + navLink: providers.navLink.getService(), + }; + return {children}; +}; diff --git a/x-pack/plugins/canvas/public/services/embeddables.ts b/x-pack/plugins/canvas/public/services/embeddables.ts new file mode 100644 index 0000000000000..13e308effcdba --- /dev/null +++ b/x-pack/plugins/canvas/public/services/embeddables.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EmbeddableFactory } from '../../../../../src/plugins/embeddable/public'; +import { CanvasServiceFactory } from '.'; + +export interface EmbeddablesService { + getEmbeddableFactories: () => IterableIterator; +} + +export const embeddablesServiceFactory: CanvasServiceFactory = async ( + _coreSetup, + _coreStart, + _setupPlugins, + startPlugins +) => ({ + getEmbeddableFactories: startPlugins.embeddable.getEmbeddableFactories, +}); diff --git a/x-pack/plugins/canvas/public/services/expressions.ts b/x-pack/plugins/canvas/public/services/expressions.ts index 16f939a9c97fc..1376aab0ca8b9 100644 --- a/x-pack/plugins/canvas/public/services/expressions.ts +++ b/x-pack/plugins/canvas/public/services/expressions.ts @@ -14,6 +14,5 @@ export const expressionsServiceFactory: CanvasServiceFactory startPlugins ) => { await setupPlugins.expressions.__LEGACY.loadLegacyServerFunctionWrappers(); - return setupPlugins.expressions.fork(); }; diff --git a/x-pack/plugins/canvas/public/services/index.ts b/x-pack/plugins/canvas/public/services/index.ts index a929b4639d3e4..700d874d4507d 100644 --- a/x-pack/plugins/canvas/public/services/index.ts +++ b/x-pack/plugins/canvas/public/services/index.ts @@ -10,8 +10,16 @@ import { CanvasSetupDeps, CanvasStartDeps } from '../plugin'; import { notifyServiceFactory } from './notify'; import { platformServiceFactory } from './platform'; import { navLinkServiceFactory } from './nav_link'; +import { embeddablesServiceFactory } from './embeddables'; import { expressionsServiceFactory } from './expressions'; +export { NotifyService } from './notify'; +export { PlatformService } from './platform'; +export { NavLinkService } from './nav_link'; +export { EmbeddablesService } from './embeddables'; +export { ExpressionsService } from '../../../../../src/plugins/expressions/common'; +export * from './context'; + export type CanvasServiceFactory = ( coreSetup: CoreSetup, coreStart: CoreStart, @@ -28,6 +36,10 @@ class CanvasServiceProvider { this.factory = factory; } + setService(service: Service) { + this.service = service; + } + async start( coreSetup: CoreSetup, coreStart: CoreStart, @@ -60,13 +72,17 @@ class CanvasServiceProvider { export type ServiceFromProvider

= P extends CanvasServiceProvider ? T : never; export const services = { + embeddables: new CanvasServiceProvider(embeddablesServiceFactory), expressions: new CanvasServiceProvider(expressionsServiceFactory), notify: new CanvasServiceProvider(notifyServiceFactory), platform: new CanvasServiceProvider(platformServiceFactory), navLink: new CanvasServiceProvider(navLinkServiceFactory), }; +export type CanvasServiceProviders = typeof services; + export interface CanvasServices { + embeddables: ServiceFromProvider; expressions: ServiceFromProvider; notify: ServiceFromProvider; platform: ServiceFromProvider; @@ -88,10 +104,11 @@ export const startServices = async ( }; export const stopServices = () => { - Object.entries(services).forEach(([key, provider]) => provider.stop()); + Object.values(services).forEach((provider) => provider.stop()); }; export const { + embeddables: embeddableService, notify: notifyService, platform: platformService, navLink: navLinkService, diff --git a/x-pack/plugins/canvas/public/services/nav_link.ts b/x-pack/plugins/canvas/public/services/nav_link.ts index 68d685242351b..532b5264ee9ed 100644 --- a/x-pack/plugins/canvas/public/services/nav_link.ts +++ b/x-pack/plugins/canvas/public/services/nav_link.ts @@ -8,15 +8,15 @@ import { CanvasServiceFactory } from '.'; import { SESSIONSTORAGE_LASTPATH } from '../../common/lib/constants'; import { getSessionStorage } from '../lib/storage'; -interface NavLinkService { +export interface NavLinkService { updatePath: (path: string) => void; } export const navLinkServiceFactory: CanvasServiceFactory = ( coreSetup, - coreStart, - setupPlugins, - startPlugins, + _coreStart, + _setupPlugins, + _startPlugins, appUpdater ) => { return { diff --git a/x-pack/plugins/canvas/public/services/notify.ts b/x-pack/plugins/canvas/public/services/notify.ts index 5454a0f87c3f0..819525c8fa922 100644 --- a/x-pack/plugins/canvas/public/services/notify.ts +++ b/x-pack/plugins/canvas/public/services/notify.ts @@ -26,7 +26,7 @@ const getToast = (err: Error | string, opts: ToastInputFields = {}) => { }; }; -interface NotifyService { +export interface NotifyService { error: (err: string | Error, opts?: ToastInputFields) => void; warning: (err: string | Error, opts?: ToastInputFields) => void; info: (err: string | Error, opts?: ToastInputFields) => void; diff --git a/x-pack/plugins/canvas/public/services/platform.ts b/x-pack/plugins/canvas/public/services/platform.ts index 440e9523044c1..92c378e9aa597 100644 --- a/x-pack/plugins/canvas/public/services/platform.ts +++ b/x-pack/plugins/canvas/public/services/platform.ts @@ -4,21 +4,52 @@ * you may not use this file except in compliance with the Elastic License. */ +import { + SavedObjectsStart, + SavedObjectsClientContract, + IUiSettingsClient, + ChromeBreadcrumb, + IBasePath, +} from '../../../../../src/core/public'; import { CanvasServiceFactory } from '.'; -import { CoreStart, CoreSetup, CanvasSetupDeps, CanvasStartDeps } from '../plugin'; -interface PlatformService { - coreSetup: CoreSetup; - coreStart: CoreStart; - setupPlugins: CanvasSetupDeps; - startPlugins: CanvasStartDeps; +export interface PlatformService { + getBasePath: () => string; + getBasePathInterface: () => IBasePath; + getDocLinkVersion: () => string; + getElasticWebsiteUrl: () => string; + getHasWriteAccess: () => boolean; + getUISetting: (key: string, defaultValue?: any) => any; + setBreadcrumbs: (newBreadcrumbs: ChromeBreadcrumb[]) => void; + setRecentlyAccessed: (link: string, label: string, id: string) => void; + + // TODO: these should go away. We want thin accessors, not entire objects. + // Entire objects are hard to mock, and hide our dependency on the external service. + getSavedObjects: () => SavedObjectsStart; + getSavedObjectsClient: () => SavedObjectsClientContract; + getUISettings: () => IUiSettingsClient; } export const platformServiceFactory: CanvasServiceFactory = ( - coreSetup, - coreStart, - setupPlugins, - startPlugins + _coreSetup, + coreStart ) => { - return { coreSetup, coreStart, setupPlugins, startPlugins }; + return { + getBasePath: coreStart.http.basePath.get, + getBasePathInterface: () => coreStart.http.basePath, + getElasticWebsiteUrl: () => coreStart.docLinks.ELASTIC_WEBSITE_URL, + getDocLinkVersion: () => coreStart.docLinks.DOC_LINK_VERSION, + // TODO: is there a better type for this? The capabilities type allows for a Record, + // though we don't do this. So this cast may be the best option. + getHasWriteAccess: () => coreStart.application.capabilities.canvas.save as boolean, + getUISetting: coreStart.uiSettings.get.bind(coreStart.uiSettings), + setBreadcrumbs: coreStart.chrome.setBreadcrumbs, + setRecentlyAccessed: coreStart.chrome.recentlyAccessed.add, + + // TODO: these should go away. We want thin accessors, not entire objects. + // Entire objects are hard to mock, and hide our dependency on the external service. + getSavedObjects: () => coreStart.savedObjects, + getSavedObjectsClient: () => coreStart.savedObjects.client, + getUISettings: () => coreStart.uiSettings, + }; }; diff --git a/x-pack/plugins/canvas/public/components/border_resize_handle/index.js b/x-pack/plugins/canvas/public/services/stubs/embeddables.ts similarity index 56% rename from x-pack/plugins/canvas/public/components/border_resize_handle/index.js rename to x-pack/plugins/canvas/public/services/stubs/embeddables.ts index c3fea05d60f7e..48100da462dd5 100644 --- a/x-pack/plugins/canvas/public/components/border_resize_handle/index.js +++ b/x-pack/plugins/canvas/public/services/stubs/embeddables.ts @@ -3,8 +3,10 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import { EmbeddablesService } from '../embeddables'; -import { pure } from 'recompose'; -import { BorderResizeHandle as Component } from './border_resize_handle'; +const noop = (..._args: any[]): any => {}; -export const BorderResizeHandle = pure(Component); +export const embeddablesService: EmbeddablesService = { + getEmbeddableFactories: noop, +}; diff --git a/x-pack/plugins/canvas/public/services/stubs/expressions.ts b/x-pack/plugins/canvas/public/services/stubs/expressions.ts new file mode 100644 index 0000000000000..26a90670106d0 --- /dev/null +++ b/x-pack/plugins/canvas/public/services/stubs/expressions.ts @@ -0,0 +1,27 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ExpressionsService } from '../'; +import { + plugin, + ExpressionRenderDefinition, +} from '../../../../../../src/plugins/expressions/public'; +import { functions as functionDefinitions } from '../../../canvas_plugin_src/functions/common'; +// @ts-expect-error untyped local +import { renderFunctions } from '../../../canvas_plugin_src/renderers/core'; + +const placeholder = {} as any; +const expressionsPlugin = plugin(placeholder); +const setup = expressionsPlugin.setup(placeholder, { + inspector: {}, +} as any); + +export const expressionsService: ExpressionsService = setup.fork(); + +functionDefinitions.forEach((fn) => expressionsService.registerFunction(fn)); +renderFunctions.forEach((fn: ExpressionRenderDefinition) => + expressionsService.registerRenderer(fn) +); diff --git a/x-pack/plugins/canvas/public/services/stubs/index.ts b/x-pack/plugins/canvas/public/services/stubs/index.ts new file mode 100644 index 0000000000000..b4e440f204cc7 --- /dev/null +++ b/x-pack/plugins/canvas/public/services/stubs/index.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { CanvasServices, services } from '../'; +import { embeddablesService } from './embeddables'; +import { expressionsService } from './expressions'; +import { navLinkService } from './nav_link'; +import { notifyService } from './notify'; +import { platformService } from './platform'; + +export const stubs: CanvasServices = { + embeddables: embeddablesService, + expressions: expressionsService, + navLink: navLinkService, + notify: notifyService, + platform: platformService, +}; + +export const startServices = async (providedServices: Partial = {}) => { + Object.entries(services).forEach(([key, provider]) => { + // @ts-expect-error Object.entries isn't strongly typed + const stub = providedServices[key] || stubs[key]; + provider.setService(stub); + }); +}; diff --git a/x-pack/plugins/canvas/public/components/font_picker/index.js b/x-pack/plugins/canvas/public/services/stubs/nav_link.ts similarity index 60% rename from x-pack/plugins/canvas/public/components/font_picker/index.js rename to x-pack/plugins/canvas/public/services/stubs/nav_link.ts index 5ccb7846b7a77..3b40eeb3e84f2 100644 --- a/x-pack/plugins/canvas/public/components/font_picker/index.js +++ b/x-pack/plugins/canvas/public/services/stubs/nav_link.ts @@ -4,8 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; +import { NavLinkService } from '../nav_link'; -import { FontPicker as Component } from './font_picker'; +const noop = (..._args: any[]): any => {}; -export const FontPicker = pure(Component); +export const navLinkService: NavLinkService = { + updatePath: noop, +}; diff --git a/x-pack/plugins/canvas/public/components/alignment_guide/index.js b/x-pack/plugins/canvas/public/services/stubs/notify.ts similarity index 55% rename from x-pack/plugins/canvas/public/components/alignment_guide/index.js rename to x-pack/plugins/canvas/public/services/stubs/notify.ts index 6793e0151759b..38eac2a5813eb 100644 --- a/x-pack/plugins/canvas/public/components/alignment_guide/index.js +++ b/x-pack/plugins/canvas/public/services/stubs/notify.ts @@ -4,7 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; -import { AlignmentGuide as Component } from './alignment_guide'; +import { NotifyService } from '../notify'; -export const AlignmentGuide = pure(Component); +const noop = (..._args: any[]): any => {}; + +export const notifyService: NotifyService = { + error: noop, + info: noop, + success: noop, + warning: noop, +}; diff --git a/x-pack/plugins/canvas/public/services/stubs/platform.ts b/x-pack/plugins/canvas/public/services/stubs/platform.ts new file mode 100644 index 0000000000000..9ada579573502 --- /dev/null +++ b/x-pack/plugins/canvas/public/services/stubs/platform.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { PlatformService } from '../platform'; + +const noop = (..._args: any[]): any => {}; + +export const platformService: PlatformService = { + getBasePath: () => '/base/path', + getBasePathInterface: noop, + getDocLinkVersion: () => 'dockLinkVersion', + getElasticWebsiteUrl: () => 'https://elastic.co', + getHasWriteAccess: () => true, + getUISetting: noop, + setBreadcrumbs: noop, + setRecentlyAccessed: noop, + getSavedObjects: noop, + getSavedObjectsClient: noop, + getUISettings: noop, +}; diff --git a/x-pack/plugins/canvas/public/state/actions/__tests__/elements.get_sibling_context.js b/x-pack/plugins/canvas/public/state/actions/__tests__/elements.get_sibling_context.js deleted file mode 100644 index 198ccb2ffc381..0000000000000 --- a/x-pack/plugins/canvas/public/state/actions/__tests__/elements.get_sibling_context.js +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import { getSiblingContext } from '../elements'; - -const state = { - transient: { - resolvedArgs: { - 'element-foo': { - expressionContext: { - '0': { - state: 'ready', - value: { - type: 'datatable', - columns: [ - { name: 'project', type: 'string' }, - { name: 'cost', type: 'string' }, - { name: 'age', type: 'string' }, - ], - rows: [ - { project: 'pandas', cost: '500', age: '18' }, - { project: 'tigers', cost: '200', age: '12' }, - ], - }, - error: null, - }, - '1': { - state: 'ready', - value: { - type: 'datatable', - columns: [ - { name: 'project', type: 'string' }, - { name: 'cost', type: 'string' }, - { name: 'age', type: 'string' }, - ], - rows: [ - { project: 'tigers', cost: '200', age: '12' }, - { project: 'pandas', cost: '500', age: '18' }, - ], - }, - error: null, - }, - '2': { - state: 'ready', - value: { - type: 'pointseries', - columns: { - x: { type: 'string', role: 'dimension', expression: 'cost' }, - y: { type: 'string', role: 'dimension', expression: 'project' }, - color: { type: 'string', role: 'dimension', expression: 'project' }, - }, - rows: [ - { x: '200', y: 'tigers', color: 'tigers' }, - { x: '500', y: 'pandas', color: 'pandas' }, - ], - }, - error: null, - }, - }, - }, - }, - }, -}; - -describe('actions/elements getSiblingContext', () => { - it('should find context when a previous context value is found', () => { - // pointseries map - expect(getSiblingContext(state, 'element-foo', 2)).to.eql({ - index: 2, - context: { - type: 'pointseries', - columns: { - x: { type: 'string', role: 'dimension', expression: 'cost' }, - y: { type: 'string', role: 'dimension', expression: 'project' }, - color: { type: 'string', role: 'dimension', expression: 'project' }, - }, - rows: [ - { x: '200', y: 'tigers', color: 'tigers' }, - { x: '500', y: 'pandas', color: 'pandas' }, - ], - }, - }); - }); - - it('should find context when a previous context value is not found', () => { - // pointseries map - expect(getSiblingContext(state, 'element-foo', 1000)).to.eql({ - index: 2, - context: { - type: 'pointseries', - columns: { - x: { type: 'string', role: 'dimension', expression: 'cost' }, - y: { type: 'string', role: 'dimension', expression: 'project' }, - color: { type: 'string', role: 'dimension', expression: 'project' }, - }, - rows: [ - { x: '200', y: 'tigers', color: 'tigers' }, - { x: '500', y: 'pandas', color: 'pandas' }, - ], - }, - }); - }); -}); diff --git a/x-pack/plugins/canvas/public/state/actions/elements.test.js b/x-pack/plugins/canvas/public/state/actions/elements.test.js new file mode 100644 index 0000000000000..a790e81e65e25 --- /dev/null +++ b/x-pack/plugins/canvas/public/state/actions/elements.test.js @@ -0,0 +1,106 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { getSiblingContext } from './elements'; + +describe('getSiblingContext', () => { + const state = { + transient: { + resolvedArgs: { + 'element-foo': { + expressionContext: { + '0': { + state: 'ready', + value: { + type: 'datatable', + columns: [ + { name: 'project', type: 'string' }, + { name: 'cost', type: 'string' }, + { name: 'age', type: 'string' }, + ], + rows: [ + { project: 'pandas', cost: '500', age: '18' }, + { project: 'tigers', cost: '200', age: '12' }, + ], + }, + error: null, + }, + '1': { + state: 'ready', + value: { + type: 'datatable', + columns: [ + { name: 'project', type: 'string' }, + { name: 'cost', type: 'string' }, + { name: 'age', type: 'string' }, + ], + rows: [ + { project: 'tigers', cost: '200', age: '12' }, + { project: 'pandas', cost: '500', age: '18' }, + ], + }, + error: null, + }, + '2': { + state: 'ready', + value: { + type: 'pointseries', + columns: { + x: { type: 'string', role: 'dimension', expression: 'cost' }, + y: { type: 'string', role: 'dimension', expression: 'project' }, + color: { type: 'string', role: 'dimension', expression: 'project' }, + }, + rows: [ + { x: '200', y: 'tigers', color: 'tigers' }, + { x: '500', y: 'pandas', color: 'pandas' }, + ], + }, + error: null, + }, + }, + }, + }, + }, + }; + + it('should find context when a previous context value is found', () => { + // pointseries map + expect(getSiblingContext(state, 'element-foo', 2)).toEqual({ + index: 2, + context: { + type: 'pointseries', + columns: { + x: { type: 'string', role: 'dimension', expression: 'cost' }, + y: { type: 'string', role: 'dimension', expression: 'project' }, + color: { type: 'string', role: 'dimension', expression: 'project' }, + }, + rows: [ + { x: '200', y: 'tigers', color: 'tigers' }, + { x: '500', y: 'pandas', color: 'pandas' }, + ], + }, + }); + }); + + it('should find context when a previous context value is not found', () => { + // pointseries map + expect(getSiblingContext(state, 'element-foo', 1000)).toEqual({ + index: 2, + context: { + type: 'pointseries', + columns: { + x: { type: 'string', role: 'dimension', expression: 'cost' }, + y: { type: 'string', role: 'dimension', expression: 'project' }, + color: { type: 'string', role: 'dimension', expression: 'project' }, + }, + rows: [ + { x: '200', y: 'tigers', color: 'tigers' }, + { x: '500', y: 'pandas', color: 'pandas' }, + ], + }, + }); + }); +}); diff --git a/x-pack/plugins/canvas/public/state/initial_state.js b/x-pack/plugins/canvas/public/state/initial_state.js index 13021893e72e8..f9b02d33d6112 100644 --- a/x-pack/plugins/canvas/public/state/initial_state.js +++ b/x-pack/plugins/canvas/public/state/initial_state.js @@ -9,11 +9,13 @@ import { platformService } from '../services'; import { getDefaultWorkpad } from './defaults'; export const getInitialState = (path) => { + const { getHasWriteAccess } = platformService.getService(); + const state = { app: {}, // Kibana stuff in here assets: {}, // assets end up here transient: { - canUserWrite: platformService.getService().coreStart.application.capabilities.canvas.save, + canUserWrite: getHasWriteAccess(), zoomScale: 1, elementStats: { total: 0, diff --git a/x-pack/plugins/canvas/public/state/middleware/in_flight.ts b/x-pack/plugins/canvas/public/state/middleware/in_flight.ts index 028b9f214133f..d564a44b0b5f7 100644 --- a/x-pack/plugins/canvas/public/state/middleware/in_flight.ts +++ b/x-pack/plugins/canvas/public/state/middleware/in_flight.ts @@ -9,7 +9,6 @@ import { loadingIndicator as defaultLoadingIndicator, LoadingIndicatorInterface, } from '../../lib/loading_indicator'; -// @ts-expect-error import { convert } from '../../lib/modify_path'; interface InFlightMiddlewareOptions { diff --git a/x-pack/plugins/canvas/public/state/reducers/__tests__/fixtures/action_creator.js b/x-pack/plugins/canvas/public/state/reducers/__fixtures__/action_creator.js similarity index 100% rename from x-pack/plugins/canvas/public/state/reducers/__tests__/fixtures/action_creator.js rename to x-pack/plugins/canvas/public/state/reducers/__fixtures__/action_creator.js diff --git a/x-pack/plugins/canvas/public/state/reducers/__tests__/elements.js b/x-pack/plugins/canvas/public/state/reducers/elements.test.js similarity index 78% rename from x-pack/plugins/canvas/public/state/reducers/__tests__/elements.js rename to x-pack/plugins/canvas/public/state/reducers/elements.test.js index e1f7509325a7a..23f684879ce06 100644 --- a/x-pack/plugins/canvas/public/state/reducers/__tests__/elements.js +++ b/x-pack/plugins/canvas/public/state/reducers/elements.test.js @@ -4,10 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import expect from '@kbn/expect'; -import { get } from 'lodash'; -import { elementsReducer } from '../elements'; -import { actionCreator } from './fixtures/action_creator'; +import { elementsReducer } from './elements'; +import { actionCreator } from './__fixtures__/action_creator'; describe('elements reducer', () => { let state; @@ -46,8 +44,8 @@ describe('elements reducer', () => { }); const newState = elementsReducer(state, action); - const newElement = get(newState, ['pages', 0, 'elements', 1]); + const newElement = newState?.pages?.[0]?.elements?.[1]; - expect(newElement).to.eql(expected); + expect(newElement).toEqual(expected); }); }); diff --git a/x-pack/plugins/canvas/public/state/reducers/__tests__/resolved_args.js b/x-pack/plugins/canvas/public/state/reducers/resolved_args.test.js similarity index 62% rename from x-pack/plugins/canvas/public/state/reducers/__tests__/resolved_args.js rename to x-pack/plugins/canvas/public/state/reducers/resolved_args.test.js index ee1d0fc1ca9ba..74f1544403e67 100644 --- a/x-pack/plugins/canvas/public/state/reducers/__tests__/resolved_args.js +++ b/x-pack/plugins/canvas/public/state/reducers/resolved_args.test.js @@ -4,11 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import expect from '@kbn/expect'; -import * as actions from '../../actions/resolved_args'; -import { flushContextAfterIndex } from '../../actions/elements'; -import { resolvedArgsReducer } from '../resolved_args'; -import { actionCreator } from './fixtures/action_creator'; +import * as actions from '../actions/resolved_args'; +import { flushContextAfterIndex } from '../actions/elements'; +import { resolvedArgsReducer } from './resolved_args'; +import { actionCreator } from './__fixtures__/action_creator'; describe('resolved args reducer', () => { let state; @@ -41,13 +40,15 @@ describe('resolved args reducer', () => { }); const newState = resolvedArgsReducer(state, action); - expect(newState.resolvedArgs['element-1']).to.eql([ - { - state: 'pending', - value: null, - error: null, - }, - ]); + expect(newState.resolvedArgs['element-1']).toMatchInlineSnapshot(` + Object { + "0": Object { + "error": null, + "state": "pending", + "value": null, + }, + } + `); }); it('sets state to loading, with array path', () => { @@ -56,13 +57,15 @@ describe('resolved args reducer', () => { }); const newState = resolvedArgsReducer(state, action); - expect(newState.resolvedArgs['element-1']).to.eql([ - { - state: 'pending', - value: null, - error: null, - }, - ]); + expect(newState.resolvedArgs['element-1']).toMatchInlineSnapshot(` + Object { + "0": Object { + "error": null, + "state": "pending", + "value": null, + }, + } + `); }); }); @@ -75,13 +78,15 @@ describe('resolved args reducer', () => { }); const newState = resolvedArgsReducer(state, action); - expect(newState.resolvedArgs['element-1']).to.eql([ - { - state: 'ready', - value, - error: null, - }, - ]); + expect(newState.resolvedArgs['element-1']).toMatchInlineSnapshot(` + Object { + "0": Object { + "error": null, + "state": "ready", + "value": "hello world", + }, + } + `); }); it('handles error values', () => { @@ -92,13 +97,15 @@ describe('resolved args reducer', () => { }); const newState = resolvedArgsReducer(state, action); - expect(newState.resolvedArgs['element-1']).to.eql([ - { - state: 'error', - value: null, - error: err, - }, - ]); + expect(newState.resolvedArgs['element-1']).toMatchInlineSnapshot(` + Object { + "0": Object { + "error": [Error: farewell world], + "state": "error", + "value": null, + }, + } + `); }); it('preserves old value on error', () => { @@ -109,11 +116,13 @@ describe('resolved args reducer', () => { }); const newState = resolvedArgsReducer(state, action); - expect(newState.resolvedArgs['element-0'][0]).to.eql({ - state: 'error', - value: 'testing', - error: err, - }); + expect(newState.resolvedArgs['element-0'][0]).toMatchInlineSnapshot(` + Object { + "error": [Error: farewell world], + "state": "error", + "value": "testing", + } + `); }); }); @@ -124,14 +133,15 @@ describe('resolved args reducer', () => { }); const newState = resolvedArgsReducer(state, action); - expect(newState.resolvedArgs['element-0']).to.have.length(1); - expect(newState.resolvedArgs['element-0']).to.eql([ - { - state: 'ready', - value: 'testing', - error: null, - }, - ]); + expect(newState.resolvedArgs['element-0']).toMatchInlineSnapshot(` + Array [ + Object { + "error": null, + "state": "ready", + "value": "testing", + }, + ] + `); }); it('deeply removes resolved values', () => { @@ -140,7 +150,7 @@ describe('resolved args reducer', () => { }); const newState = resolvedArgsReducer(state, action); - expect(newState.resolvedArgs['element-0']).to.be(undefined); + expect(newState.resolvedArgs['element-0']).toBe(undefined); }); }); @@ -183,12 +193,22 @@ describe('resolved args reducer', () => { }); const newState = resolvedArgsReducer(state, action); - expect(newState.resolvedArgs['element-1']).to.eql({ - expressionContext: { - '1': { state: 'ready', value: 'test-1', error: null }, - '2': { state: 'ready', value: 'test-2', error: null }, - }, - }); + expect(newState.resolvedArgs['element-1']).toMatchInlineSnapshot(` + Object { + "expressionContext": Object { + "1": Object { + "error": null, + "state": "ready", + "value": "test-1", + }, + "2": Object { + "error": null, + "state": "ready", + "value": "test-2", + }, + }, + } + `); }); }); }); diff --git a/x-pack/plugins/canvas/public/state/reducers/workpad.js b/x-pack/plugins/canvas/public/state/reducers/workpad.js index 9a0c30bdf1337..1c210577e1014 100644 --- a/x-pack/plugins/canvas/public/state/reducers/workpad.js +++ b/x-pack/plugins/canvas/public/state/reducers/workpad.js @@ -25,11 +25,7 @@ export const workpadReducer = handleActions( [setWorkpad]: (workpadState, { payload }) => { platformService .getService() - .coreStart.chrome.recentlyAccessed.add( - `${APP_ROUTE_WORKPAD}/${payload.id}`, - payload.name, - payload.id - ); + .setRecentlyAccessed(`${APP_ROUTE_WORKPAD}/${payload.id}`, payload.name, payload.id); return payload; }, @@ -44,11 +40,7 @@ export const workpadReducer = handleActions( [setName]: (workpadState, { payload }) => { platformService .getService() - .coreStart.chrome.recentlyAccessed.add( - `${APP_ROUTE_WORKPAD}/${workpadState.id}`, - payload, - workpadState.id - ); + .setRecentlyAccessed(`${APP_ROUTE_WORKPAD}/${workpadState.id}`, payload, workpadState.id); return { ...workpadState, name: payload }; }, diff --git a/x-pack/plugins/canvas/public/state/selectors/__tests__/resolved_args.js b/x-pack/plugins/canvas/public/state/selectors/resolved_args.test.js similarity index 55% rename from x-pack/plugins/canvas/public/state/selectors/__tests__/resolved_args.js rename to x-pack/plugins/canvas/public/state/selectors/resolved_args.test.js index 3157201927854..1710d6704f980 100644 --- a/x-pack/plugins/canvas/public/state/selectors/__tests__/resolved_args.js +++ b/x-pack/plugins/canvas/public/state/selectors/resolved_args.test.js @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import expect from '@kbn/expect'; -import * as selector from '../resolved_args'; +import * as selector from './resolved_args'; describe('resolved args selector', () => { let state; @@ -35,21 +34,20 @@ describe('resolved args selector', () => { }); it('getValue returns the state', () => { - expect(selector.getState(state, 'test1')).to.equal('ready'); - expect(selector.getState(state, 'test2')).to.equal('pending'); - expect(selector.getState(state, 'test3')).to.equal('error'); + expect(selector.getState(state, 'test1')).toEqual('ready'); + expect(selector.getState(state, 'test2')).toEqual('pending'); + expect(selector.getState(state, 'test3')).toEqual('error'); }); it('getValue returns the value', () => { - expect(selector.getValue(state, 'test1')).to.equal('test value'); - expect(selector.getValue(state, 'test2')).to.equal(null); - expect(selector.getValue(state, 'test3')).to.equal('some old value'); + expect(selector.getValue(state, 'test1')).toEqual('test value'); + expect(selector.getValue(state, 'test2')).toEqual(null); + expect(selector.getValue(state, 'test3')).toEqual('some old value'); }); it('getError returns the error', () => { - expect(selector.getError(state, 'test1')).to.equal(null); - expect(selector.getError(state, 'test2')).to.equal(null); - expect(selector.getError(state, 'test3')).to.be.an(Error); - expect(selector.getError(state, 'test3').toString()).to.match(/i\ have\ failed$/); + expect(selector.getError(state, 'test1')).toEqual(null); + expect(selector.getError(state, 'test2')).toEqual(null); + expect(selector.getError(state, 'test3')).toMatchInlineSnapshot(`[Error: i have failed]`); }); }); diff --git a/x-pack/plugins/canvas/public/state/selectors/resolved_args.ts b/x-pack/plugins/canvas/public/state/selectors/resolved_args.ts index 770d4403f8587..b557ff04921ca 100644 --- a/x-pack/plugins/canvas/public/state/selectors/resolved_args.ts +++ b/x-pack/plugins/canvas/public/state/selectors/resolved_args.ts @@ -5,9 +5,7 @@ */ import { get } from 'lodash'; -// @ts-expect-error untyped local import * as argHelper from '../../lib/resolved_arg'; -// @ts-expect-error untyped local import { prepend } from '../../lib/modify_path'; import { State } from '../../../types'; diff --git a/x-pack/plugins/canvas/public/state/selectors/__tests__/workpad.js b/x-pack/plugins/canvas/public/state/selectors/workpad.test.js similarity index 80% rename from x-pack/plugins/canvas/public/state/selectors/__tests__/workpad.js rename to x-pack/plugins/canvas/public/state/selectors/workpad.test.js index 5fdc662c592cc..d5f7e003af858 100644 --- a/x-pack/plugins/canvas/public/state/selectors/__tests__/workpad.js +++ b/x-pack/plugins/canvas/public/state/selectors/workpad.test.js @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import expect from '@kbn/expect'; -import * as selector from '../workpad'; +import * as selector from './workpad'; describe('workpad selectors', () => { let asts; @@ -125,42 +124,42 @@ describe('workpad selectors', () => { describe('empty state', () => { it('returns undefined', () => { - expect(selector.getSelectedPage({})).to.be(undefined); - expect(selector.getPageById({}, 'page-1')).to.be(undefined); - expect(selector.getSelectedElement({})).to.be(undefined); - expect(selector.getElementById({}, 'element-1')).to.be(undefined); - expect(selector.getResolvedArgs({}, 'element-1')).to.be(undefined); - expect(selector.getSelectedResolvedArgs({})).to.be(undefined); - expect(selector.isWriteable({})).to.be(true); + expect(selector.getSelectedPage({})).toBe(undefined); + expect(selector.getPageById({}, 'page-1')).toBe(undefined); + expect(selector.getSelectedElement({})).toBe(undefined); + expect(selector.getElementById({}, 'element-1')).toBe(undefined); + expect(selector.getResolvedArgs({}, 'element-1')).toBe(undefined); + expect(selector.getSelectedResolvedArgs({})).toBe(undefined); + expect(selector.isWriteable({})).toBe(true); }); }); describe('getSelectedPage', () => { it('returns the selected page', () => { - expect(selector.getSelectedPage(state)).to.equal('page-1'); + expect(selector.getSelectedPage(state)).toEqual('page-1'); }); }); describe('getPages', () => { it('return an empty array with no pages', () => { - expect(selector.getPages({})).to.eql([]); + expect(selector.getPages({})).toEqual([]); }); it('returns all pages in persisent state', () => { - expect(selector.getPages(state)).to.eql(state.persistent.workpad.pages); + expect(selector.getPages(state)).toEqual(state.persistent.workpad.pages); }); }); describe('getPageById', () => { it('should return matching page', () => { - expect(selector.getPageById(state, 'page-1')).to.eql(state.persistent.workpad.pages[0]); + expect(selector.getPageById(state, 'page-1')).toEqual(state.persistent.workpad.pages[0]); }); }); describe('getSelectedElement', () => { it('returns selected element', () => { const { elements } = state.persistent.workpad.pages[0]; - expect(selector.getSelectedElement(state)).to.eql({ + expect(selector.getSelectedElement(state)).toEqual({ ...elements[1], ast: asts['element-1'], }); @@ -169,7 +168,7 @@ describe('workpad selectors', () => { describe('getElements', () => { it('is an empty array with no state', () => { - expect(selector.getElements({})).to.eql([]); + expect(selector.getElements({})).toEqual([]); }); it('returns all elements on the page', () => { @@ -179,18 +178,18 @@ describe('workpad selectors', () => { ...element, ast: asts[element.id], })); - expect(selector.getElements(state)).to.eql(expected); + expect(selector.getElements(state)).toEqual(expected); }); }); describe('getElementById', () => { it('returns element matching id', () => { const { elements } = state.persistent.workpad.pages[0]; - expect(selector.getElementById(state, 'element-0')).to.eql({ + expect(selector.getElementById(state, 'element-0')).toEqual({ ...elements[0], ast: asts['element-0'], }); - expect(selector.getElementById(state, 'element-1')).to.eql({ + expect(selector.getElementById(state, 'element-1')).toEqual({ ...elements[1], ast: asts['element-1'], }); @@ -199,18 +198,18 @@ describe('workpad selectors', () => { describe('getResolvedArgs', () => { it('returns resolved args by element id', () => { - expect(selector.getResolvedArgs(state, 'element-0')).to.equal('test resolved arg, el 0'); + expect(selector.getResolvedArgs(state, 'element-0')).toEqual('test resolved arg, el 0'); }); it('returns resolved args at given path', () => { const arg = selector.getResolvedArgs(state, 'element-2', 'example1'); - expect(arg).to.equal('first thing'); + expect(arg).toEqual('first thing'); }); }); describe('getSelectedResolvedArgs', () => { it('returns resolved args for selected element', () => { - expect(selector.getSelectedResolvedArgs(state)).to.equal('test resolved arg, el 1'); + expect(selector.getSelectedResolvedArgs(state)).toEqual('test resolved arg, el 1'); }); it('returns resolved args at given path', () => { @@ -222,7 +221,7 @@ describe('workpad selectors', () => { }, }; const arg = selector.getSelectedResolvedArgs(tmpState, 'example2'); - expect(arg).to.eql(['why not', 'an array?']); + expect(arg).toEqual(['why not', 'an array?']); }); it('returns resolved args at given deep path', () => { @@ -234,14 +233,14 @@ describe('workpad selectors', () => { }, }; const arg = selector.getSelectedResolvedArgs(tmpState, ['example3', 'deeper', 'object']); - expect(arg).to.be(true); + expect(arg).toBe(true); }); }); describe('getGlobalFilters', () => { it('gets filters from all elements', () => { const filters = selector.getGlobalFilters(state); - expect(filters).to.eql([ + expect(filters).toEqual([ 'exactly value="beats" column="project"', 'timefilter filterGroup=one column=@timestamp from=now-24h to=now', ]); @@ -249,17 +248,14 @@ describe('workpad selectors', () => { it('gets returns empty array with no elements', () => { const filters = selector.getGlobalFilters({}); - expect(filters).to.be.an(Array); - expect(filters).to.have.length(0); + expect(filters).toEqual([]); }); }); describe('getGlobalFilterGroups', () => { it('gets filter group from elements', () => { const filterGroups = selector.getGlobalFilterGroups(state); - expect(filterGroups).to.be.an(Array); - expect(filterGroups).to.have.length(1); - expect(filterGroups[0]).to.equal('one'); + expect(filterGroups).toEqual(['one']); }); it('gets all unique filter groups', () => { @@ -282,7 +278,7 @@ describe('workpad selectors', () => { }); // filters are alphabetical - expect(filterGroups).to.eql(['one', 'two']); + expect(filterGroups).toEqual(['one', 'two']); }); it('gets filter groups in filter function args', () => { @@ -311,13 +307,13 @@ describe('workpad selectors', () => { // {string two} is skipped, only primitive values are extracted // filterGroup=one and {filters one} are de-duped // filters are alphabetical - expect(filterGroups).to.eql(['four', 'one', 'three']); + expect(filterGroups).toEqual(['four', 'one', 'three']); }); }); describe('isWriteable', () => { it('returns boolean for if the workpad is writeable', () => { - expect(selector.isWriteable(state)).to.equal(false); + expect(selector.isWriteable(state)).toEqual(false); }); }); }); diff --git a/x-pack/plugins/canvas/public/state/selectors/workpad.ts b/x-pack/plugins/canvas/public/state/selectors/workpad.ts index 1d7ea05daaa61..b05615b7930c5 100644 --- a/x-pack/plugins/canvas/public/state/selectors/workpad.ts +++ b/x-pack/plugins/canvas/public/state/selectors/workpad.ts @@ -7,7 +7,6 @@ import { get, omit } from 'lodash'; // @ts-expect-error untyped local import { safeElementFromExpression, fromExpression } from '@kbn/interpreter/common'; -// @ts-expect-error untyped local import { append } from '../../lib/modify_path'; import { getAssets } from './assets'; import { @@ -497,7 +496,7 @@ export function getRenderedWorkpad(state: State) { const workpad = getWorkpad(state); // eslint-disable-next-line no-unused-vars - const { pages, ...rest } = workpad; + const { pages, variables, ...rest } = workpad; return { pages: renderedPages, diff --git a/x-pack/plugins/canvas/public/style/index.scss b/x-pack/plugins/canvas/public/style/index.scss index ccaf6f1c1a478..3937d7fc05544 100644 --- a/x-pack/plugins/canvas/public/style/index.scss +++ b/x-pack/plugins/canvas/public/style/index.scss @@ -8,15 +8,12 @@ @import '../apps/export/export/export_app'; // Canvas components -@import '../components/alignment_guide/alignment_guide'; @import '../components/arg_add/arg_add'; @import '../components/arg_add_popover/arg_add_popover'; @import '../components/arg_form/arg_form'; @import '../components/asset_manager/asset_manager'; @import '../components/asset_picker/asset_picker'; @import '../components/autocomplete/autocomplete'; -@import '../components/border_connection/border_connection'; -@import '../components/border_resize_handle/border_resize_handle'; @import '../components/clipboard/clipboard'; @import '../components/color_dot/color_dot'; @import '../components/color_palette/color_palette'; @@ -27,25 +24,22 @@ @import '../components/datatable/datatable'; @import '../components/debug/debug'; @import '../components/dom_preview/dom_preview'; -@import '../components/dragbox_annotation/dragbox_annotation'; @import '../components/element_card/element_card'; @import '../components/element_content/element_content'; @import '../components/expression/expression'; @import '../components/fullscreen/fullscreen'; @import '../components/function_form/function_form'; -@import '../components/hover_annotation/hover_annotation'; +@import '../components/layout_annotations/layout_annotations'; @import '../components/loading/loading'; @import '../components/navbar/navbar'; @import '../components/page_manager/page_manager'; @import '../components/positionable/positionable'; -@import '../components/rotation_handle/rotation_handle'; @import '../components/shape_preview/shape_preview'; @import '../components/shape_picker/shape_picker'; @import '../components/sidebar/sidebar'; @import '../components/sidebar_header/sidebar_header'; @import '../components/toolbar/toolbar'; @import '../components/toolbar/tray/tray'; -@import '../components/tooltip_annotation/tooltip_annotation'; @import '../components/workpad/workpad'; @import '../components/workpad_header/element_menu/element_menu'; @import '../components/workpad_header/share_menu/share_menu'; diff --git a/x-pack/plugins/canvas/shareable_runtime/README.md b/x-pack/plugins/canvas/shareable_runtime/README.md index 8fdeb6ca6258e..3839e7c4ecb3f 100644 --- a/x-pack/plugins/canvas/shareable_runtime/README.md +++ b/x-pack/plugins/canvas/shareable_runtime/README.md @@ -207,7 +207,7 @@ There are a number of options for the build script: ### Prerequisite -Before testing or running this PR locally, you **must** run `node scripts/runtime` from `/canvas` _after_ `yarn kbn bootstrap` and _before_ starting Kibana. It is only built automatically when Kibana is built to avoid slowing down other development activities. +Before testing or running this PR locally, you **must** run `node scripts/shareable_runtime` from `/canvas` _after_ `yarn kbn bootstrap` and _before_ starting Kibana. It is only built automatically when Kibana is built to avoid slowing down other development activities. ### Webpack Dev Server diff --git a/x-pack/plugins/canvas/shareable_runtime/webpack.config.js b/x-pack/plugins/canvas/shareable_runtime/webpack.config.js index 1a5a21985ba72..93dc3dbccd549 100644 --- a/x-pack/plugins/canvas/shareable_runtime/webpack.config.js +++ b/x-pack/plugins/canvas/shareable_runtime/webpack.config.js @@ -55,7 +55,6 @@ module.exports = { options: { presets: [require.resolve('@kbn/babel-preset/webpack_preset')], }, - sideEffects: false, }, { test: /\.tsx?$/, @@ -92,6 +91,7 @@ module.exports = { }, }, ], + sideEffects: true, }, { test: /\.module\.s(a|c)ss$/, diff --git a/x-pack/plugins/canvas/storybook/config.js b/x-pack/plugins/canvas/storybook/config.js index f349f9b7ccf98..dc16d6c46084d 100644 --- a/x-pack/plugins/canvas/storybook/config.js +++ b/x-pack/plugins/canvas/storybook/config.js @@ -8,6 +8,7 @@ import { configure, addDecorator, addParameters } from '@storybook/react'; import { withInfo } from '@storybook/addon-info'; import { create } from '@storybook/theming'; +import { startServices } from '../public/services/stubs'; import { addDecorators } from './decorators'; // If we're running Storyshots, be sure to register the require context hook. @@ -32,6 +33,7 @@ if (process.env.NODE_ENV === 'test') { } addDecorators(); +startServices(); function loadStories() { require('./dll_contexts'); diff --git a/x-pack/plugins/dashboard_enhanced/kibana.json b/x-pack/plugins/dashboard_enhanced/kibana.json index ba5d8052ca787..264fa0438ea11 100644 --- a/x-pack/plugins/dashboard_enhanced/kibana.json +++ b/x-pack/plugins/dashboard_enhanced/kibana.json @@ -8,6 +8,7 @@ "requiredBundles": [ "kibanaUtils", "embeddableEnhanced", - "kibanaReact" + "kibanaReact", + "uiActions" ] } diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_create_drilldown/flyout_create_drilldown.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_create_drilldown/flyout_create_drilldown.tsx index 4804a700c6cff..2de862a6708a8 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_create_drilldown/flyout_create_drilldown.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_create_drilldown/flyout_create_drilldown.tsx @@ -6,7 +6,12 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; -import { ActionByType } from '../../../../../../../../src/plugins/ui_actions/public'; +import { + ActionByType, + APPLY_FILTER_TRIGGER, + SELECT_RANGE_TRIGGER, + VALUE_CLICK_TRIGGER, +} from '../../../../../../../../src/plugins/ui_actions/public'; import { toMountPoint } from '../../../../../../../../src/plugins/kibana_react/public'; import { isEnhancedEmbeddable } from '../../../../../../embeddable_enhanced/public'; import { EmbeddableContext } from '../../../../../../../../src/plugins/embeddable/public'; @@ -42,7 +47,9 @@ export class FlyoutCreateDrilldownAction implements ActionByType -1; + return supportedTriggers.some((trigger) => + [VALUE_CLICK_TRIGGER, SELECT_RANGE_TRIGGER, APPLY_FILTER_TRIGGER].includes(trigger) + ); } public async isCompatible(context: EmbeddableContext) { diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/constants.ts b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/constants.ts index e2a530b156da5..daefcf2d68cc5 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/constants.ts +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/constants.ts @@ -4,4 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ +/** + * note: + * don't change this string without carefull consideration, + * because it is stored in saved objects. + * Also temporary dashboard drilldown migration code inside embeddable plugin relies on it + * x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts + */ export const DASHBOARD_TO_DASHBOARD_DRILLDOWN = 'DASHBOARD_TO_DASHBOARD_DRILLDOWN'; diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.test.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.test.tsx index 52b232afa9410..40fa469feb34b 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.test.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.test.tsx @@ -5,9 +5,8 @@ */ import { DashboardToDashboardDrilldown } from './drilldown'; -import { savedObjectsServiceMock, coreMock } from '../../../../../../../src/core/public/mocks'; -import { dataPluginMock } from '../../../../../../../src/plugins/data/public/mocks'; -import { ActionContext, Config } from './types'; +import { Config } from './types'; +import { coreMock, savedObjectsServiceMock } from '../../../../../../../src/core/public/mocks'; import { Filter, FilterStateStore, @@ -15,16 +14,13 @@ import { RangeFilter, TimeRange, } from '../../../../../../../src/plugins/data/common'; -import { esFilters } from '../../../../../../../src/plugins/data/public'; - +import { + ApplyGlobalFilterActionContext, + esFilters, +} from '../../../../../../../src/plugins/data/public'; // convenient to use real implementation here. import { createDashboardUrlGenerator } from '../../../../../../../src/plugins/dashboard/public/url_generator'; import { UrlGeneratorsService } from '../../../../../../../src/plugins/share/public/url_generators'; -import { VisualizeEmbeddableContract } from '../../../../../../../src/plugins/visualizations/public'; -import { - RangeSelectContext, - ValueClickContext, -} from '../../../../../../../src/plugins/embeddable/public'; import { StartDependencies } from '../../../plugin'; import { SavedObjectLoader } from '../../../../../../../src/plugins/saved_objects/public'; import { StartServicesGetter } from '../../../../../../../src/plugins/kibana_utils/public/core'; @@ -82,11 +78,10 @@ describe('.execute() & getHref', () => { config: Partial, embeddableInput: { filters?: Filter[]; timeRange?: TimeRange; query?: Query }, filtersFromEvent: Filter[], - useRangeEvent = false + timeFieldName?: string ) { const navigateToApp = jest.fn(); const getUrlForApp = jest.fn((app, opt) => `${app}/${opt.path}`); - const dataPluginActions = dataPluginMock.createStartContract().actions; const savedObjectsClient = savedObjectsServiceMock.createStartContract().client; const drilldown = new DashboardToDashboardDrilldown({ @@ -102,9 +97,6 @@ describe('.execute() & getHref', () => { }, plugins: { uiActionsEnhanced: {}, - data: { - actions: dataPluginActions, - }, }, self: {}, })) as unknown) as StartServicesGetter>, @@ -119,12 +111,6 @@ describe('.execute() & getHref', () => { ) ), }); - const selectRangeFiltersSpy = jest - .spyOn(dataPluginActions, 'createFiltersFromRangeSelectAction') - .mockImplementation(() => Promise.resolve(filtersFromEvent)); - const valueClickFiltersSpy = jest - .spyOn(dataPluginActions, 'createFiltersFromValueClickAction') - .mockImplementation(() => Promise.resolve(filtersFromEvent)); const completeConfig: Config = { dashboardId: 'id', @@ -134,12 +120,7 @@ describe('.execute() & getHref', () => { }; const context = ({ - data: { - ...(useRangeEvent - ? ({ range: {} } as RangeSelectContext['data']) - : ({ data: [] } as ValueClickContext['data'])), - timeFieldName: 'order_date', - }, + filters: filtersFromEvent, embeddable: { getInput: () => ({ filters: [], @@ -148,18 +129,11 @@ describe('.execute() & getHref', () => { ...embeddableInput, }), }, - } as unknown) as ActionContext; + timeFieldName, + } as unknown) as ApplyGlobalFilterActionContext; await drilldown.execute(completeConfig, context); - if (useRangeEvent) { - expect(selectRangeFiltersSpy).toBeCalledTimes(1); - expect(valueClickFiltersSpy).toBeCalledTimes(0); - } else { - expect(selectRangeFiltersSpy).toBeCalledTimes(0); - expect(valueClickFiltersSpy).toBeCalledTimes(1); - } - expect(navigateToApp).toBeCalledTimes(1); expect(navigateToApp.mock.calls[0][0]).toBe('dashboards'); @@ -180,8 +154,7 @@ describe('.execute() & getHref', () => { dashboardId: testDashboardId, }, {}, - [], - false + [] ); expect(href).toEqual(expect.stringContaining(`view/${testDashboardId}`)); @@ -289,8 +262,7 @@ describe('.execute() & getHref', () => { to: 'now', }, }, - [], - false + [] ); expect(href).not.toEqual(expect.stringContaining('now-300m')); @@ -308,7 +280,7 @@ describe('.execute() & getHref', () => { }, }, [getMockTimeRangeFilter()], - true + getMockTimeRangeFilter().meta.key ); expect(href).not.toEqual(expect.stringContaining('now-300m')); diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.tsx index 26a69132cffb1..703acbc8d9d59 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.tsx @@ -6,20 +6,24 @@ import React from 'react'; import { reactToUiComponent } from '../../../../../../../src/plugins/kibana_react/public'; -import { DashboardUrlGenerator } from '../../../../../../../src/plugins/dashboard/public'; -import { ActionContext, Config } from './types'; +import { + DashboardUrlGenerator, + DashboardUrlGeneratorState, +} from '../../../../../../../src/plugins/dashboard/public'; import { CollectConfigContainer } from './components'; import { DASHBOARD_TO_DASHBOARD_DRILLDOWN } from './constants'; import { UiActionsEnhancedDrilldownDefinition as Drilldown } from '../../../../../ui_actions_enhanced/public'; import { txtGoToDashboard } from './i18n'; -import { esFilters } from '../../../../../../../src/plugins/data/public'; -import { VisualizeEmbeddableContract } from '../../../../../../../src/plugins/visualizations/public'; import { - isRangeSelectTriggerContext, - isValueClickTriggerContext, -} from '../../../../../../../src/plugins/embeddable/public'; + ApplyGlobalFilterActionContext, + esFilters, + isFilters, + isQuery, + isTimeRange, +} from '../../../../../../../src/plugins/data/public'; import { StartServicesGetter } from '../../../../../../../src/plugins/kibana_utils/public'; import { StartDependencies } from '../../../plugin'; +import { Config } from './types'; export interface Params { start: StartServicesGetter>; @@ -27,7 +31,7 @@ export interface Params { } export class DashboardToDashboardDrilldown - implements Drilldown> { + implements Drilldown { constructor(protected readonly params: Params) {} public readonly id = DASHBOARD_TO_DASHBOARD_DRILLDOWN; @@ -57,15 +61,12 @@ export class DashboardToDashboardDrilldown public readonly getHref = async ( config: Config, - context: ActionContext + context: ApplyGlobalFilterActionContext ): Promise => { return this.getDestinationUrl(config, context); }; - public readonly execute = async ( - config: Config, - context: ActionContext - ) => { + public readonly execute = async (config: Config, context: ApplyGlobalFilterActionContext) => { const dashboardPath = await this.getDestinationUrl(config, context); const dashboardHash = dashboardPath.split('#')[1]; @@ -76,73 +77,43 @@ export class DashboardToDashboardDrilldown private getDestinationUrl = async ( config: Config, - context: ActionContext + context: ApplyGlobalFilterActionContext ): Promise => { + const state: DashboardUrlGeneratorState = { + dashboardId: config.dashboardId, + }; + + if (context.embeddable) { + const input = context.embeddable.getInput(); + if (isQuery(input.query) && config.useCurrentFilters) state.query = input.query; + + // if useCurrentDashboardDataRange is enabled, then preserve current time range + // if undefined is passed, then destination dashboard will figure out time range itself + // for brush event this time range would be overwritten + if (isTimeRange(input.timeRange) && config.useCurrentDateRange) + state.timeRange = input.timeRange; + + // if useCurrentDashboardFilters enabled, then preserve all the filters (pinned and unpinned) + // otherwise preserve only pinned + if (isFilters(input.filters)) + state.filters = config.useCurrentFilters + ? input.filters + : input.filters?.filter((f) => esFilters.isFilterPinned(f)); + } + const { - createFiltersFromRangeSelectAction, - createFiltersFromValueClickAction, - } = this.params.start().plugins.data.actions; - const { - timeRange: currentTimeRange, - query, - filters: currentFilters, - } = context.embeddable!.getInput(); - - // if useCurrentDashboardFilters enabled, then preserve all the filters (pinned and unpinned) - // otherwise preserve only pinned - const existingFilters = - (config.useCurrentFilters - ? currentFilters - : currentFilters?.filter((f) => esFilters.isFilterPinned(f))) ?? []; - - // if useCurrentDashboardDataRange is enabled, then preserve current time range - // if undefined is passed, then destination dashboard will figure out time range itself - // for brush event this time range would be overwritten - let timeRange = config.useCurrentDateRange ? currentTimeRange : undefined; - let filtersFromEvent = await (async () => { - try { - if (isRangeSelectTriggerContext(context)) - return await createFiltersFromRangeSelectAction(context.data); - if (isValueClickTriggerContext(context)) - return await createFiltersFromValueClickAction(context.data); - - // eslint-disable-next-line no-console - console.warn( - ` - DashboardToDashboard drilldown: can't extract filters from action. - Is it not supported action?`, - context - ); - - return []; - } catch (e) { - // eslint-disable-next-line no-console - console.warn( - ` - DashboardToDashboard drilldown: error extracting filters from action. - Continuing without applying filters from event`, - e - ); - return []; - } - })(); - - if (context.data.timeFieldName) { - const { timeRangeFilter, restOfFilters } = esFilters.extractTimeFilter( - context.data.timeFieldName, - filtersFromEvent - ); - filtersFromEvent = restOfFilters; - if (timeRangeFilter) { - timeRange = esFilters.convertRangeFilterToTimeRangeString(timeRangeFilter); - } + restOfFilters: filtersFromEvent, + timeRange: timeRangeFromEvent, + } = esFilters.extractTimeRange(context.filters, context.timeFieldName); + + if (filtersFromEvent) { + state.filters = [...(state.filters ?? []), ...filtersFromEvent]; } - return this.params.getDashboardUrlGenerator().createUrl({ - dashboardId: config.dashboardId, - query: config.useCurrentFilters ? query : undefined, - timeRange, - filters: [...existingFilters, ...filtersFromEvent], - }); + if (timeRangeFromEvent) { + state.timeRange = timeRangeFromEvent; + } + + return this.params.getDashboardUrlGenerator().createUrl(state); }; } diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/index.ts b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/index.ts index 914f34980a272..49065a96b4f7b 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/index.ts +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/index.ts @@ -9,7 +9,4 @@ export { DashboardToDashboardDrilldown, Params as DashboardToDashboardDrilldownParams, } from './drilldown'; -export { - ActionContext as DashboardToDashboardActionContext, - Config as DashboardToDashboardConfig, -} from './types'; +export { Config } from './types'; diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/types.ts b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/types.ts index 6be2e2a77269f..426e250499de0 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/types.ts +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/types.ts @@ -4,16 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - ValueClickContext, - RangeSelectContext, - IEmbeddable, -} from '../../../../../../../src/plugins/embeddable/public'; - -export type ActionContext = - | ValueClickContext - | RangeSelectContext; - export interface Config { dashboardId?: string; useCurrentFilters: boolean; diff --git a/x-pack/plugins/data_enhanced/server/plugin.ts b/x-pack/plugins/data_enhanced/server/plugin.ts index 4f6756231912c..9c3a0edf7e733 100644 --- a/x-pack/plugins/data_enhanced/server/plugin.ts +++ b/x-pack/plugins/data_enhanced/server/plugin.ts @@ -9,6 +9,7 @@ import { CoreSetup, CoreStart, Plugin, + Logger, } from '../../../../src/core/server'; import { ES_SEARCH_STRATEGY } from '../../../../src/plugins/data/common'; import { PluginSetup as DataPluginSetup } from '../../../../src/plugins/data/server'; @@ -19,12 +20,19 @@ interface SetupDependencies { } export class EnhancedDataServerPlugin implements Plugin { - constructor(private initializerContext: PluginInitializerContext) {} + private readonly logger: Logger; + + constructor(private initializerContext: PluginInitializerContext) { + this.logger = initializerContext.logger.get('data_enhanced'); + } public setup(core: CoreSetup, deps: SetupDependencies) { deps.data.search.registerSearchStrategy( ES_SEARCH_STRATEGY, - enhancedEsSearchStrategyProvider(this.initializerContext.config.legacy.globalConfig$) + enhancedEsSearchStrategyProvider( + this.initializerContext.config.legacy.globalConfig$, + this.logger + ) ); } diff --git a/x-pack/plugins/data_enhanced/server/search/es_search_strategy.test.ts b/x-pack/plugins/data_enhanced/server/search/es_search_strategy.test.ts index 1eec941466b73..faa4f2ee499e5 100644 --- a/x-pack/plugins/data_enhanced/server/search/es_search_strategy.test.ts +++ b/x-pack/plugins/data_enhanced/server/search/es_search_strategy.test.ts @@ -31,6 +31,9 @@ const mockRollupResponse = { describe('ES search strategy', () => { const mockApiCaller = jest.fn(); + const mockLogger: any = { + info: () => {}, + }; const mockContext = { core: { elasticsearch: { legacy: { client: { callAsCurrentUser: mockApiCaller } } } }, }; @@ -41,7 +44,7 @@ describe('ES search strategy', () => { }); it('returns a strategy with `search`', async () => { - const esSearch = await enhancedEsSearchStrategyProvider(mockConfig$); + const esSearch = await enhancedEsSearchStrategyProvider(mockConfig$, mockLogger); expect(typeof esSearch.search).toBe('function'); }); @@ -50,7 +53,7 @@ describe('ES search strategy', () => { mockApiCaller.mockResolvedValueOnce(mockAsyncResponse); const params = { index: 'logstash-*', body: { query: {} } }; - const esSearch = await enhancedEsSearchStrategyProvider(mockConfig$); + const esSearch = await enhancedEsSearchStrategyProvider(mockConfig$, mockLogger); await esSearch.search((mockContext as unknown) as RequestHandlerContext, { params }); @@ -66,7 +69,7 @@ describe('ES search strategy', () => { mockApiCaller.mockResolvedValueOnce(mockAsyncResponse); const params = { index: 'logstash-*', body: { query: {} } }; - const esSearch = await enhancedEsSearchStrategyProvider(mockConfig$); + const esSearch = await enhancedEsSearchStrategyProvider(mockConfig$, mockLogger); await esSearch.search((mockContext as unknown) as RequestHandlerContext, { id: 'foo', params }); @@ -82,7 +85,7 @@ describe('ES search strategy', () => { mockApiCaller.mockResolvedValueOnce(mockAsyncResponse); const params = { index: 'foo-程', body: {} }; - const esSearch = await enhancedEsSearchStrategyProvider(mockConfig$); + const esSearch = await enhancedEsSearchStrategyProvider(mockConfig$, mockLogger); await esSearch.search((mockContext as unknown) as RequestHandlerContext, { params }); @@ -97,7 +100,7 @@ describe('ES search strategy', () => { mockApiCaller.mockResolvedValueOnce(mockRollupResponse); const params = { index: 'foo-程', body: {} }; - const esSearch = await enhancedEsSearchStrategyProvider(mockConfig$); + const esSearch = await enhancedEsSearchStrategyProvider(mockConfig$, mockLogger); await esSearch.search((mockContext as unknown) as RequestHandlerContext, { indexType: 'rollup', diff --git a/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts b/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts index 7b29117495a67..358335a2a4d60 100644 --- a/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts +++ b/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts @@ -12,6 +12,7 @@ import { LegacyAPICaller, SharedGlobalConfig, RequestHandlerContext, + Logger, } from '../../../../../src/core/server'; import { ISearchOptions, @@ -30,13 +31,15 @@ export interface AsyncSearchResponse { } export const enhancedEsSearchStrategyProvider = ( - config$: Observable + config$: Observable, + logger: Logger ): ISearchStrategy => { const search = async ( context: RequestHandlerContext, request: IEnhancedEsSearchRequest, options?: ISearchOptions ) => { + logger.info(`search ${JSON.stringify(request.params) || request.id}`); const config = await config$.pipe(first()).toPromise(); const caller = context.core.elasticsearch.legacy.client.callAsCurrentUser; const defaultParams = getDefaultSearchParams(config); @@ -48,6 +51,7 @@ export const enhancedEsSearchStrategyProvider = ( }; const cancel = async (context: RequestHandlerContext, id: string) => { + logger.info(`cancel ${id}`); const method = 'DELETE'; const path = encodeURI(`/_async_search/${id}`); await context.core.elasticsearch.legacy.client.callAsCurrentUser('transport.request', { diff --git a/x-pack/plugins/discover_enhanced/kibana.json b/x-pack/plugins/discover_enhanced/kibana.json index fbd04fe009687..531a84cd4c0e0 100644 --- a/x-pack/plugins/discover_enhanced/kibana.json +++ b/x-pack/plugins/discover_enhanced/kibana.json @@ -5,7 +5,7 @@ "server": true, "ui": true, "requiredPlugins": ["uiActions", "embeddable", "discover"], - "optionalPlugins": ["share"], + "optionalPlugins": ["share", "kibanaLegacy"], "configPath": ["xpack", "discoverEnhanced"], "requiredBundles": ["kibanaUtils", "data"] } diff --git a/x-pack/plugins/discover_enhanced/public/actions/explore_data/abstract_explore_data_action.ts b/x-pack/plugins/discover_enhanced/public/actions/explore_data/abstract_explore_data_action.ts index 59359fb35f544..434d38c76d428 100644 --- a/x-pack/plugins/discover_enhanced/public/actions/explore_data/abstract_explore_data_action.ts +++ b/x-pack/plugins/discover_enhanced/public/actions/explore_data/abstract_explore_data_action.ts @@ -9,6 +9,7 @@ import { DiscoverStart } from '../../../../../../src/plugins/discover/public'; import { EmbeddableStart } from '../../../../../../src/plugins/embeddable/public'; import { ViewMode, IEmbeddable } from '../../../../../../src/plugins/embeddable/public'; import { StartServicesGetter } from '../../../../../../src/plugins/kibana_utils/public'; +import { KibanaLegacyStart } from '../../../../../../src/plugins/kibana_legacy/public'; import { CoreStart } from '../../../../../../src/core/public'; import { KibanaURL } from './kibana_url'; import * as shared from './shared'; @@ -18,6 +19,11 @@ export const ACTION_EXPLORE_DATA = 'ACTION_EXPLORE_DATA'; export interface PluginDeps { discover: Pick; embeddable: Pick; + kibanaLegacy?: { + dashboardConfig: { + getHideWriteControls: KibanaLegacyStart['dashboardConfig']['getHideWriteControls']; + }; + }; } export interface CoreDeps { @@ -42,7 +48,17 @@ export abstract class AbstractExploreDataAction { if (!embeddable) return false; - if (!this.params.start().plugins.discover.urlGenerator) return false; + + const { core, plugins } = this.params.start(); + const { capabilities } = core.application; + + if (capabilities.discover && !capabilities.discover.show) return false; + if (!plugins.discover.urlGenerator) return false; + const isDashboardOnlyMode = !!this.params + .start() + .plugins.kibanaLegacy?.dashboardConfig.getHideWriteControls(); + if (isDashboardOnlyMode) return false; + if (!shared.hasExactlyOneIndexPattern(embeddable)) return false; if (embeddable.getInput().viewMode !== ViewMode.VIEW) return false; return true; diff --git a/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_chart_action.test.ts b/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_chart_action.test.ts index 0d22f0a36d418..14cd48ae1f509 100644 --- a/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_chart_action.test.ts +++ b/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_chart_action.test.ts @@ -34,7 +34,10 @@ afterEach(() => { i18nTranslateSpy.mockClear(); }); -const setup = ({ useRangeEvent = false }: { useRangeEvent?: boolean } = {}) => { +const setup = ({ + useRangeEvent = false, + dashboardOnlyMode = false, +}: { useRangeEvent?: boolean; dashboardOnlyMode?: boolean } = {}) => { type UrlGenerator = UrlGeneratorContract<'DISCOVER_APP_URL_GENERATOR'>; const core = coreMock.createStart(); @@ -54,6 +57,11 @@ const setup = ({ useRangeEvent = false }: { useRangeEvent?: boolean } = {}) => { embeddable: { filtersAndTimeRangeFromContext, }, + kibanaLegacy: { + dashboardConfig: { + getHideWriteControls: () => dashboardOnlyMode, + }, + }, }; const params: Params = { @@ -181,6 +189,26 @@ describe('"Explore underlying data" panel action', () => { expect(isCompatible).toBe(false); }); + + test('return false for dashboard_only mode', async () => { + const { action, context } = setup({ dashboardOnlyMode: true }); + const isCompatible = await action.isCompatible(context); + + expect(isCompatible).toBe(false); + }); + + test('returns false if Discover app is disabled', async () => { + const { action, context, core } = setup(); + + core.application.capabilities = { ...core.application.capabilities }; + (core.application.capabilities as any).discover = { + show: false, + }; + + const isCompatible = await action.isCompatible(context); + + expect(isCompatible).toBe(false); + }); }); describe('getHref()', () => { diff --git a/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_context_menu_action.test.ts b/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_context_menu_action.test.ts index c362e554e96c0..68253655af890 100644 --- a/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_context_menu_action.test.ts +++ b/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_context_menu_action.test.ts @@ -28,7 +28,7 @@ afterEach(() => { i18nTranslateSpy.mockClear(); }); -const setup = () => { +const setup = ({ dashboardOnlyMode = false }: { dashboardOnlyMode?: boolean } = {}) => { type UrlGenerator = UrlGeneratorContract<'DISCOVER_APP_URL_GENERATOR'>; const core = coreMock.createStart(); @@ -48,6 +48,11 @@ const setup = () => { embeddable: { filtersAndTimeRangeFromContext, }, + kibanaLegacy: { + dashboardConfig: { + getHideWriteControls: () => dashboardOnlyMode, + }, + }, }; const params: Params = { @@ -167,6 +172,26 @@ describe('"Explore underlying data" panel action', () => { expect(isCompatible).toBe(false); }); + + test('return false for dashboard_only mode', async () => { + const { action, context } = setup({ dashboardOnlyMode: true }); + const isCompatible = await action.isCompatible(context); + + expect(isCompatible).toBe(false); + }); + + test('returns false if Discover app is disabled', async () => { + const { action, context, core } = setup(); + + core.application.capabilities = { ...core.application.capabilities }; + (core.application.capabilities as any).discover = { + show: false, + }; + + const isCompatible = await action.isCompatible(context); + + expect(isCompatible).toBe(false); + }); }); describe('getHref()', () => { diff --git a/x-pack/plugins/discover_enhanced/public/plugin.ts b/x-pack/plugins/discover_enhanced/public/plugin.ts index 9613a9a8e3c8c..4b018354aa092 100644 --- a/x-pack/plugins/discover_enhanced/public/plugin.ts +++ b/x-pack/plugins/discover_enhanced/public/plugin.ts @@ -15,6 +15,7 @@ import { import { createStartServicesGetter } from '../../../../src/plugins/kibana_utils/public'; import { DiscoverSetup, DiscoverStart } from '../../../../src/plugins/discover/public'; import { SharePluginSetup, SharePluginStart } from '../../../../src/plugins/share/public'; +import { KibanaLegacySetup, KibanaLegacyStart } from '../../../../src/plugins/kibana_legacy/public'; import { EmbeddableSetup, EmbeddableStart, @@ -39,6 +40,7 @@ declare module '../../../../src/plugins/ui_actions/public' { export interface DiscoverEnhancedSetupDependencies { discover: DiscoverSetup; embeddable: EmbeddableSetup; + kibanaLegacy?: KibanaLegacySetup; share?: SharePluginSetup; uiActions: UiActionsSetup; } @@ -46,6 +48,7 @@ export interface DiscoverEnhancedSetupDependencies { export interface DiscoverEnhancedStartDependencies { discover: DiscoverStart; embeddable: EmbeddableStart; + kibanaLegacy?: KibanaLegacyStart; share?: SharePluginStart; uiActions: UiActionsStart; } diff --git a/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.test.ts b/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.test.ts index 5c5d98d75295d..fffb75451f8ac 100644 --- a/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.test.ts +++ b/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.test.ts @@ -11,6 +11,9 @@ import { } from './embeddable_action_storage'; import { UiActionsEnhancedSerializedEvent } from '../../../ui_actions_enhanced/public'; import { of } from '../../../../../src/plugins/kibana_utils/public'; +// use real const to make test fail in case someone accidentally changes it +import { DASHBOARD_TO_DASHBOARD_DRILLDOWN } from '../../../dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown'; +import { APPLY_FILTER_TRIGGER } from '../../../../../src/plugins/ui_actions/public'; class TestEmbeddable extends Embeddable { public readonly type = 'test'; @@ -539,4 +542,42 @@ describe('EmbeddableActionStorage', () => { expect(await storage.list()).toEqual([]); }); }); + + describe('migrate', () => { + test('DASHBOARD_TO_DASHBOARD_DRILLDOWN triggers migration', async () => { + const embeddable = new TestEmbeddable(); + const OTHER_TRIGGER = 'OTHER_TRIGGER'; + embeddable.updateInput({ + enhancements: { + dynamicActions: { + events: [ + { + eventId: '1', + triggers: [OTHER_TRIGGER], + action: { + factoryId: DASHBOARD_TO_DASHBOARD_DRILLDOWN, + name: '', + config: {}, + }, + }, + { + eventId: '2', + triggers: [OTHER_TRIGGER], + action: { + factoryId: 'SOME_OTHER', + name: '', + config: {}, + }, + }, + ], + }, + }, + }); + const storage = new EmbeddableActionStorage(embeddable); + + const [event1, event2] = await storage.list(); + expect(event1.triggers).toEqual([APPLY_FILTER_TRIGGER]); + expect(event2.triggers).toEqual([OTHER_TRIGGER]); + }); + }); }); diff --git a/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts b/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts index fdc42585a80ce..8881b2063c8db 100644 --- a/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts +++ b/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts @@ -46,7 +46,7 @@ export class EmbeddableActionStorage extends AbstractActionStorage { public async create(event: SerializedEvent) { const input = this.embbeddable.getInput(); - const events = input.enhancements?.dynamicActions?.events || []; + const events = this.getEventsFromEmbeddable(); const exists = !!events.find(({ eventId }) => eventId === event.eventId); if (exists) { @@ -61,7 +61,7 @@ export class EmbeddableActionStorage extends AbstractActionStorage { public async update(event: SerializedEvent) { const input = this.embbeddable.getInput(); - const events = input.enhancements?.dynamicActions?.events || []; + const events = this.getEventsFromEmbeddable(); const index = events.findIndex(({ eventId }) => eventId === event.eventId); if (index === -1) { @@ -77,7 +77,7 @@ export class EmbeddableActionStorage extends AbstractActionStorage { public async remove(eventId: string) { const input = this.embbeddable.getInput(); - const events = input.enhancements?.dynamicActions?.events || []; + const events = this.getEventsFromEmbeddable(); const index = events.findIndex((event) => eventId === event.eventId); if (index === -1) { @@ -93,7 +93,7 @@ export class EmbeddableActionStorage extends AbstractActionStorage { public async read(eventId: string): Promise { const input = this.embbeddable.getInput(); - const events = input.enhancements?.dynamicActions?.events || []; + const events = this.getEventsFromEmbeddable(); const event = events.find((ev) => eventId === ev.eventId); if (!event) { @@ -107,8 +107,28 @@ export class EmbeddableActionStorage extends AbstractActionStorage { } public async list(): Promise { + return this.getEventsFromEmbeddable(); + } + + private getEventsFromEmbeddable() { const input = this.embbeddable.getInput(); const events = input.enhancements?.dynamicActions?.events || []; - return events; + return this.migrate(events); + } + + // TODO: https://github.com/elastic/kibana/issues/71431 + // Migration implementation should use registry + // Action factories implementations should register own migrations + private migrate(events: SerializedEvent[]): SerializedEvent[] { + return events.map((event) => { + // Initially dashboard drilldown relied on VALUE_CLICK & RANGE_SELECT + if (event.action.factoryId === 'DASHBOARD_TO_DASHBOARD_DRILLDOWN') { + return { + ...event, + triggers: ['FILTER_TRIGGER'], + }; + } + return event; + }); } } diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/empty_states/error_state.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/empty_states/error_state.tsx index 7ac02082ee75c..346e70d32f7b1 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/empty_states/error_state.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/empty_states/error_state.tsx @@ -21,7 +21,7 @@ export const ErrorState: React.FC = () => { - + diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview_header/engine_overview_header.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview_header/engine_overview_header.test.tsx index 2e49540270ef0..7d2106f2a56f7 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview_header/engine_overview_header.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview_header/engine_overview_header.test.tsx @@ -30,12 +30,4 @@ describe('EngineOverviewHeader', () => { button.simulate('click'); expect(sendTelemetry).toHaveBeenCalled(); }); - - it('renders a disabled button when isButtonDisabled is true', () => { - const wrapper = shallow(); - const button = wrapper.find('[data-test-subj="launchButton"]'); - - expect(button.prop('isDisabled')).toBe(true); - expect(button.prop('href')).toBeUndefined(); - }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview_header/engine_overview_header.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview_header/engine_overview_header.tsx index 9aafa8ec0380c..cc480d241ad50 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview_header/engine_overview_header.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview_header/engine_overview_header.tsx @@ -18,34 +18,23 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { sendTelemetry } from '../../../shared/telemetry'; import { KibanaContext, IKibanaContext } from '../../../index'; -interface IEngineOverviewHeaderProps { - isButtonDisabled?: boolean; -} - -export const EngineOverviewHeader: React.FC = ({ - isButtonDisabled, -}) => { +export const EngineOverviewHeader: React.FC = () => { const { enterpriseSearchUrl, http } = useContext(KibanaContext) as IKibanaContext; const buttonProps = { fill: true, iconType: 'popout', 'data-test-subj': 'launchButton', - } as EuiButtonProps & EuiLinkProps; - - if (isButtonDisabled) { - buttonProps.isDisabled = true; - } else { - buttonProps.href = `${enterpriseSearchUrl}/as`; - buttonProps.target = '_blank'; - buttonProps.onClick = () => + href: `${enterpriseSearchUrl}/as`, + target: '_blank', + onClick: () => sendTelemetry({ http, product: 'app_search', action: 'clicked', metric: 'header_launch_button', - }); - } + }), + } as EuiButtonProps & EuiLinkProps; return ( diff --git a/x-pack/plugins/enterprise_search/public/applications/kea.d.ts b/x-pack/plugins/enterprise_search/public/applications/kea.d.ts new file mode 100644 index 0000000000000..961d93ccc12e6 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/kea.d.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +declare module 'kea' { + export function useValues(logic?: object): object; + export function useActions(logic?: object): object; + export function getContext(): { store: object }; + export function resetContext(context: object): object; + export function kea(logic: object): object; +} diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/error_state/error_state_prompt.scss b/x-pack/plugins/enterprise_search/public/applications/shared/error_state/error_state_prompt.scss new file mode 100644 index 0000000000000..0d9926ab147bf --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/shared/error_state/error_state_prompt.scss @@ -0,0 +1,12 @@ +.troubleshootingSteps { + text-align: left; + + li { + margin: $euiSizeS auto; + } + + ul, + ol { + margin-bottom: 0; + } +} diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/error_state/error_state_prompt.tsx b/x-pack/plugins/enterprise_search/public/applications/shared/error_state/error_state_prompt.tsx index 81455cea0b497..ccd5beff66e70 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/error_state/error_state_prompt.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/shared/error_state/error_state_prompt.tsx @@ -11,6 +11,8 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { EuiButton } from '../react_router_helpers'; import { KibanaContext, IKibanaContext } from '../../index'; +import './error_state_prompt.scss'; + export const ErrorStatePrompt: React.FC = () => { const { enterpriseSearchUrl } = useContext(KibanaContext) as IKibanaContext; @@ -38,7 +40,7 @@ export const ErrorStatePrompt: React.FC = () => { }} />

-
    +
    1. { defaultMessage="Confirm that the Enterprise Search server is responsive." />
    2. +
    3. + +
        +
      • + +
      • +
      • + +
      • +
      +
    4. { + mount(): void; + values: IKeaValues; + actions: IKeaActions; +} + +/** + * This reusable interface mostly saves us a few characters / allows us to skip + * defining params inline. Unfortunately, the return values *do not work* as + * expected (hence the voids). While I can tell selectors to use TKeaSelectors, + * the return value is *not* properly type checked if it's not declared inline. :/ + * + * Also note that if you switch to Kea 2.1's plain object notation - + * `selectors: {}` vs. `selectors: () => ({})` + * - type checking also stops working and type errors become significantly less + * helpful - showing less specific error messages and highlighting. 👎 + */ +export interface IKeaParams { + selectors?(params: { selectors: IKeaValues }): void; + listeners?(params: { actions: IKeaActions; values: IKeaValues }): void; +} + +/** + * This reducers() type checks that: + * + * 1. The value object keys are defined within IKeaValues + * 2. The default state (array[0]) matches the type definition within IKeaValues + * 3. The action object keys (array[1]) are defined within IKeaActions + * 3. The new state returned by the action matches the type definition within IKeaValues + */ +export type TKeaReducers = { + [Value in keyof IKeaValues]?: [ + IKeaValues[Value], + { + [Action in keyof IKeaActions]?: (state: IKeaValues, payload: IKeaValues) => IKeaValues[Value]; + } + ]; +}; + +/** + * This selectors() type checks that: + * + * 1. The object keys are defined within IKeaValues + * 2. The selected values are defined within IKeaValues + * 3. The returned value match the type definition within IKeaValues + * + * The unknown[] and any[] are unfortunately because I have no idea how to + * assert for arbitrary type/values as an array + */ +export type TKeaSelectors = { + [Value in keyof IKeaValues]?: [ + (selectors: IKeaValues) => unknown[], + (...args: any[]) => IKeaValues[Value] // eslint-disable-line @typescript-eslint/no-explicit-any + ]; +}; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/__mocks__/index.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/__mocks__/index.ts new file mode 100644 index 0000000000000..e5169a51ce522 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/__mocks__/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 { setMockValues, mockLogicValues, mockLogicActions } from './overview_logic.mock'; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/__mocks__/overview_logic.mock.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/__mocks__/overview_logic.mock.ts new file mode 100644 index 0000000000000..43cff5de6668d --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/__mocks__/overview_logic.mock.ts @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { IOverviewValues } from '../overview_logic'; +import { IAccount, IOrganization, IUser } from '../../../types'; + +export const mockLogicValues = { + accountsCount: 0, + activityFeed: [], + canCreateContentSources: false, + canCreateInvitations: false, + currentUser: {} as IUser, + fpAccount: {} as IAccount, + hasOrgSources: false, + hasUsers: false, + isFederatedAuth: true, + isOldAccount: false, + organization: {} as IOrganization, + pendingInvitationsCount: 0, + personalSourcesCount: 0, + sourcesCount: 0, + dataLoading: true, + hasErrorConnecting: false, + flashMessages: {}, +} as IOverviewValues; + +export const mockLogicActions = { + initializeOverview: jest.fn(() => ({})), +}; + +jest.mock('kea', () => ({ + ...(jest.requireActual('kea') as object), + useActions: jest.fn(() => ({ ...mockLogicActions })), + useValues: jest.fn(() => ({ ...mockLogicValues })), +})); + +import { useValues } from 'kea'; + +export const setMockValues = (values: object) => { + (useValues as jest.Mock).mockImplementationOnce(() => ({ + ...mockLogicValues, + ...values, + })); +}; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/onboarding_steps.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/onboarding_steps.test.tsx index 6174dc1c795eb..3cf88cf120cc4 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/onboarding_steps.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/onboarding_steps.test.tsx @@ -5,6 +5,8 @@ */ import '../../../__mocks__/shallow_usecontext.mock'; +import './__mocks__/overview_logic.mock'; +import { setMockValues } from './__mocks__'; import React from 'react'; import { shallow } from 'enzyme'; @@ -16,7 +18,6 @@ import { sendTelemetry } from '../../../shared/telemetry'; import { OnboardingSteps, OrgNameOnboarding } from './onboarding_steps'; import { OnboardingCard } from './onboarding_card'; -import { defaultServerData } from './overview'; const account = { id: '1', @@ -30,7 +31,8 @@ const account = { describe('OnboardingSteps', () => { describe('Shared Sources', () => { it('renders 0 sources state', () => { - const wrapper = shallow(); + setMockValues({ canCreateContentSources: true }); + const wrapper = shallow(); expect(wrapper.find(OnboardingCard)).toHaveLength(1); expect(wrapper.find(OnboardingCard).prop('actionPath')).toBe(ORG_SOURCES_PATH); @@ -40,9 +42,8 @@ describe('OnboardingSteps', () => { }); it('renders completed sources state', () => { - const wrapper = shallow( - - ); + setMockValues({ sourcesCount: 2, hasOrgSources: true }); + const wrapper = shallow(); expect(wrapper.find(OnboardingCard).prop('description')).toEqual( 'You have added 2 shared sources. Happy searching.' @@ -50,9 +51,8 @@ describe('OnboardingSteps', () => { }); it('disables link when the user cannot create sources', () => { - const wrapper = shallow( - - ); + setMockValues({ canCreateContentSources: false }); + const wrapper = shallow(); expect(wrapper.find(OnboardingCard).prop('actionPath')).toBe(undefined); }); @@ -60,15 +60,14 @@ describe('OnboardingSteps', () => { describe('Users & Invitations', () => { it('renders 0 users when not on federated auth', () => { - const wrapper = shallow( - - ); + setMockValues({ + canCreateInvitations: true, + isFederatedAuth: false, + fpAccount: account, + accountsCount: 0, + hasUsers: false, + }); + const wrapper = shallow(); expect(wrapper.find(OnboardingCard)).toHaveLength(2); expect(wrapper.find(OnboardingCard).last().prop('actionPath')).toBe(USERS_PATH); @@ -78,15 +77,13 @@ describe('OnboardingSteps', () => { }); it('renders completed users state', () => { - const wrapper = shallow( - - ); + setMockValues({ + isFederatedAuth: false, + fpAccount: account, + accountsCount: 1, + hasUsers: true, + }); + const wrapper = shallow(); expect(wrapper.find(OnboardingCard).last().prop('description')).toEqual( 'Nice, you’ve invited colleagues to search with you.' @@ -94,21 +91,15 @@ describe('OnboardingSteps', () => { }); it('disables link when the user cannot create invitations', () => { - const wrapper = shallow( - - ); - + setMockValues({ isFederatedAuth: false, canCreateInvitations: false }); + const wrapper = shallow(); expect(wrapper.find(OnboardingCard).last().prop('actionPath')).toBe(undefined); }); }); describe('Org Name', () => { it('renders button to change name', () => { - const wrapper = shallow(); + const wrapper = shallow(); const button = wrapper .find(OrgNameOnboarding) @@ -120,15 +111,13 @@ describe('OnboardingSteps', () => { }); it('hides card when name has been changed', () => { - const wrapper = shallow( - - ); + setMockValues({ + organization: { + name: 'foo', + defaultOrgName: 'bar', + }, + }); + const wrapper = shallow(); expect(wrapper.find(OrgNameOnboarding)).toHaveLength(0); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/onboarding_steps.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/onboarding_steps.tsx index 1b00347437338..7fe1eae502329 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/onboarding_steps.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/onboarding_steps.tsx @@ -7,6 +7,7 @@ import React, { useContext } from 'react'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; +import { useValues } from 'kea'; import { EuiSpacer, @@ -28,7 +29,7 @@ import { ORG_SOURCES_PATH, USERS_PATH, ORG_SETTINGS_PATH } from '../../routes'; import { ContentSection } from '../shared/content_section'; -import { IAppServerData } from './overview'; +import { OverviewLogic, IOverviewValues } from './overview_logic'; import { OnboardingCard } from './onboarding_card'; @@ -57,17 +58,19 @@ const ONBOARDING_USERS_CARD_DESCRIPTION = i18n.translate( { defaultMessage: 'Invite your colleagues into this organization to search with you.' } ); -export const OnboardingSteps: React.FC = ({ - hasUsers, - hasOrgSources, - canCreateContentSources, - canCreateInvitations, - accountsCount, - sourcesCount, - fpAccount: { isCurated }, - organization: { name, defaultOrgName }, - isFederatedAuth, -}) => { +export const OnboardingSteps: React.FC = () => { + const { + hasUsers, + hasOrgSources, + canCreateContentSources, + canCreateInvitations, + accountsCount, + sourcesCount, + fpAccount: { isCurated }, + organization: { name, defaultOrgName }, + isFederatedAuth, + } = useValues(OverviewLogic) as IOverviewValues; + const accountsPath = !isFederatedAuth && (canCreateInvitations || isCurated) ? USERS_PATH : undefined; const sourcesPath = canCreateContentSources || isCurated ? ORG_SOURCES_PATH : undefined; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/organization_stats.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/organization_stats.test.tsx index 112e9a910667a..d9b05c5da777d 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/organization_stats.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/organization_stats.test.tsx @@ -5,6 +5,8 @@ */ import '../../../__mocks__/shallow_usecontext.mock'; +import './__mocks__/overview_logic.mock'; +import { setMockValues } from './__mocks__'; import React from 'react'; import { shallow } from 'enzyme'; @@ -12,18 +14,18 @@ import { EuiFlexGrid } from '@elastic/eui'; import { OrganizationStats } from './organization_stats'; import { StatisticCard } from './statistic_card'; -import { defaultServerData } from './overview'; describe('OrganizationStats', () => { it('renders', () => { - const wrapper = shallow(); + const wrapper = shallow(); expect(wrapper.find(StatisticCard)).toHaveLength(2); expect(wrapper.find(EuiFlexGrid).prop('columns')).toEqual(2); }); it('renders additional cards for federated auth', () => { - const wrapper = shallow(); + setMockValues({ isFederatedAuth: false }); + const wrapper = shallow(); expect(wrapper.find(StatisticCard)).toHaveLength(4); expect(wrapper.find(EuiFlexGrid).prop('columns')).toEqual(4); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/organization_stats.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/organization_stats.tsx index aa9be81f32bae..4c5efce9baf12 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/organization_stats.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/organization_stats.tsx @@ -6,6 +6,7 @@ import React from 'react'; import { EuiFlexGrid } from '@elastic/eui'; +import { useValues } from 'kea'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; @@ -13,62 +14,66 @@ import { i18n } from '@kbn/i18n'; import { ContentSection } from '../shared/content_section'; import { ORG_SOURCES_PATH, USERS_PATH } from '../../routes'; -import { IAppServerData } from './overview'; +import { OverviewLogic, IOverviewValues } from './overview_logic'; import { StatisticCard } from './statistic_card'; -export const OrganizationStats: React.FC = ({ - sourcesCount, - pendingInvitationsCount, - accountsCount, - personalSourcesCount, - isFederatedAuth, -}) => ( - - } - headerSpacer="m" - > - - - {!isFederatedAuth && ( - <> - - - - )} - { + const { + sourcesCount, + pendingInvitationsCount, + accountsCount, + personalSourcesCount, + isFederatedAuth, + } = useValues(OverviewLogic) as IOverviewValues; + + return ( + + } + headerSpacer="m" + > + + + {!isFederatedAuth && ( + <> + + + )} - count={personalSourcesCount} - /> - - -); + + + + ); +}; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview.test.tsx index e5e5235c52368..744fd8aeb1951 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview.test.tsx @@ -5,11 +5,11 @@ */ import '../../../__mocks__/react_router_history.mock'; +import './__mocks__/overview_logic.mock'; +import { mockLogicActions, setMockValues } from './__mocks__'; import React from 'react'; -import { shallow } from 'enzyme'; - -import { mountWithAsyncContext, mockKibanaContext } from '../../../__mocks__'; +import { shallow, mount } from 'enzyme'; import { ErrorState } from '../error_state'; import { Loading } from '../shared/loading'; @@ -18,11 +18,9 @@ import { ViewContentHeader } from '../shared/view_content_header'; import { OnboardingSteps } from './onboarding_steps'; import { OrganizationStats } from './organization_stats'; import { RecentActivity } from './recent_activity'; -import { Overview, defaultServerData } from './overview'; +import { Overview } from './overview'; describe('Overview', () => { - const mockHttp = mockKibanaContext.http; - describe('non-happy-path states', () => { it('isLoading', () => { const wrapper = shallow(); @@ -30,24 +28,24 @@ describe('Overview', () => { expect(wrapper.find(Loading)).toHaveLength(1); }); - it('hasErrorConnecting', async () => { - const wrapper = await mountWithAsyncContext(, { - http: { - ...mockHttp, - get: () => Promise.reject({ invalidPayload: true }), - }, - }); + it('hasErrorConnecting', () => { + setMockValues({ hasErrorConnecting: true }); + const wrapper = shallow(); expect(wrapper.find(ErrorState)).toHaveLength(1); }); }); describe('happy-path states', () => { - it('renders onboarding state', async () => { - const mockApi = jest.fn(() => defaultServerData); - const wrapper = await mountWithAsyncContext(, { - http: { ...mockHttp, get: mockApi }, - }); + it('calls initialize function', async () => { + mount(); + + expect(mockLogicActions.initializeOverview).toHaveBeenCalled(); + }); + + it('renders onboarding state', () => { + setMockValues({ dataLoading: false }); + const wrapper = shallow(); expect(wrapper.find(ViewContentHeader)).toHaveLength(1); expect(wrapper.find(OnboardingSteps)).toHaveLength(1); @@ -55,9 +53,9 @@ describe('Overview', () => { expect(wrapper.find(RecentActivity)).toHaveLength(1); }); - it('renders when onboarding complete', async () => { - const obCompleteData = { - ...defaultServerData, + it('renders when onboarding complete', () => { + setMockValues({ + dataLoading: false, hasUsers: true, hasOrgSources: true, isOldAccount: true, @@ -65,11 +63,8 @@ describe('Overview', () => { name: 'foo', defaultOrgName: 'bar', }, - }; - const mockApi = jest.fn(() => obCompleteData); - const wrapper = await mountWithAsyncContext(, { - http: { ...mockHttp, get: mockApi }, }); + const wrapper = shallow(); expect(wrapper.find(OnboardingSteps)).toHaveLength(0); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview.tsx index bacd65a2be75f..b75a2841dad9b 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview.tsx @@ -4,15 +4,16 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useContext, useEffect, useState } from 'react'; +import React, { useContext, useEffect } from 'react'; import { EuiPage, EuiPageBody, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; +import { useActions, useValues } from 'kea'; import { SetWorkplaceSearchBreadcrumbs as SetBreadcrumbs } from '../../../shared/kibana_breadcrumbs'; import { SendWorkplaceSearchTelemetry as SendTelemetry } from '../../../shared/telemetry'; import { KibanaContext, IKibanaContext } from '../../../index'; -import { IAccount } from '../../types'; +import { OverviewLogic, IOverviewActions, IOverviewValues } from './overview_logic'; import { ErrorState } from '../error_state'; @@ -22,57 +23,7 @@ import { ViewContentHeader } from '../shared/view_content_header'; import { OnboardingSteps } from './onboarding_steps'; import { OrganizationStats } from './organization_stats'; -import { RecentActivity, IFeedActivity } from './recent_activity'; - -export interface IAppServerData { - hasUsers: boolean; - hasOrgSources: boolean; - canCreateContentSources: boolean; - canCreateInvitations: boolean; - isOldAccount: boolean; - sourcesCount: number; - pendingInvitationsCount: number; - accountsCount: number; - personalSourcesCount: number; - activityFeed: IFeedActivity[]; - organization: { - name: string; - defaultOrgName: string; - }; - isFederatedAuth: boolean; - currentUser: { - firstName: string; - email: string; - name: string; - color: string; - }; - fpAccount: IAccount; -} - -export const defaultServerData = { - accountsCount: 1, - activityFeed: [], - canCreateContentSources: true, - canCreateInvitations: true, - currentUser: { - firstName: '', - email: '', - name: '', - color: '', - }, - fpAccount: {} as IAccount, - hasOrgSources: false, - hasUsers: false, - isFederatedAuth: true, - isOldAccount: false, - organization: { - name: '', - defaultOrgName: '', - }, - pendingInvitationsCount: 0, - personalSourcesCount: 0, - sourcesCount: 0, -} as IAppServerData; +import { RecentActivity } from './recent_activity'; const ONBOARDING_HEADER_TITLE = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.overviewOnboardingHeader.title', @@ -96,34 +47,24 @@ const HEADER_DESCRIPTION = i18n.translate( export const Overview: React.FC = () => { const { http } = useContext(KibanaContext) as IKibanaContext; - const [isLoading, setIsLoading] = useState(true); - const [hasErrorConnecting, setHasErrorConnecting] = useState(false); - const [appData, setAppData] = useState(defaultServerData); - - const getAppData = async () => { - try { - const response = await http.get('/api/workplace_search/overview'); - setAppData(response); - } catch (error) { - setHasErrorConnecting(true); - } finally { - setIsLoading(false); - } - }; - - useEffect(() => { - getAppData(); - }, []); - - if (hasErrorConnecting) return ; - if (isLoading) return ; + const { initializeOverview } = useActions(OverviewLogic) as IOverviewActions; const { + dataLoading, + hasErrorConnecting, hasUsers, hasOrgSources, isOldAccount, organization: { name: orgName, defaultOrgName }, - } = appData as IAppServerData; + } = useValues(OverviewLogic) as IOverviewValues; + + useEffect(() => { + initializeOverview({ http }); + }, [initializeOverview]); + + if (hasErrorConnecting) return ; + if (dataLoading) return ; + const hideOnboarding = hasUsers && hasOrgSources && isOldAccount && orgName !== defaultOrgName; const headerTitle = hideOnboarding ? HEADER_TITLE : ONBOARDING_HEADER_TITLE; @@ -140,11 +81,11 @@ export const Overview: React.FC = () => { description={headerDescription} action={} /> - {!hideOnboarding && } + {!hideOnboarding && } - + - + ); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview_logic.test.ts new file mode 100644 index 0000000000000..285ec9b973378 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview_logic.test.ts @@ -0,0 +1,141 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { resetContext } from 'kea'; +import { act } from 'react-dom/test-utils'; + +import { mockKibanaContext } from '../../../__mocks__'; + +import { mockLogicValues } from './__mocks__'; +import { OverviewLogic } from './overview_logic'; + +describe('OverviewLogic', () => { + let unmount: any; + + beforeEach(() => { + resetContext({}); + unmount = OverviewLogic.mount() as any; + jest.clearAllMocks(); + }); + + afterEach(() => { + unmount(); + }); + + it('has expected default values', () => { + expect(OverviewLogic.values).toEqual(mockLogicValues); + }); + + describe('setServerData', () => { + const feed = [{ foo: 'bar' }] as any; + const user = { firstName: 'Joe', email: 'e@e.e', name: 'Joe Jo', color: 'pearl' }; + const account = { + name: 'Jane doe', + id: '1243', + isAdmin: true, + canCreatePersonalSources: true, + groups: [], + supportEligible: true, + }; + const org = { name: 'ACME', defaultOrgName: 'Org' }; + + const data = { + accountsCount: 1, + activityFeed: feed, + canCreateContentSources: true, + canCreateInvitations: true, + currentUser: user, + fpAccount: account, + hasOrgSources: true, + hasUsers: true, + isFederatedAuth: false, + isOldAccount: true, + organization: org, + pendingInvitationsCount: 1, + personalSourcesCount: 1, + sourcesCount: 1, + }; + + beforeEach(() => { + OverviewLogic.actions.setServerData(data); + }); + + it('will set `dataLoading` to false', () => { + expect(OverviewLogic.values.dataLoading).toEqual(false); + }); + + it('will set server values', () => { + expect(OverviewLogic.values.organization).toEqual(org); + expect(OverviewLogic.values.isFederatedAuth).toEqual(false); + expect(OverviewLogic.values.currentUser).toEqual(user); + expect(OverviewLogic.values.fpAccount).toEqual(account); + expect(OverviewLogic.values.canCreateInvitations).toEqual(true); + expect(OverviewLogic.values.hasUsers).toEqual(true); + expect(OverviewLogic.values.hasOrgSources).toEqual(true); + expect(OverviewLogic.values.canCreateContentSources).toEqual(true); + expect(OverviewLogic.values.isOldAccount).toEqual(true); + expect(OverviewLogic.values.sourcesCount).toEqual(1); + expect(OverviewLogic.values.pendingInvitationsCount).toEqual(1); + expect(OverviewLogic.values.accountsCount).toEqual(1); + expect(OverviewLogic.values.personalSourcesCount).toEqual(1); + expect(OverviewLogic.values.activityFeed).toEqual(feed); + }); + }); + + describe('setFlashMessages', () => { + it('will set `flashMessages`', () => { + const flashMessages = { error: ['error'] }; + OverviewLogic.actions.setFlashMessages(flashMessages); + + expect(OverviewLogic.values.flashMessages).toEqual(flashMessages); + }); + }); + + describe('setHasErrorConnecting', () => { + it('will set `hasErrorConnecting`', () => { + OverviewLogic.actions.setHasErrorConnecting(true); + + expect(OverviewLogic.values.hasErrorConnecting).toEqual(true); + expect(OverviewLogic.values.dataLoading).toEqual(false); + }); + }); + + describe('initializeOverview', () => { + it('calls API and sets values', async () => { + const mockHttp = mockKibanaContext.http; + const mockApi = jest.fn(() => mockLogicValues as any); + const setServerDataSpy = jest.spyOn(OverviewLogic.actions, 'setServerData'); + + await act(async () => + OverviewLogic.actions.initializeOverview({ + http: { + ...mockHttp, + get: mockApi, + }, + }) + ); + + expect(mockApi).toHaveBeenCalledWith('/api/workplace_search/overview'); + expect(setServerDataSpy).toHaveBeenCalled(); + }); + + it('handles error state', async () => { + const mockHttp = mockKibanaContext.http; + const setHasErrorConnectingSpy = jest.spyOn(OverviewLogic.actions, 'setHasErrorConnecting'); + + await act(async () => + OverviewLogic.actions.initializeOverview({ + http: { + ...mockHttp, + get: () => Promise.reject(), + }, + }) + ); + + expect(setHasErrorConnectingSpy).toHaveBeenCalled(); + }); + }); +}); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview_logic.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview_logic.ts new file mode 100644 index 0000000000000..f1b4f447f7445 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/overview_logic.ts @@ -0,0 +1,168 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { HttpSetup } from 'src/core/public'; + +import { kea } from 'kea'; + +import { IAccount, IOrganization, IUser } from '../../types'; +import { IFlashMessagesProps, IKeaLogic, TKeaReducers, IKeaParams } from '../../../shared/types'; + +import { IFeedActivity } from './recent_activity'; + +export interface IOverviewServerData { + hasUsers: boolean; + hasOrgSources: boolean; + canCreateContentSources: boolean; + canCreateInvitations: boolean; + isOldAccount: boolean; + sourcesCount: number; + pendingInvitationsCount: number; + accountsCount: number; + personalSourcesCount: number; + activityFeed: IFeedActivity[]; + organization: IOrganization; + isFederatedAuth: boolean; + currentUser: IUser; + fpAccount: IAccount; +} + +export interface IOverviewActions { + setServerData(serverData: IOverviewServerData): void; + setFlashMessages(flashMessages: IFlashMessagesProps): void; + setHasErrorConnecting(hasErrorConnecting: boolean): void; + initializeOverview({ http }: { http: HttpSetup }): void; +} + +export interface IOverviewValues extends IOverviewServerData { + dataLoading: boolean; + hasErrorConnecting: boolean; + flashMessages: IFlashMessagesProps; +} + +export const OverviewLogic = kea({ + actions: (): IOverviewActions => ({ + setServerData: (serverData) => serverData, + setFlashMessages: (flashMessages) => ({ flashMessages }), + setHasErrorConnecting: (hasErrorConnecting) => ({ hasErrorConnecting }), + initializeOverview: ({ http }) => ({ http }), + }), + reducers: (): TKeaReducers => ({ + organization: [ + {} as IOrganization, + { + setServerData: (_, { organization }) => organization, + }, + ], + isFederatedAuth: [ + true, + { + setServerData: (_, { isFederatedAuth }) => isFederatedAuth, + }, + ], + currentUser: [ + {} as IUser, + { + setServerData: (_, { currentUser }) => currentUser, + }, + ], + fpAccount: [ + {} as IAccount, + { + setServerData: (_, { fpAccount }) => fpAccount, + }, + ], + canCreateInvitations: [ + false, + { + setServerData: (_, { canCreateInvitations }) => canCreateInvitations, + }, + ], + flashMessages: [ + {}, + { + setFlashMessages: (_, { flashMessages }) => flashMessages, + }, + ], + hasUsers: [ + false, + { + setServerData: (_, { hasUsers }) => hasUsers, + }, + ], + hasOrgSources: [ + false, + { + setServerData: (_, { hasOrgSources }) => hasOrgSources, + }, + ], + canCreateContentSources: [ + false, + { + setServerData: (_, { canCreateContentSources }) => canCreateContentSources, + }, + ], + isOldAccount: [ + false, + { + setServerData: (_, { isOldAccount }) => isOldAccount, + }, + ], + sourcesCount: [ + 0, + { + setServerData: (_, { sourcesCount }) => sourcesCount, + }, + ], + pendingInvitationsCount: [ + 0, + { + setServerData: (_, { pendingInvitationsCount }) => pendingInvitationsCount, + }, + ], + accountsCount: [ + 0, + { + setServerData: (_, { accountsCount }) => accountsCount, + }, + ], + personalSourcesCount: [ + 0, + { + setServerData: (_, { personalSourcesCount }) => personalSourcesCount, + }, + ], + activityFeed: [ + [], + { + setServerData: (_, { activityFeed }) => activityFeed, + }, + ], + dataLoading: [ + true, + { + setServerData: () => false, + setHasErrorConnecting: () => false, + }, + ], + hasErrorConnecting: [ + false, + { + setHasErrorConnecting: (_, { hasErrorConnecting }) => hasErrorConnecting, + }, + ], + }), + listeners: ({ actions }): Partial => ({ + initializeOverview: async ({ http }: { http: HttpSetup }) => { + try { + const response = await http.get('/api/workplace_search/overview'); + actions.setServerData(response); + } catch (error) { + actions.setHasErrorConnecting(true); + } + }, + }), +} as IKeaParams) as IKeaLogic; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/recent_activity.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/recent_activity.test.tsx index e9bdedb199dad..22a82af18527d 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/recent_activity.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/recent_activity.test.tsx @@ -5,6 +5,8 @@ */ import '../../../__mocks__/shallow_usecontext.mock'; +import './__mocks__/overview_logic.mock'; +import { setMockValues } from './__mocks__'; import React from 'react'; import { shallow } from 'enzyme'; @@ -12,14 +14,13 @@ import { shallow } from 'enzyme'; import { EuiEmptyPrompt, EuiLink } from '@elastic/eui'; import { RecentActivity, RecentActivityItem } from './recent_activity'; -import { defaultServerData } from './overview'; jest.mock('../../../shared/telemetry', () => ({ sendTelemetry: jest.fn() })); import { sendTelemetry } from '../../../shared/telemetry'; -const org = { name: 'foo', defaultOrgName: 'bar' }; +const organization = { name: 'foo', defaultOrgName: 'bar' }; -const feed = [ +const activityFeed = [ { id: 'demo', sourceId: 'd2d2d23d', @@ -30,17 +31,19 @@ const feed = [ ]; describe('RecentActivity', () => { - it('renders with no feed data', () => { - const wrapper = shallow(); + it('renders with no activityFeed data', () => { + const wrapper = shallow(); expect(wrapper.find(EuiEmptyPrompt)).toHaveLength(1); // Branch coverage - renders without error for custom org name - shallow(); + setMockValues({ organization }); + shallow(); }); - it('renders an activity feed with links', () => { - const wrapper = shallow(); + it('renders an activityFeed with links', () => { + setMockValues({ activityFeed }); + const wrapper = shallow(); const activity = wrapper.find(RecentActivityItem).dive(); expect(activity).toHaveLength(1); @@ -51,7 +54,7 @@ describe('RecentActivity', () => { }); it('renders activity item error state', () => { - const props = { ...feed[0], status: 'error' }; + const props = { ...activityFeed[0], status: 'error' }; const wrapper = shallow(); expect(wrapper.find('.activity--error')).toHaveLength(1); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/recent_activity.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/recent_activity.tsx index 8d69582c93684..2c0fbe1275cbf 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/recent_activity.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/overview/recent_activity.tsx @@ -7,6 +7,7 @@ import React, { useContext } from 'react'; import moment from 'moment'; +import { useValues } from 'kea'; import { EuiEmptyPrompt, EuiLink, EuiPanel, EuiSpacer, EuiLinkProps } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -17,7 +18,7 @@ import { sendTelemetry } from '../../../shared/telemetry'; import { KibanaContext, IKibanaContext } from '../../../index'; import { getSourcePath } from '../../routes'; -import { IAppServerData } from './overview'; +import { OverviewLogic, IOverviewValues } from './overview_logic'; import './recent_activity.scss'; @@ -29,10 +30,12 @@ export interface IFeedActivity { sourceId: string; } -export const RecentActivity: React.FC = ({ - organization: { name, defaultOrgName }, - activityFeed, -}) => { +export const RecentActivity: React.FC = () => { + const { + organization: { name, defaultOrgName }, + activityFeed, + } = useValues(OverviewLogic) as IOverviewValues; + return ( , testSubj: 'contentSection', - className: 'test', }; describe('ContentSection', () => { it('renders', () => { - const wrapper = shallow(); + const wrapper = shallow(); expect(wrapper.prop('data-test-subj')).toEqual('contentSection'); expect(wrapper.prop('className')).toEqual('test'); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/shared/view_content_header/view_content_header.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/shared/view_content_header/view_content_header.test.tsx index 4680f15771caa..b0b07c46b4ea8 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/shared/view_content_header/view_content_header.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/shared/view_content_header/view_content_header.test.tsx @@ -26,9 +26,10 @@ describe('ViewContentHeader', () => { }); it('shows description, when present', () => { - const wrapper = shallow(); + const wrapper = shallow(); expect(wrapper.find('p').text()).toEqual('Hello World'); + expect(wrapper.find(EuiFlexGroup).prop('alignItems')).toEqual('center'); }); it('shows action, when present', () => { diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/index.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/index.tsx index 36b1a56ecba26..cfa70ea29eca8 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/index.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/index.tsx @@ -6,6 +6,13 @@ import React, { useContext } from 'react'; import { Route, Redirect } from 'react-router-dom'; +import { Provider } from 'react-redux'; +import { Store } from 'redux'; +import { getContext, resetContext } from 'kea'; + +resetContext({ createStore: true }); + +const store = getContext().store as Store; import { KibanaContext, IKibanaContext } from '../index'; @@ -17,13 +24,13 @@ import { Overview } from './components/overview'; export const WorkplaceSearch: React.FC = () => { const { enterpriseSearchUrl } = useContext(KibanaContext) as IKibanaContext; return ( - <> + {!enterpriseSearchUrl ? : } - + ); }; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/types.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/types.ts index b448c59c52f3e..77c35adef3300 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/types.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/types.ts @@ -13,4 +13,15 @@ export interface IAccount { supportEligible: boolean; } +export interface IOrganization { + name: string; + defaultOrgName: string; +} +export interface IUser { + firstName: string; + email: string; + name: string; + color: string; +} + export type TSpacerSize = 'xs' | 's' | 'm' | 'l' | 'xl' | 'xxl'; diff --git a/x-pack/plugins/features/common/feature.ts b/x-pack/plugins/features/common/feature.ts index 4a293e0c962cc..1b700fb1a6ad0 100644 --- a/x-pack/plugins/features/common/feature.ts +++ b/x-pack/plugins/features/common/feature.ts @@ -94,6 +94,13 @@ export interface FeatureConfig { */ catalogue?: readonly string[]; + /** + * If your feature grants access to specific Alert Types, you can specify them here to control visibility based on the current space. + * Include both Alert Types registered by the feature and external Alert Types such as built-in + * Alert Types and Alert Types provided by other features to which you wish to grant access. + */ + alerting?: readonly string[]; + /** * Feature privilege definition. * @@ -179,6 +186,10 @@ export class Feature { return this.config.privileges; } + public get alerting() { + return this.config.alerting; + } + public get excludeFromBasePrivileges() { return this.config.excludeFromBasePrivileges ?? false; } diff --git a/x-pack/plugins/features/common/feature_kibana_privileges.ts b/x-pack/plugins/features/common/feature_kibana_privileges.ts index a9ba38e36f20b..c8faf75b348fd 100644 --- a/x-pack/plugins/features/common/feature_kibana_privileges.ts +++ b/x-pack/plugins/features/common/feature_kibana_privileges.ts @@ -75,6 +75,34 @@ export interface FeatureKibanaPrivileges { */ app?: readonly string[]; + /** + * If your feature requires access to specific Alert Types, then specify your access needs here. + * Include both Alert Types registered by the feature and external Alert Types such as built-in + * Alert Types and Alert Types provided by other features to which you wish to grant access. + */ + alerting?: { + /** + * List of alert types which users should have full read/write access to when granted this privilege. + * @example + * ```ts + * { + * all: ['my-alert-type-within-my-feature'] + * } + * ``` + */ + all?: readonly string[]; + + /** + * List of alert types which users should have read-only access to when granted this privilege. + * @example + * ```ts + * { + * read: ['my-alert-type'] + * } + * ``` + */ + read?: readonly string[]; + }; /** * If your feature requires access to specific saved objects, then specify your access needs here. */ diff --git a/x-pack/plugins/features/server/__snapshots__/oss_features.test.ts.snap b/x-pack/plugins/features/server/__snapshots__/oss_features.test.ts.snap index fe0a13fe702e5..bfbc8b68c3d2c 100644 --- a/x-pack/plugins/features/server/__snapshots__/oss_features.test.ts.snap +++ b/x-pack/plugins/features/server/__snapshots__/oss_features.test.ts.snap @@ -55,6 +55,10 @@ exports[`buildOSSFeatures returns the dashboard feature augmented with appropria Array [ Object { "privilege": Object { + "alerting": Object { + "all": Array [], + "read": Array [], + }, "api": Array [], "app": Array [ "dashboards", @@ -67,8 +71,8 @@ Array [ "savedObject": Object { "all": Array [ "dashboard", - "url", "query", + "url", ], "read": Array [ "index-pattern", @@ -179,6 +183,10 @@ exports[`buildOSSFeatures returns the discover feature augmented with appropriat Array [ Object { "privilege": Object { + "alerting": Object { + "all": Array [], + "read": Array [], + }, "api": Array [], "app": Array [ "discover", @@ -403,6 +411,10 @@ exports[`buildOSSFeatures returns the visualize feature augmented with appropria Array [ Object { "privilege": Object { + "alerting": Object { + "all": Array [], + "read": Array [], + }, "api": Array [], "app": Array [ "visualize", diff --git a/x-pack/plugins/features/server/feature_registry.test.ts b/x-pack/plugins/features/server/feature_registry.test.ts index 75022922917b3..f123068e41758 100644 --- a/x-pack/plugins/features/server/feature_registry.test.ts +++ b/x-pack/plugins/features/server/feature_registry.test.ts @@ -743,6 +743,168 @@ describe('FeatureRegistry', () => { ); }); + it(`prevents privileges from specifying alerting entries that don't exist at the root level`, () => { + const feature: FeatureConfig = { + id: 'test-feature', + name: 'Test Feature', + app: [], + alerting: ['bar'], + privileges: { + all: { + alerting: { + all: ['foo', 'bar'], + read: ['baz'], + }, + savedObject: { + all: [], + read: [], + }, + ui: [], + app: [], + }, + read: { + alerting: { read: ['foo', 'bar', 'baz'] }, + savedObject: { + all: [], + read: [], + }, + ui: [], + app: [], + }, + }, + }; + + const featureRegistry = new FeatureRegistry(); + + expect(() => featureRegistry.register(feature)).toThrowErrorMatchingInlineSnapshot( + `"Feature privilege test-feature.all has unknown alerting entries: foo, baz"` + ); + }); + + it(`prevents features from specifying alerting entries that don't exist at the privilege level`, () => { + const feature: FeatureConfig = { + id: 'test-feature', + name: 'Test Feature', + app: [], + alerting: ['foo', 'bar', 'baz'], + privileges: { + all: { + alerting: { all: ['foo'] }, + savedObject: { + all: [], + read: [], + }, + ui: [], + app: [], + }, + read: { + alerting: { all: ['foo'] }, + savedObject: { + all: [], + read: [], + }, + ui: [], + app: [], + }, + }, + subFeatures: [ + { + name: 'my sub feature', + privilegeGroups: [ + { + groupType: 'independent', + privileges: [ + { + id: 'cool-sub-feature-privilege', + name: 'cool privilege', + includeIn: 'none', + savedObject: { + all: [], + read: [], + }, + ui: [], + alerting: { all: ['bar'] }, + }, + ], + }, + ], + }, + ], + }; + + const featureRegistry = new FeatureRegistry(); + + expect(() => featureRegistry.register(feature)).toThrowErrorMatchingInlineSnapshot( + `"Feature test-feature specifies alerting entries which are not granted to any privileges: baz"` + ); + }); + + it(`prevents reserved privileges from specifying alerting entries that don't exist at the root level`, () => { + const feature: FeatureConfig = { + id: 'test-feature', + name: 'Test Feature', + app: [], + alerting: ['bar'], + privileges: null, + reserved: { + description: 'something', + privileges: [ + { + id: 'reserved', + privilege: { + alerting: { all: ['foo', 'bar', 'baz'] }, + savedObject: { + all: [], + read: [], + }, + ui: [], + app: [], + }, + }, + ], + }, + }; + + const featureRegistry = new FeatureRegistry(); + + expect(() => featureRegistry.register(feature)).toThrowErrorMatchingInlineSnapshot( + `"Feature privilege test-feature.reserved has unknown alerting entries: foo, baz"` + ); + }); + + it(`prevents features from specifying alerting entries that don't exist at the reserved privilege level`, () => { + const feature: FeatureConfig = { + id: 'test-feature', + name: 'Test Feature', + app: [], + alerting: ['foo', 'bar', 'baz'], + privileges: null, + reserved: { + description: 'something', + privileges: [ + { + id: 'reserved', + privilege: { + alerting: { all: ['foo', 'bar'] }, + savedObject: { + all: [], + read: [], + }, + ui: [], + app: [], + }, + }, + ], + }, + }; + + const featureRegistry = new FeatureRegistry(); + + expect(() => featureRegistry.register(feature)).toThrowErrorMatchingInlineSnapshot( + `"Feature test-feature specifies alerting entries which are not granted to any privileges: baz"` + ); + }); + it(`prevents privileges from specifying management sections that don't exist at the root level`, () => { const feature: FeatureConfig = { id: 'test-feature', diff --git a/x-pack/plugins/features/server/feature_schema.ts b/x-pack/plugins/features/server/feature_schema.ts index c45788b511cde..95298603d706a 100644 --- a/x-pack/plugins/features/server/feature_schema.ts +++ b/x-pack/plugins/features/server/feature_schema.ts @@ -26,6 +26,7 @@ const managementSchema = Joi.object().pattern( Joi.array().items(Joi.string().regex(uiCapabilitiesRegex)) ); const catalogueSchema = Joi.array().items(Joi.string().regex(uiCapabilitiesRegex)); +const alertingSchema = Joi.array().items(Joi.string()); const privilegeSchema = Joi.object({ excludeFromBasePrivileges: Joi.boolean(), @@ -33,6 +34,10 @@ const privilegeSchema = Joi.object({ catalogue: catalogueSchema, api: Joi.array().items(Joi.string()), app: Joi.array().items(Joi.string()), + alerting: Joi.object({ + all: alertingSchema, + read: alertingSchema, + }), savedObject: Joi.object({ all: Joi.array().items(Joi.string()).required(), read: Joi.array().items(Joi.string()).required(), @@ -46,6 +51,10 @@ const subFeaturePrivilegeSchema = Joi.object({ includeIn: Joi.string().allow('all', 'read', 'none').required(), management: managementSchema, catalogue: catalogueSchema, + alerting: Joi.object({ + all: alertingSchema, + read: alertingSchema, + }), api: Joi.array().items(Joi.string()), app: Joi.array().items(Joi.string()), savedObject: Joi.object({ @@ -82,6 +91,7 @@ const schema = Joi.object({ app: Joi.array().items(Joi.string()).required(), management: managementSchema, catalogue: catalogueSchema, + alerting: alertingSchema, privileges: Joi.object({ all: privilegeSchema, read: privilegeSchema, @@ -113,7 +123,7 @@ export function validateFeature(feature: FeatureConfig) { throw validateResult.error; } // the following validation can't be enforced by the Joi schema, since it'd require us looking "up" the object graph for the list of valid value, which they explicitly forbid. - const { app = [], management = {}, catalogue = [] } = feature; + const { app = [], management = {}, catalogue = [], alerting = [] } = feature; const unseenApps = new Set(app); @@ -126,6 +136,8 @@ export function validateFeature(feature: FeatureConfig) { const unseenCatalogue = new Set(catalogue); + const unseenAlertTypes = new Set(alerting); + function validateAppEntry(privilegeId: string, entry: readonly string[] = []) { entry.forEach((privilegeApp) => unseenApps.delete(privilegeApp)); @@ -152,6 +164,23 @@ export function validateFeature(feature: FeatureConfig) { } } + function validateAlertingEntry(privilegeId: string, entry: FeatureKibanaPrivileges['alerting']) { + const all = entry?.all ?? []; + const read = entry?.read ?? []; + + all.forEach((privilegeAlertTypes) => unseenAlertTypes.delete(privilegeAlertTypes)); + read.forEach((privilegeAlertTypes) => unseenAlertTypes.delete(privilegeAlertTypes)); + + const unknownAlertingEntries = difference([...all, ...read], alerting); + if (unknownAlertingEntries.length > 0) { + throw new Error( + `Feature privilege ${ + feature.id + }.${privilegeId} has unknown alerting entries: ${unknownAlertingEntries.join(', ')}` + ); + } + } + function validateManagementEntry( privilegeId: string, managementEntry: Record = {} @@ -212,6 +241,7 @@ export function validateFeature(feature: FeatureConfig) { validateCatalogueEntry(privilegeId, privilegeDefinition.catalogue); validateManagementEntry(privilegeId, privilegeDefinition.management); + validateAlertingEntry(privilegeId, privilegeDefinition.alerting); }); const subFeatureEntries = feature.subFeatures ?? []; @@ -221,6 +251,7 @@ export function validateFeature(feature: FeatureConfig) { validateAppEntry(subFeaturePrivilege.id, subFeaturePrivilege.app); validateCatalogueEntry(subFeaturePrivilege.id, subFeaturePrivilege.catalogue); validateManagementEntry(subFeaturePrivilege.id, subFeaturePrivilege.management); + validateAlertingEntry(subFeaturePrivilege.id, subFeaturePrivilege.alerting); }); }); }); @@ -261,4 +292,14 @@ export function validateFeature(feature: FeatureConfig) { )}` ); } + + if (unseenAlertTypes.size > 0) { + throw new Error( + `Feature ${ + feature.id + } specifies alerting entries which are not granted to any privileges: ${Array.from( + unseenAlertTypes.values() + ).join(',')}` + ); + } } diff --git a/x-pack/plugins/features/server/oss_features.ts b/x-pack/plugins/features/server/oss_features.ts index 8d40f51df5760..9df042b45a32e 100644 --- a/x-pack/plugins/features/server/oss_features.ts +++ b/x-pack/plugins/features/server/oss_features.ts @@ -148,7 +148,7 @@ export const buildOSSFeatures = ({ savedObjectTypes, includeTimelion }: BuildOSS app: ['dashboards', 'kibana'], catalogue: ['dashboard'], savedObject: { - all: ['dashboard', 'url', 'query'], + all: ['dashboard', 'query'], read: [ 'index-pattern', 'search', diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/http_requests.ts b/x-pack/plugins/index_management/__jest__/client_integration/helpers/http_requests.ts index 907c749f8ec0b..12cf7ccac6c59 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/http_requests.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/http_requests.ts @@ -92,6 +92,17 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { ]); }; + const setSimulateTemplateResponse = (response?: HttpResponse, error?: any) => { + const status = error ? error.status || 400 : 200; + const body = error ? JSON.stringify(error.body) : JSON.stringify(response); + + server.respondWith('POST', `${API_BASE_PATH}/index_templates/simulate`, [ + status, + { 'Content-Type': 'application/json' }, + body, + ]); + }; + return { setLoadTemplatesResponse, setLoadIndicesResponse, @@ -102,6 +113,7 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { setLoadTemplateResponse, setCreateTemplateResponse, setUpdateTemplateResponse, + setSimulateTemplateResponse, }; }; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx index ad445f75f047c..e40cdc026210d 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx @@ -14,6 +14,8 @@ import { notificationServiceMock, docLinksServiceMock, } from '../../../../../../src/core/public/mocks'; +import { GlobalFlyout } from '../../../../../../src/plugins/es_ui_shared/public'; + import { AppContextProvider } from '../../../public/application/app_context'; import { httpService } from '../../../public/application/services/http'; import { breadcrumbService } from '../../../public/application/services/breadcrumbs'; @@ -23,9 +25,11 @@ import { ExtensionsService } from '../../../public/services'; import { UiMetricService } from '../../../public/application/services/ui_metric'; import { setUiMetricService } from '../../../public/application/services/api'; import { setExtensionsService } from '../../../public/application/store/selectors'; +import { MappingsEditorProvider } from '../../../public/application/components'; import { init as initHttpRequests } from './http_requests'; const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); +const { GlobalFlyoutProvider } = GlobalFlyout; export const services = { extensionsService: new ExtensionsService(), @@ -62,7 +66,11 @@ export const WithAppDependencies = (Comp: any, overridingDependencies: any = {}) const mergedDependencies = merge({}, appDependencies, overridingDependencies); return ( - + + + + + ); }; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/test_subjects.ts b/x-pack/plugins/index_management/__jest__/client_integration/helpers/test_subjects.ts index 9889ebe16ba1e..ecedf819e6185 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/test_subjects.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/test_subjects.ts @@ -28,6 +28,7 @@ export type TestSubjects = | 'legacyTemplateTable' | 'manageTemplateButton' | 'mappingsTabContent' + | 'previewTabContent' | 'noAliasesCallout' | 'noMappingsCallout' | 'noSettingsCallout' @@ -48,4 +49,5 @@ export type TestSubjects = | 'templateList' | 'templatesTab' | 'templateTable' - | 'viewButton'; + | 'viewButton' + | 'simulateTemplatePreview'; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/home/index_templates_tab.helpers.ts b/x-pack/plugins/index_management/__jest__/client_integration/home/index_templates_tab.helpers.ts index a397419053351..23b40f4cbd3d7 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/home/index_templates_tab.helpers.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/home/index_templates_tab.helpers.ts @@ -40,10 +40,15 @@ const createActions = (testBed: TestBed) => { /** * User Actions */ - const selectDetailsTab = (tab: 'summary' | 'settings' | 'mappings' | 'aliases') => { - const tabs = ['summary', 'settings', 'mappings', 'aliases']; + const selectDetailsTab = async ( + tab: 'summary' | 'settings' | 'mappings' | 'aliases' | 'preview' + ) => { + const tabs = ['summary', 'settings', 'mappings', 'aliases', 'preview']; - testBed.find('templateDetails.tab').at(tabs.indexOf(tab)).simulate('click'); + await act(async () => { + testBed.find('templateDetails.tab').at(tabs.indexOf(tab)).simulate('click'); + }); + testBed.component.update(); }; const clickReloadButton = () => { diff --git a/x-pack/plugins/index_management/__jest__/client_integration/home/index_templates_tab.test.ts b/x-pack/plugins/index_management/__jest__/client_integration/home/index_templates_tab.test.ts index f7ebc0bcf632b..06f57896d4900 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/home/index_templates_tab.test.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/home/index_templates_tab.test.ts @@ -493,7 +493,7 @@ describe('Index Templates tab', () => { }); describe('tabs', () => { - test('should have 4 tabs', async () => { + test('should have 5 tabs', async () => { const template = fixtures.getTemplate({ name: `a${getRandomString()}`, indexPatterns: ['template1Pattern1*', 'template1Pattern2'], @@ -524,35 +524,48 @@ describe('Index Templates tab', () => { const { find, actions, exists } = testBed; httpRequestsMockHelpers.setLoadTemplateResponse(template); + httpRequestsMockHelpers.setSimulateTemplateResponse({ simulateTemplate: 'response' }); await actions.clickTemplateAt(0); - expect(find('templateDetails.tab').length).toBe(4); + expect(find('templateDetails.tab').length).toBe(5); expect(find('templateDetails.tab').map((t) => t.text())).toEqual([ 'Summary', 'Settings', 'Mappings', 'Aliases', + 'Preview', ]); // Summary tab should be initial active tab expect(exists('summaryTab')).toBe(true); // Navigate and verify all tabs - actions.selectDetailsTab('settings'); + await actions.selectDetailsTab('settings'); expect(exists('summaryTab')).toBe(false); expect(exists('settingsTabContent')).toBe(true); - actions.selectDetailsTab('aliases'); + await actions.selectDetailsTab('aliases'); expect(exists('summaryTab')).toBe(false); expect(exists('settingsTabContent')).toBe(false); expect(exists('aliasesTabContent')).toBe(true); - actions.selectDetailsTab('mappings'); + await actions.selectDetailsTab('mappings'); expect(exists('summaryTab')).toBe(false); expect(exists('settingsTabContent')).toBe(false); expect(exists('aliasesTabContent')).toBe(false); expect(exists('mappingsTabContent')).toBe(true); + + await actions.selectDetailsTab('preview'); + expect(exists('summaryTab')).toBe(false); + expect(exists('settingsTabContent')).toBe(false); + expect(exists('aliasesTabContent')).toBe(false); + expect(exists('mappingsTabContent')).toBe(false); + expect(exists('previewTabContent')).toBe(true); + + expect(find('simulateTemplatePreview').text().replace(/\s/g, '')).toEqual( + JSON.stringify({ simulateTemplate: 'response' }) + ); }); test('should show an info callout if data is not present', async () => { @@ -568,17 +581,17 @@ describe('Index Templates tab', () => { await actions.clickTemplateAt(0); - expect(find('templateDetails.tab').length).toBe(4); + expect(find('templateDetails.tab').length).toBe(5); expect(exists('summaryTab')).toBe(true); // Navigate and verify callout message per tab - actions.selectDetailsTab('settings'); + await actions.selectDetailsTab('settings'); expect(exists('noSettingsCallout')).toBe(true); - actions.selectDetailsTab('mappings'); + await actions.selectDetailsTab('mappings'); expect(exists('noMappingsCallout')).toBe(true); - actions.selectDetailsTab('aliases'); + await actions.selectDetailsTab('aliases'); expect(exists('noAliasesCallout')).toBe(true); }); }); diff --git a/x-pack/plugins/index_management/common/constants/index.ts b/x-pack/plugins/index_management/common/constants/index.ts index d1700f0e611c0..11240271503e2 100644 --- a/x-pack/plugins/index_management/common/constants/index.ts +++ b/x-pack/plugins/index_management/common/constants/index.ts @@ -47,7 +47,9 @@ export { UIM_TEMPLATE_DETAIL_PANEL_SETTINGS_TAB, UIM_TEMPLATE_DETAIL_PANEL_MAPPINGS_TAB, UIM_TEMPLATE_DETAIL_PANEL_ALIASES_TAB, + UIM_TEMPLATE_DETAIL_PANEL_PREVIEW_TAB, UIM_TEMPLATE_CREATE, UIM_TEMPLATE_UPDATE, UIM_TEMPLATE_CLONE, + UIM_TEMPLATE_SIMULATE, } from './ui_metric'; diff --git a/x-pack/plugins/index_management/common/constants/ui_metric.ts b/x-pack/plugins/index_management/common/constants/ui_metric.ts index 5fda812c704d1..545555b92f352 100644 --- a/x-pack/plugins/index_management/common/constants/ui_metric.ts +++ b/x-pack/plugins/index_management/common/constants/ui_metric.ts @@ -41,6 +41,8 @@ export const UIM_TEMPLATE_DETAIL_PANEL_SUMMARY_TAB = 'template_details_summary_t export const UIM_TEMPLATE_DETAIL_PANEL_SETTINGS_TAB = 'template_details_settings_tab'; export const UIM_TEMPLATE_DETAIL_PANEL_MAPPINGS_TAB = 'template_details_mappings_tab'; export const UIM_TEMPLATE_DETAIL_PANEL_ALIASES_TAB = 'template_details_aliases_tab'; +export const UIM_TEMPLATE_DETAIL_PANEL_PREVIEW_TAB = 'template_details_preview_tab'; export const UIM_TEMPLATE_CREATE = 'template_create'; export const UIM_TEMPLATE_UPDATE = 'template_update'; export const UIM_TEMPLATE_CLONE = 'template_clone'; +export const UIM_TEMPLATE_SIMULATE = 'template_simulate'; diff --git a/x-pack/plugins/index_management/common/lib/template_serialization.ts b/x-pack/plugins/index_management/common/lib/template_serialization.ts index 069d6ac29fbca..1803d89a40016 100644 --- a/x-pack/plugins/index_management/common/lib/template_serialization.ts +++ b/x-pack/plugins/index_management/common/lib/template_serialization.ts @@ -109,7 +109,7 @@ export function serializeLegacyTemplate(template: TemplateDeserialized): LegacyT version, order, indexPatterns, - template: { settings, aliases, mappings }, + template: { settings, aliases, mappings } = {}, } = template; return { diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/component_template_details.test.ts b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/component_template_details.test.ts index 3d496d68cc66e..a112d73230b82 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/component_template_details.test.ts +++ b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/component_template_details.test.ts @@ -61,11 +61,10 @@ describe('', () => { const { exists, find, actions, component } = testBed; // Verify flyout exists with correct title - expect(exists('componentTemplateDetails')).toBe(true); - expect(find('componentTemplateDetails.title').text()).toBe(COMPONENT_TEMPLATE.name); + expect(find('title').text()).toBe(COMPONENT_TEMPLATE.name); // Verify footer does not display since "actions" prop was not provided - expect(exists('componentTemplateDetails.footer')).toBe(false); + expect(exists('footer')).toBe(false); // Verify tabs exist expect(exists('settingsTab')).toBe(true); @@ -185,7 +184,7 @@ describe('', () => { const { exists, actions, component, find } = testBed; // Verify footer exists - expect(exists('componentTemplateDetails.footer')).toBe(true); + expect(exists('footer')).toBe(true); expect(exists('manageComponentTemplateButton')).toBe(true); // Click manage button and verify actions diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/component_template_details.helpers.ts b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/component_template_details.helpers.ts index 25c2d654fd900..fe81e8dcfe123 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/component_template_details.helpers.ts +++ b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/component_template_details.helpers.ts @@ -6,7 +6,7 @@ import { registerTestBed, TestBed } from '../../../../../../../../../test_utils'; import { WithAppDependencies } from './setup_environment'; -import { ComponentTemplateDetailsFlyout } from '../../../component_template_details'; +import { ComponentTemplateDetailsFlyoutContent } from '../../../component_template_details'; export type ComponentTemplateDetailsTestBed = TestBed & { actions: ReturnType; @@ -44,7 +44,7 @@ const createActions = (testBed: TestBed) = export const setup = (props: any): ComponentTemplateDetailsTestBed => { const setupTestBed = registerTestBed( - WithAppDependencies(ComponentTemplateDetailsFlyout), + WithAppDependencies(ComponentTemplateDetailsFlyoutContent), { memoryRouter: { wrapComponent: false, @@ -65,6 +65,8 @@ export type ComponentTemplateDetailsTestSubjects = | 'componentTemplateDetails' | 'componentTemplateDetails.title' | 'componentTemplateDetails.footer' + | 'title' + | 'footer' | 'summaryTab' | 'mappingsTab' | 'settingsTab' diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx index 7e460d3855cb0..2f7317e3e656b 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx @@ -15,12 +15,15 @@ import { applicationServiceMock, } from '../../../../../../../../../../src/core/public/mocks'; +import { GlobalFlyout } from '../../../../../../../../../../src/plugins/es_ui_shared/public'; +import { MappingsEditorProvider } from '../../../../mappings_editor'; import { ComponentTemplatesProvider } from '../../../component_templates_context'; import { init as initHttpRequests } from './http_requests'; import { API_BASE_PATH } from './constants'; const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); +const { GlobalFlyoutProvider } = GlobalFlyout; const appDependencies = { httpClient: (mockHttpClient as unknown) as HttpSetup, @@ -42,7 +45,11 @@ export const setupEnvironment = () => { }; export const WithAppDependencies = (Comp: any) => (props: any) => ( - - - + + + + + + + ); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/component_template_details.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/component_template_details.tsx index 60f1fff3cc9de..0f5bc64c358b9 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/component_template_details.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/component_template_details.tsx @@ -8,7 +8,6 @@ import React, { useState } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; import { - EuiFlyout, EuiFlyoutHeader, EuiTitle, EuiFlyoutBody, @@ -28,14 +27,19 @@ import { ComponentTemplateTabs, TabType } from './tabs'; import { ManageButton, ManageAction } from './manage_button'; import { attemptToDecodeURI } from '../lib'; -interface Props { +export interface Props { componentTemplateName: string; onClose: () => void; actions?: ManageAction[]; showSummaryCallToAction?: boolean; } -export const ComponentTemplateDetailsFlyout: React.FunctionComponent = ({ +export const defaultFlyoutProps = { + 'data-test-subj': 'componentTemplateDetails', + 'aria-labelledby': 'componentTemplateDetailsFlyoutTitle', +}; + +export const ComponentTemplateDetailsFlyoutContent: React.FunctionComponent = ({ componentTemplateName, onClose, actions, @@ -109,13 +113,7 @@ export const ComponentTemplateDetailsFlyout: React.FunctionComponent = ({ } return ( - + <> @@ -172,6 +170,6 @@ export const ComponentTemplateDetailsFlyout: React.FunctionComponent = ({ )} - + ); }; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/index.ts b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/index.ts index 11aac200a2f14..8687a1f5b89c0 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/index.ts +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/index.ts @@ -4,4 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -export { ComponentTemplateDetailsFlyout } from './component_template_details'; +export { + ComponentTemplateDetailsFlyoutContent, + defaultFlyoutProps, + Props as ComponentTemplateDetailsProps, +} from './component_template_details'; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx index efc8b649ef872..8ba7409a9ac57 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx @@ -4,18 +4,22 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useState, useEffect } from 'react'; +import React, { useState, useEffect, useCallback } from 'react'; import { RouteComponentProps } from 'react-router-dom'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { ScopedHistory } from 'kibana/public'; import { EuiLink, EuiText, EuiSpacer } from '@elastic/eui'; -import { SectionLoading, ComponentTemplateDeserialized } from '../shared_imports'; +import { SectionLoading, ComponentTemplateDeserialized, GlobalFlyout } from '../shared_imports'; import { UIM_COMPONENT_TEMPLATE_LIST_LOAD } from '../constants'; import { attemptToDecodeURI } from '../lib'; import { useComponentTemplatesContext } from '../component_templates_context'; -import { ComponentTemplateDetailsFlyout } from '../component_template_details'; +import { + ComponentTemplateDetailsFlyoutContent, + defaultFlyoutProps, + ComponentTemplateDetailsProps, +} from '../component_template_details'; import { EmptyPrompt } from './empty_prompt'; import { ComponentTable } from './table'; import { LoadError } from './error'; @@ -26,39 +30,112 @@ interface Props { history: RouteComponentProps['history']; } +const { useGlobalFlyout } = GlobalFlyout; + export const ComponentTemplateList: React.FunctionComponent = ({ componentTemplateName, history, }) => { + const { + addContent: addContentToGlobalFlyout, + removeContent: removeContentFromGlobalFlyout, + } = useGlobalFlyout(); const { api, trackMetric, documentation } = useComponentTemplatesContext(); const { data, isLoading, error, sendRequest } = api.useLoadComponentTemplates(); const [componentTemplatesToDelete, setComponentTemplatesToDelete] = useState([]); - const goToComponentTemplateList = () => { + const goToComponentTemplateList = useCallback(() => { return history.push({ pathname: 'component_templates', }); - }; - - const goToEditComponentTemplate = (name: string) => { - return history.push({ - pathname: encodeURI(`edit_component_template/${encodeURIComponent(name)}`), - }); - }; + }, [history]); + + const goToEditComponentTemplate = useCallback( + (name: string) => { + return history.push({ + pathname: encodeURI(`edit_component_template/${encodeURIComponent(name)}`), + }); + }, + [history] + ); - const goToCloneComponentTemplate = (name: string) => { - return history.push({ - pathname: encodeURI(`create_component_template/${encodeURIComponent(name)}`), - }); - }; + const goToCloneComponentTemplate = useCallback( + (name: string) => { + return history.push({ + pathname: encodeURI(`create_component_template/${encodeURIComponent(name)}`), + }); + }, + [history] + ); // Track component loaded useEffect(() => { trackMetric('loaded', UIM_COMPONENT_TEMPLATE_LIST_LOAD); }, [trackMetric]); + useEffect(() => { + if (componentTemplateName) { + const actions = [ + { + name: i18n.translate('xpack.idxMgmt.componentTemplateDetails.editButtonLabel', { + defaultMessage: 'Edit', + }), + icon: 'pencil', + handleActionClick: () => + goToEditComponentTemplate(attemptToDecodeURI(componentTemplateName)), + }, + { + name: i18n.translate('xpack.idxMgmt.componentTemplateDetails.cloneActionLabel', { + defaultMessage: 'Clone', + }), + icon: 'copy', + handleActionClick: () => + goToCloneComponentTemplate(attemptToDecodeURI(componentTemplateName)), + }, + { + name: i18n.translate('xpack.idxMgmt.componentTemplateDetails.deleteButtonLabel', { + defaultMessage: 'Delete', + }), + icon: 'trash', + getIsDisabled: (details: ComponentTemplateDeserialized) => + details._kbnMeta.usedBy.length > 0, + closePopoverOnClick: true, + handleActionClick: () => { + setComponentTemplatesToDelete([attemptToDecodeURI(componentTemplateName)]); + }, + }, + ]; + + // Open the flyout with the Component Template Details content + addContentToGlobalFlyout({ + id: 'componentTemplateDetails', + Component: ComponentTemplateDetailsFlyoutContent, + props: { + onClose: goToComponentTemplateList, + componentTemplateName, + showSummaryCallToAction: true, + actions, + }, + flyoutProps: { ...defaultFlyoutProps, onClose: goToComponentTemplateList }, + }); + } + }, [ + componentTemplateName, + goToComponentTemplateList, + goToEditComponentTemplate, + goToCloneComponentTemplate, + addContentToGlobalFlyout, + history, + ]); + + useEffect(() => { + if (!componentTemplateName) { + removeContentFromGlobalFlyout('componentTemplateDetails'); + } + }, [componentTemplateName, removeContentFromGlobalFlyout]); + let content: React.ReactNode; if (isLoading) { @@ -126,45 +203,6 @@ export const ComponentTemplateList: React.FunctionComponent = ({ componentTemplatesToDelete={componentTemplatesToDelete} /> ) : null} - - {/* details flyout */} - {componentTemplateName && ( - - goToEditComponentTemplate(attemptToDecodeURI(componentTemplateName)), - }, - { - name: i18n.translate('xpack.idxMgmt.componentTemplateDetails.cloneActionLabel', { - defaultMessage: 'Clone', - }), - icon: 'copy', - handleActionClick: () => - goToCloneComponentTemplate(attemptToDecodeURI(componentTemplateName)), - }, - { - name: i18n.translate('xpack.idxMgmt.componentTemplateDetails.deleteButtonLabel', { - defaultMessage: 'Delete', - }), - icon: 'trash', - getIsDisabled: (details: ComponentTemplateDeserialized) => - details._kbnMeta.usedBy.length > 0, - closePopoverOnClick: true, - handleActionClick: () => { - setComponentTemplatesToDelete([attemptToDecodeURI(componentTemplateName)]); - }, - }, - ]} - /> - )}
); }; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.tsx index 8795c08fd2bee..ed570579d4e45 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.tsx @@ -11,8 +11,12 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; import { ComponentTemplateListItem } from '../../../../../common'; -import { SectionError, SectionLoading } from '../shared_imports'; -import { ComponentTemplateDetailsFlyout } from '../component_template_details'; +import { SectionError, SectionLoading, GlobalFlyout } from '../shared_imports'; +import { + ComponentTemplateDetailsFlyoutContent, + defaultFlyoutProps, + ComponentTemplateDetailsProps, +} from '../component_template_details'; import { CreateButtonPopOver } from './components'; import { ComponentTemplates } from './component_templates'; import { ComponentTemplatesSelection } from './component_templates_selection'; @@ -20,10 +24,12 @@ import { useApi } from '../component_templates_context'; import './component_templates_selector.scss'; +const { useGlobalFlyout } = GlobalFlyout; + interface Props { onChange: (components: string[]) => void; onComponentsLoaded: (components: ComponentTemplateListItem[]) => void; - defaultValue: string[]; + defaultValue?: string[]; docUri: string; emptyPrompt?: { text?: string | JSX.Element; @@ -53,6 +59,10 @@ export const ComponentTemplatesSelector = ({ emptyPrompt: { text, showCreateButton } = {}, }: Props) => { const { data: components, isLoading, error } = useApi().useLoadComponentTemplates(); + const { + addContent: addContentToGlobalFlyout, + removeContent: removeContentFromGlobalFlyout, + } = useGlobalFlyout(); const [selectedComponent, setSelectedComponent] = useState(null); const [componentsSelected, setComponentsSelected] = useState([]); const isInitialized = useRef(false); @@ -60,15 +70,20 @@ export const ComponentTemplatesSelector = ({ const hasSelection = Object.keys(componentsSelected).length > 0; const hasComponents = components && components.length > 0 ? true : false; + const closeComponentTemplateDetails = () => { + setSelectedComponent(null); + }; + useEffect(() => { if (components) { if ( + defaultValue && defaultValue.length > 0 && componentsSelected.length === 0 && isInitialized.current === false ) { - // Once the components are loaded we check the ones selected - // from the defaultValue provided + // Once the components are fetched, we check the ones previously selected + // from the prop "defaultValue" passed. const nextComponentsSelected = defaultValue .map((name) => components.find((comp) => comp.name === name)) .filter(Boolean) as ComponentTemplateListItem[]; @@ -88,6 +103,30 @@ export const ComponentTemplatesSelector = ({ } }, [isLoading, error, components, onComponentsLoaded]); + useEffect(() => { + if (selectedComponent) { + // Open the flyout with the Component Template Details content + addContentToGlobalFlyout({ + id: 'componentTemplateDetails', + Component: ComponentTemplateDetailsFlyoutContent, + props: { + onClose: closeComponentTemplateDetails, + componentTemplateName: selectedComponent, + }, + flyoutProps: { ...defaultFlyoutProps, onClose: closeComponentTemplateDetails }, + cleanUpFunc: () => { + setSelectedComponent(null); + }, + }); + } + }, [selectedComponent, addContentToGlobalFlyout]); + + useEffect(() => { + if (!selectedComponent) { + removeContentFromGlobalFlyout('componentTemplateDetails'); + } + }, [selectedComponent, removeContentFromGlobalFlyout]); + const onSelectionReorder = (reorderedComponents: ComponentTemplateListItem[]) => { setComponentsSelected(reorderedComponents); }; @@ -198,30 +237,12 @@ export const ComponentTemplatesSelector = ({ ); - const renderComponentDetails = () => { - if (!selectedComponent) { - return null; - } - - return ( - setSelectedComponent(null)} - componentTemplateName={selectedComponent} - /> - ); - }; - if (isLoading) { return renderLoading(); } else if (error) { return renderError(); } else if (hasComponents) { - return ( - <> - {renderSelector()} - {renderComponentDetails()} - - ); + return renderSelector(); } // No components: render empty prompt @@ -244,6 +265,7 @@ export const ComponentTemplatesSelector = ({

); + return ( { + const [templatePreview, setTemplatePreview] = useState('{}'); + + const updatePreview = useCallback(async () => { + if (!template || Object.keys(template).length === 0) { + return; + } + + const indexTemplate = serializeTemplate(stripEmptyFields(template) as TemplateDeserialized); + + // Until ES fixes a bug on their side we will send a random index pattern to the simulate API. + // Issue: https://github.com/elastic/elasticsearch/issues/59152 + indexTemplate.index_patterns = [uuid.v4()]; + + const { data, error } = await simulateIndexTemplate(indexTemplate); + + if (data) { + // "Overlapping" info is only useful when simulating against an index + // which we don't do here. + delete data.overlapping; + } + + setTemplatePreview(JSON.stringify(data ?? error, null, 2)); + }, [template]); + + useEffect(() => { + updatePreview(); + }, [updatePreview]); + + return templatePreview === '{}' ? null : ( + + {templatePreview} + + ); +}); diff --git a/x-pack/plugins/index_management/public/application/components/index_templates/simulate_template/simulate_template_flyout.tsx b/x-pack/plugins/index_management/public/application/components/index_templates/simulate_template/simulate_template_flyout.tsx new file mode 100644 index 0000000000000..63bfe78546041 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/index_templates/simulate_template/simulate_template_flyout.tsx @@ -0,0 +1,119 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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, useCallback, useEffect, useRef } from 'react'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { + EuiFlyoutHeader, + EuiTitle, + EuiFlyoutBody, + EuiFlyoutFooter, + EuiFlexGroup, + EuiFlexItem, + EuiButton, + EuiButtonEmpty, + EuiTextColor, + EuiText, + EuiSpacer, +} from '@elastic/eui'; + +import { SimulateTemplate } from './simulate_template'; + +export interface Props { + onClose(): void; + getTemplate: () => { [key: string]: any }; +} + +export const defaultFlyoutProps = { + 'data-test-subj': 'simulateTemplateFlyout', + 'aria-labelledby': 'simulateTemplateFlyoutTitle', +}; + +export const SimulateTemplateFlyoutContent = ({ onClose, getTemplate }: Props) => { + const isMounted = useRef(false); + const [heightCodeBlock, setHeightCodeBlock] = useState(0); + const [template, setTemplate] = useState<{ [key: string]: any }>({}); + + useEffect(() => { + setHeightCodeBlock( + document.getElementsByClassName('euiFlyoutBody__overflow')[0].clientHeight - 96 + ); + }, []); + + const updatePreview = useCallback(async () => { + const indexTemplate = await getTemplate(); + setTemplate(indexTemplate); + }, [getTemplate]); + + useEffect(() => { + if (isMounted.current === false) { + updatePreview(); + } + isMounted.current = true; + }, [updatePreview]); + + return ( + <> + + +

+ +

+
+ + + +

+ +

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + ); +}; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/shape_datatype.test.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/shape_datatype.test.tsx index 311cb37d0b47a..64347d19e9b47 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/shape_datatype.test.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/shape_datatype.test.tsx @@ -36,8 +36,6 @@ describe('Mappings editor: shape datatype', () => { test('initial view and default parameters values', async () => { const defaultMappings = { - _meta: {}, - _source: {}, properties: { myField: { type: 'shape', diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/text_datatype.test.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/text_datatype.test.tsx index ed60414d198f1..c03aa4805d27f 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/text_datatype.test.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/text_datatype.test.tsx @@ -47,8 +47,6 @@ describe.skip('Mappings editor: text datatype', () => { test('initial view and default parameters values', async () => { const defaultMappings = { - _meta: {}, - _source: {}, properties: { myField: { type: 'text', diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/edit_field.test.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/edit_field.test.tsx index 4f9d8a960a1a2..c146c7704911f 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/edit_field.test.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/edit_field.test.tsx @@ -65,8 +65,6 @@ describe('Mappings editor: edit field', () => { test('should update form parameters when changing the field datatype', async () => { const defaultMappings = { - _meta: {}, - _source: {}, properties: { userName: { ...defaultTextParameters, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.tsx index 638bbfd925ffb..a6558b28a1273 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.tsx @@ -7,9 +7,11 @@ import React from 'react'; import { act } from 'react-dom/test-utils'; import { ReactWrapper } from 'enzyme'; +import { GlobalFlyout } from '../../../../../../../../../../src/plugins/es_ui_shared/public'; import { registerTestBed, TestBed } from '../../../../../../../../../test_utils'; import { getChildFieldsName } from '../../../lib'; import { MappingsEditor } from '../../../mappings_editor'; +import { MappingsEditorProvider } from '../../../mappings_editor_context'; jest.mock('@elastic/eui', () => { const original = jest.requireActual('@elastic/eui'); @@ -51,6 +53,8 @@ jest.mock('@elastic/eui', () => { }; }); +const { GlobalFlyoutProvider } = GlobalFlyout; + export interface DomFields { [key: string]: { type: string; @@ -247,7 +251,15 @@ const createActions = (testBed: TestBed) => { }; export const setup = (props: any = { onUpdate() {} }): MappingsEditorTestBed => { - const setupTestBed = registerTestBed(MappingsEditor, { + const ComponentToTest = (propsOverride: { [key: string]: any }) => ( + + + + + + ); + + const setupTestBed = registerTestBed(ComponentToTest, { memoryRouter: { wrapComponent: false, }, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx index 86bcc796a88eb..20b2e11855029 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx @@ -7,16 +7,14 @@ import React, { useEffect, useRef } from 'react'; import { EuiSpacer } from '@elastic/eui'; import { useForm, Form, SerializerFunc } from '../../shared_imports'; -import { GenericObject } from '../../types'; -import { Types, useDispatch } from '../../mappings_state'; +import { GenericObject, MappingsConfiguration } from '../../types'; +import { useDispatch } from '../../mappings_state_context'; import { DynamicMappingSection } from './dynamic_mapping_section'; import { SourceFieldSection } from './source_field_section'; import { MetaFieldSection } from './meta_field_section'; import { RoutingSection } from './routing_section'; import { configurationFormSchema } from './configuration_form_schema'; -type MappingsConfiguration = Types['MappingsConfiguration']; - interface Props { value?: MappingsConfiguration; } diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form_schema.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form_schema.tsx index 6e80f8b813ec2..8742dfc916924 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form_schema.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form_schema.tsx @@ -11,8 +11,7 @@ import { EuiLink, EuiCode } from '@elastic/eui'; import { documentationService } from '../../../../services/documentation'; import { FormSchema, FIELD_TYPES, VALIDATION_TYPES, fieldValidators } from '../../shared_imports'; -import { MappingsConfiguration } from '../../reducer'; -import { ComboBoxOption } from '../../types'; +import { ComboBoxOption, MappingsConfiguration } from '../../types'; const { containsCharsField, isJsonField } = fieldValidators; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields.tsx index 400de4052afa4..4b19b6f7ae5c3 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields.tsx @@ -6,7 +6,7 @@ import React, { useMemo, useCallback } from 'react'; import { EuiSpacer } from '@elastic/eui'; -import { useMappingsState, useDispatch } from '../../mappings_state'; +import { useMappingsState, useDispatch } from '../../mappings_state_context'; import { deNormalize } from '../../lib'; import { EditFieldContainer } from './fields'; import { DocumentFieldsHeader } from './document_fields_header'; @@ -18,7 +18,7 @@ export const DocumentFields = React.memo(() => { const { fields, search, documentFields } = useMappingsState(); const dispatch = useDispatch(); - const { status, fieldToEdit, editor: editorType } = documentFields; + const { editor: editorType } = documentFields; const jsonEditorDefaultValue = useMemo(() => { if (editorType === 'json') { @@ -33,14 +33,6 @@ export const DocumentFields = React.memo(() => { ); - const renderEditField = () => { - if (status !== 'editingField') { - return null; - } - const field = fields.byId[fieldToEdit!]; - return ; - }; - const onSearchChange = useCallback( (value: string) => { dispatch({ type: 'search:update', value }); @@ -59,7 +51,7 @@ export const DocumentFields = React.memo(() => { ) : ( editor )} - {renderEditField()} +
); }); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/editor_toggle_controls.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/editor_toggle_controls.tsx index 51f9ca63be403..ad283a3fe47bd 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/editor_toggle_controls.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/editor_toggle_controls.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { EuiButton, EuiText } from '@elastic/eui'; -import { useDispatch, useMappingsState } from '../../mappings_state'; +import { useDispatch, useMappingsState } from '../../mappings_state_context'; import { FieldsEditor } from '../../types'; import { canUseMappingsEditor, normalize } from '../../lib'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/name_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/name_parameter.tsx index 01cca7e249a23..0320f2ff51da3 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/name_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/name_parameter.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { TextField, UseField, FieldConfig } from '../../../shared_imports'; import { validateUniqueName } from '../../../lib'; import { PARAMETERS_DEFINITION } from '../../../constants'; -import { useMappingsState } from '../../../mappings_state'; +import { useMappingsState } from '../../../mappings_state_context'; export const NameParameter = () => { const { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/type_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/type_parameter.tsx index 46e70bf8e56ba..31ae37c82a43e 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/type_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/type_parameter.tsx @@ -70,7 +70,13 @@ export const TypeParameter = ({ isMultiField, isRootLevelField, showDocLink = fa : filterTypesForNonRootFields(FIELD_TYPES_OPTIONS) } selectedOptions={typeField.value} - onChange={typeField.setValue} + onChange={(value) => { + if (value.length === 0) { + // Don't allow clearing the type. One must always be selected + return; + } + typeField.setValue(value); + }} isClearable={false} data-test-subj="fieldType" /> diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/create_field/create_field.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/create_field/create_field.tsx index 57a765c38dd26..dc631b7dbf32d 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/create_field/create_field.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/create_field/create_field.tsx @@ -18,7 +18,7 @@ import { import { useForm, Form, FormDataProvider } from '../../../../shared_imports'; import { EUI_SIZE } from '../../../../constants'; -import { useDispatch } from '../../../../mappings_state'; +import { useDispatch } from '../../../../mappings_state_context'; import { fieldSerializer } from '../../../../lib'; import { Field, NormalizedFields } from '../../../../types'; import { NameParameter, TypeParameter, SubTypeParameter } from '../../field_parameters'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/delete_field_provider.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/delete_field_provider.tsx index 80e3e9bec605a..2a98b5948e5a9 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/delete_field_provider.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/delete_field_provider.tsx @@ -7,7 +7,7 @@ import React, { useState } from 'react'; import { i18n } from '@kbn/i18n'; -import { useMappingsState, useDispatch } from '../../../mappings_state'; +import { useMappingsState, useDispatch } from '../../../mappings_state_context'; import { NormalizedField } from '../../../types'; import { getAllDescendantAliases } from '../../../lib'; import { ModalConfirmationDeleteFields } from './modal_confirmation_delete_fields'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field.tsx index e8e41955a5e80..e6950ccfe253e 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field.tsx @@ -6,7 +6,6 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; import { - EuiFlyout, EuiFlyoutHeader, EuiFlyoutBody, EuiFlyoutFooter, @@ -25,7 +24,7 @@ import { TYPE_DEFINITION } from '../../../../constants'; import { Field, NormalizedField, NormalizedFields, MainType, SubType } from '../../../../types'; import { CodeBlock } from '../../../code_block'; import { getParametersFormForType } from '../field_types'; -import { UpdateFieldProvider, UpdateFieldFunc } from './update_field_provider'; +import { UpdateFieldFunc } from './use_update_field'; import { EditFieldHeaderForm } from './edit_field_header_form'; const limitStringLength = (text: string, limit = 18): string => { @@ -36,19 +35,28 @@ const limitStringLength = (text: string, limit = 18): string => { return `...${text.substr(limit * -1)}`; }; -interface Props { +export interface Props { form: FormHook; field: NormalizedField; allFields: NormalizedFields['byId']; exitEdit(): void; + updateField: UpdateFieldFunc; } -export const EditField = React.memo(({ form, field, allFields, exitEdit }: Props) => { - const getSubmitForm = (updateField: UpdateFieldFunc) => async (e?: React.FormEvent) => { - if (e) { - e.preventDefault(); - } +export const defaultFlyoutProps = { + 'data-test-subj': 'mappingsEditorFieldEdit', + 'aria-labelledby': 'mappingsEditorFieldEditTitle', + className: 'mappingsEditor__editField', + maxWidth: 720, +}; + +// The default FormWrapper is the , which wrapps the form with +// a
. We can't have a div as first child of the Flyout as it breaks +// the height calculaction and does not render the footer position correctly. +const FormWrapper: React.FC = ({ children }) => <>{children}; +export const EditField = React.memo(({ form, field, allFields, exitEdit, updateField }: Props) => { + const submitForm = async () => { const { isValid, data } = await form.submit(); if (isValid) { @@ -56,174 +64,152 @@ export const EditField = React.memo(({ form, field, allFields, exitEdit }: Props } }; - const cancel = () => { - exitEdit(); - }; - const { isMultiField } = field; return ( - - {(updateField) => ( -
- - - - - {/* We need an extra div to get out of flex grow */} -
- {/* Title */} - -

- {isMultiField - ? i18n.translate('xpack.idxMgmt.mappingsEditor.editMultiFieldTitle', { - defaultMessage: "Edit multi-field '{fieldName}'", - values: { - fieldName: limitStringLength(field.source.name), - }, - }) - : i18n.translate('xpack.idxMgmt.mappingsEditor.editFieldTitle', { - defaultMessage: "Edit field '{fieldName}'", - values: { - fieldName: limitStringLength(field.source.name), - }, - })} -

-
-
-
- - {/* Documentation link */} - - {({ type, subType }) => { - const linkDocumentation = - documentationService.getTypeDocLink(subType) || - documentationService.getTypeDocLink(type); - - if (!linkDocumentation) { - return null; - } - - const typeDefinition = TYPE_DEFINITION[type as MainType]; - const subTypeDefinition = TYPE_DEFINITION[subType as SubType]; - - return ( - - - {i18n.translate( - 'xpack.idxMgmt.mappingsEditor.editField.typeDocumentation', - { - defaultMessage: '{type} documentation', - values: { - type: subTypeDefinition - ? subTypeDefinition.label - : typeDefinition.label, - }, - } - )} - - - ); - }} - -
- - {/* Field path */} - - - {field.path.join(' > ')} - - -
- - - - - - {({ type, subType }) => { - const ParametersForm = getParametersFormForType(type, subType); - - if (!ParametersForm) { - return null; - } - - return ( - - ); - }} - - - - - {form.isSubmitted && !form.isValid && ( - <> - - - - )} - - + + + + + {/* We need an extra div to get out of flex grow */} +
+ {/* Title */} + +

+ {isMultiField + ? i18n.translate('xpack.idxMgmt.mappingsEditor.editMultiFieldTitle', { + defaultMessage: "Edit multi-field '{fieldName}'", + values: { + fieldName: limitStringLength(field.source.name), + }, + }) + : i18n.translate('xpack.idxMgmt.mappingsEditor.editFieldTitle', { + defaultMessage: "Edit field '{fieldName}'", + values: { + fieldName: limitStringLength(field.source.name), + }, + })} +

+
+
+
+ + {/* Documentation link */} + + {({ type, subType }) => { + const linkDocumentation = + documentationService.getTypeDocLink(subType) || + documentationService.getTypeDocLink(type); + + if (!linkDocumentation) { + return null; + } + + const typeDefinition = TYPE_DEFINITION[type as MainType]; + const subTypeDefinition = TYPE_DEFINITION[subType as SubType]; + + return ( - - {i18n.translate('xpack.idxMgmt.mappingsEditor.editFieldCancelButtonLabel', { - defaultMessage: 'Cancel', - })} - - - - - {i18n.translate('xpack.idxMgmt.mappingsEditor.editFieldUpdateButtonLabel', { - defaultMessage: 'Update', + {i18n.translate('xpack.idxMgmt.mappingsEditor.editField.typeDocumentation', { + defaultMessage: '{type} documentation', + values: { + type: subTypeDefinition ? subTypeDefinition.label : typeDefinition.label, + }, })} - + -
-
-
-
- )} -
+ ); + }} + + + + {/* Field path */} + + + {field.path.join(' > ')} + + + + + + + + + {({ type, subType }) => { + const ParametersForm = getParametersFormForType(type, subType); + + if (!ParametersForm) { + return null; + } + + return ( + + ); + }} + + + + + {form.isSubmitted && !form.isValid && ( + <> + + + + )} + + + + + {i18n.translate('xpack.idxMgmt.mappingsEditor.editFieldCancelButtonLabel', { + defaultMessage: 'Cancel', + })} + + + + + {i18n.translate('xpack.idxMgmt.mappingsEditor.editFieldUpdateButtonLabel', { + defaultMessage: 'Update', + })} + + + + + ); }); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_container.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_container.tsx index 5105a2a157a6d..4996f59105c04 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_container.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_container.tsx @@ -3,24 +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, { useEffect, useCallback } from 'react'; +import React, { useEffect, useCallback, useMemo } from 'react'; -import { useForm } from '../../../../shared_imports'; -import { useDispatch } from '../../../../mappings_state'; -import { Field, NormalizedField, NormalizedFields } from '../../../../types'; +import { useForm, GlobalFlyout } from '../../../../shared_imports'; +import { useDispatch, useMappingsState } from '../../../../mappings_state_context'; +import { Field } from '../../../../types'; import { fieldSerializer, fieldDeserializer } from '../../../../lib'; -import { EditField } from './edit_field'; +import { ModalConfirmationDeleteFields } from '../modal_confirmation_delete_fields'; +import { EditField, defaultFlyoutProps, Props as EditFieldProps } from './edit_field'; +import { useUpdateField } from './use_update_field'; -interface Props { - field: NormalizedField; - allFields: NormalizedFields['byId']; -} +const { useGlobalFlyout } = GlobalFlyout; -export const EditFieldContainer = React.memo(({ field, allFields }: Props) => { +export const EditFieldContainer = React.memo(() => { + const { fields, documentFields } = useMappingsState(); const dispatch = useDispatch(); + const { + addContent: addContentToGlobalFlyout, + removeContent: removeContentFromGlobalFlyout, + } = useGlobalFlyout(); + const { updateField, modal } = useUpdateField(); + + const { status, fieldToEdit } = documentFields; + const isEditing = status === 'editingField'; + + const field = isEditing ? fields.byId[fieldToEdit!] : undefined; + + const formDefaultValue = useMemo(() => { + return { ...field?.source }; + }, [field?.source]); const { form } = useForm({ - defaultValue: { ...field.source }, + defaultValue: formDefaultValue, serializer: fieldSerializer, deserializer: fieldDeserializer, options: { stripEmptyFields: false }, @@ -40,5 +54,48 @@ export const EditFieldContainer = React.memo(({ field, allFields }: Props) => { dispatch({ type: 'documentField.changeStatus', value: 'idle' }); }, [dispatch]); - return ; + useEffect(() => { + if (isEditing) { + // Open the flyout with the content + addContentToGlobalFlyout({ + id: 'mappingsEditField', + Component: EditField, + props: { + form, + field: field!, + exitEdit, + allFields: fields.byId, + updateField, + }, + flyoutProps: { ...defaultFlyoutProps, onClose: exitEdit }, + cleanUpFunc: exitEdit, + }); + } + }, [ + isEditing, + field, + form, + addContentToGlobalFlyout, + fields.byId, + fieldToEdit, + exitEdit, + updateField, + ]); + + useEffect(() => { + if (!isEditing) { + removeContentFromGlobalFlyout('mappingsEditField'); + } + }, [isEditing, removeContentFromGlobalFlyout]); + + useEffect(() => { + return () => { + if (isEditing) { + // When the component unmounts, exit edit mode. + exitEdit(); + } + }; + }, [isEditing, exitEdit]); + + return modal.isOpen ? : null; }); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/update_field_provider.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/update_field_provider.tsx deleted file mode 100644 index e31d12689e7e0..0000000000000 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/update_field_provider.tsx +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { useState } from 'react'; -import { i18n } from '@kbn/i18n'; - -import { useMappingsState, useDispatch } from '../../../../mappings_state'; -import { shouldDeleteChildFieldsAfterTypeChange, getAllDescendantAliases } from '../../../../lib'; -import { NormalizedField, DataType } from '../../../../types'; -import { PARAMETERS_DEFINITION } from '../../../../constants'; -import { ModalConfirmationDeleteFields } from '../modal_confirmation_delete_fields'; - -export type UpdateFieldFunc = (field: NormalizedField) => void; - -interface Props { - children: (saveProperty: UpdateFieldFunc) => React.ReactNode; -} - -interface State { - isModalOpen: boolean; - field?: NormalizedField; - aliases?: string[]; -} - -export const UpdateFieldProvider = ({ children }: Props) => { - const [state, setState] = useState({ - isModalOpen: false, - }); - const dispatch = useDispatch(); - - const { fields } = useMappingsState(); - const { byId, aliases } = fields; - - const confirmButtonText = i18n.translate( - 'xpack.idxMgmt.mappingsEditor.updateField.confirmationModal.confirmDescription', - { - defaultMessage: 'Confirm type change', - } - ); - - let modalTitle: string | undefined; - - if (state.field) { - const { source } = state.field; - - modalTitle = i18n.translate( - 'xpack.idxMgmt.mappingsEditor.updateField.confirmationModal.title', - { - defaultMessage: "Confirm change '{fieldName}' type to '{fieldType}'.", - values: { - fieldName: source.name, - fieldType: source.type, - }, - } - ); - } - - const closeModal = () => { - setState({ isModalOpen: false }); - }; - - const updateField: UpdateFieldFunc = (field) => { - const previousField = byId[field.id]; - - const willDeleteChildFields = (oldType: DataType, newType: DataType): boolean => { - const { hasChildFields, hasMultiFields } = field; - - if (!hasChildFields && !hasMultiFields) { - // No child or multi-fields will be deleted, no confirmation needed. - return false; - } - - return shouldDeleteChildFieldsAfterTypeChange(oldType, newType); - }; - - if (field.source.type !== previousField.source.type) { - // Array of all the aliases pointing to the current field beeing updated - const aliasesOnField = aliases[field.id] || []; - - // Array of all the aliases pointing to the current field + all its possible children - const aliasesOnFieldAndDescendants = getAllDescendantAliases(field, fields); - - const isReferencedByAlias = aliasesOnField && Boolean(aliasesOnField.length); - const nextTypeCanHaveAlias = !PARAMETERS_DEFINITION.path.targetTypesNotAllowed.includes( - field.source.type - ); - - // We need to check if, by changing the type, we will also - // delete possible child properties ("fields" or "properties"). - // If we will, we need to warn the user about it. - let requiresConfirmation: boolean; - let aliasesToDelete: string[] = []; - - if (isReferencedByAlias && !nextTypeCanHaveAlias) { - aliasesToDelete = aliasesOnFieldAndDescendants; - requiresConfirmation = true; - } else { - requiresConfirmation = willDeleteChildFields(previousField.source.type, field.source.type); - if (requiresConfirmation) { - aliasesToDelete = aliasesOnFieldAndDescendants.filter( - // We will only delete aliases that points to possible children, *NOT* the field itself - (id) => aliasesOnField.includes(id) === false - ); - } - } - - if (requiresConfirmation) { - setState({ - isModalOpen: true, - field, - aliases: Boolean(aliasesToDelete.length) - ? aliasesToDelete.map((id) => byId[id].path.join(' > ')).sort() - : undefined, - }); - return; - } - } - - dispatch({ type: 'field.edit', value: field.source }); - }; - - const confirmTypeUpdate = () => { - dispatch({ type: 'field.edit', value: state.field!.source }); - closeModal(); - }; - - return ( - <> - {children(updateField)} - - {state.isModalOpen && ( - - )} - - ); -}; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/use_update_field.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/use_update_field.ts new file mode 100644 index 0000000000000..ed659cd05b060 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/use_update_field.ts @@ -0,0 +1,146 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { useState, useCallback } from 'react'; +import { i18n } from '@kbn/i18n'; + +import { useMappingsState, useDispatch } from '../../../../mappings_state_context'; +import { shouldDeleteChildFieldsAfterTypeChange, getAllDescendantAliases } from '../../../../lib'; +import { NormalizedField, DataType } from '../../../../types'; +import { PARAMETERS_DEFINITION } from '../../../../constants'; + +export type UpdateFieldFunc = (field: NormalizedField) => void; + +interface State { + isModalOpen: boolean; + field?: NormalizedField; + aliases?: string[]; +} + +export const useUpdateField = () => { + const [state, setState] = useState({ + isModalOpen: false, + }); + const dispatch = useDispatch(); + + const { fields } = useMappingsState(); + const { byId, aliases } = fields; + + const confirmButtonText = i18n.translate( + 'xpack.idxMgmt.mappingsEditor.updateField.confirmationModal.confirmDescription', + { + defaultMessage: 'Confirm type change', + } + ); + + let modalTitle = ''; + + if (state.field) { + const { source } = state.field; + + modalTitle = i18n.translate( + 'xpack.idxMgmt.mappingsEditor.updateField.confirmationModal.title', + { + defaultMessage: "Confirm change '{fieldName}' type to '{fieldType}'.", + values: { + fieldName: source.name, + fieldType: source.type, + }, + } + ); + } + + const closeModal = () => { + setState({ isModalOpen: false }); + }; + + const updateField: UpdateFieldFunc = useCallback( + (field) => { + const previousField = byId[field.id]; + + const willDeleteChildFields = (oldType: DataType, newType: DataType): boolean => { + const { hasChildFields, hasMultiFields } = field; + + if (!hasChildFields && !hasMultiFields) { + // No child or multi-fields will be deleted, no confirmation needed. + return false; + } + + return shouldDeleteChildFieldsAfterTypeChange(oldType, newType); + }; + + if (field.source.type !== previousField.source.type) { + // Array of all the aliases pointing to the current field beeing updated + const aliasesOnField = aliases[field.id] || []; + + // Array of all the aliases pointing to the current field + all its possible children + const aliasesOnFieldAndDescendants = getAllDescendantAliases(field, fields); + + const isReferencedByAlias = aliasesOnField && Boolean(aliasesOnField.length); + const nextTypeCanHaveAlias = !PARAMETERS_DEFINITION.path.targetTypesNotAllowed.includes( + field.source.type + ); + + // We need to check if, by changing the type, we will also + // delete possible child properties ("fields" or "properties"). + // If we will, we need to warn the user about it. + let requiresConfirmation: boolean; + let aliasesToDelete: string[] = []; + + if (isReferencedByAlias && !nextTypeCanHaveAlias) { + aliasesToDelete = aliasesOnFieldAndDescendants; + requiresConfirmation = true; + } else { + requiresConfirmation = willDeleteChildFields( + previousField.source.type, + field.source.type + ); + if (requiresConfirmation) { + aliasesToDelete = aliasesOnFieldAndDescendants.filter( + // We will only delete aliases that points to possible children, *NOT* the field itself + (id) => aliasesOnField.includes(id) === false + ); + } + } + + if (requiresConfirmation) { + setState({ + isModalOpen: true, + field, + aliases: Boolean(aliasesToDelete.length) + ? aliasesToDelete.map((id) => byId[id].path.join(' > ')).sort() + : undefined, + }); + return; + } + } + + dispatch({ type: 'field.edit', value: field.source }); + }, + [dispatch, aliases, fields, byId] + ); + + const confirmTypeUpdate = () => { + dispatch({ type: 'field.edit', value: state.field!.source }); + closeModal(); + }; + + return { + updateField, + modal: { + isOpen: state.isModalOpen, + props: { + childFields: state.field && state.field.childFields, + title: modalTitle, + aliases: state.aliases, + byId, + confirmButtonText, + onConfirm: confirmTypeUpdate, + onCancel: closeModal, + }, + }, + }; +}; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/fields_list_item_container.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/fields_list_item_container.tsx index 55093e606cfa1..7d9ad3bc6aaec 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/fields_list_item_container.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/fields_list_item_container.tsx @@ -5,7 +5,7 @@ */ import React, { useMemo, useCallback, useRef } from 'react'; -import { useMappingsState, useDispatch } from '../../../mappings_state'; +import { useMappingsState, useDispatch } from '../../../mappings_state_context'; import { NormalizedField } from '../../../types'; import { FieldsListItem } from './fields_list_item'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields_json_editor.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields_json_editor.tsx index 5954f6f285f10..d750c0e604c5e 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields_json_editor.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields_json_editor.tsx @@ -6,7 +6,7 @@ import React, { useRef, useCallback } from 'react'; -import { useDispatch } from '../../mappings_state'; +import { useDispatch } from '../../mappings_state_context'; import { JsonEditor } from '../../shared_imports'; export interface Props { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields_tree_editor.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields_tree_editor.tsx index 9d9df38ef4e25..7a0b72ae647d5 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields_tree_editor.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields_tree_editor.tsx @@ -8,7 +8,7 @@ import React, { useMemo, useCallback } from 'react'; import { EuiButtonEmpty, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { useMappingsState, useDispatch } from '../../mappings_state'; +import { useMappingsState, useDispatch } from '../../mappings_state_context'; import { FieldsList, CreateField } from './fields'; export const DocumentFieldsTreeEditor = () => { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result.tsx index 9077781b7fb43..f3602a800eeeb 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result.tsx @@ -8,9 +8,8 @@ import VirtualList from 'react-tiny-virtual-list'; import { EuiEmptyPrompt, EuiButton } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { SearchResult as SearchResultType } from '../../../types'; -import { useDispatch } from '../../../mappings_state'; -import { State } from '../../../reducer'; +import { SearchResult as SearchResultType, State } from '../../../types'; +import { useDispatch } from '../../../mappings_state_context'; import { SearchResultItem } from './search_result_item'; interface Props { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result_item.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result_item.tsx index ab8b90b6be3b5..73d3e078f6ff3 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result_item.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result_item.tsx @@ -10,7 +10,7 @@ import { i18n } from '@kbn/i18n'; import { SearchResult } from '../../../types'; import { TYPE_DEFINITION } from '../../../constants'; -import { useDispatch } from '../../../mappings_state'; +import { useDispatch } from '../../../mappings_state_context'; import { getTypeLabelFromType } from '../../../lib'; import { DeleteFieldProvider } from '../fields/delete_field_provider'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/index.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/index.ts index 34c410f06e520..dc7f20f4d026b 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/index.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/index.ts @@ -4,5 +4,5 @@ * you may not use this file except in compliance with the Elastic License. */ -export * from './load_from_json_button'; -export * from './load_mappings_provider'; +export { LoadMappingsFromJsonButton } from './load_from_json_button'; +export { LoadMappingsProvider } from './load_mappings_provider'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx index a95579a8a141e..44a809a7a01bf 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx @@ -9,12 +9,11 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { EuiText, EuiLink, EuiSpacer } from '@elastic/eui'; import { useForm, Form, SerializerFunc, UseField, JsonEditorField } from '../../shared_imports'; -import { Types, useDispatch } from '../../mappings_state'; +import { MappingsTemplates } from '../../types'; +import { useDispatch } from '../../mappings_state_context'; import { templatesFormSchema } from './templates_form_schema'; import { documentationService } from '../../../../services/documentation'; -type MappingsTemplates = Types['MappingsTemplates']; - interface Props { value?: MappingsTemplates; } diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form_schema.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form_schema.ts index 667b5685723d2..daca85f95b0b9 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form_schema.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form_schema.ts @@ -7,7 +7,7 @@ import { i18n } from '@kbn/i18n'; import { FormSchema, fieldValidators } from '../../shared_imports'; -import { MappingsTemplates } from '../../reducer'; +import { MappingsTemplates } from '../../types'; const { isJsonField } = fieldValidators; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/index.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/index.ts index 29cfaf99c6559..00bb41663dd9c 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/index.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/index.ts @@ -4,12 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -export * from './mappings_editor'; +export { MappingsEditor } from './mappings_editor'; // We export both the button & the load mappings provider // to give flexibility to the consumer -export * from './components/load_mappings'; +export { LoadMappingsFromJsonButton, LoadMappingsProvider } from './components/load_mappings'; -export { OnUpdateHandler, Types } from './mappings_state'; +export { MappingsEditorProvider } from './mappings_editor_context'; -export { IndexSettings } from './types'; +export { IndexSettings, OnUpdateHandler } from './types'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/index_settings_context.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/index_settings_context.tsx index 9e3637f970293..411193f10b24a 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/index_settings_context.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/index_settings_context.tsx @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import React, { createContext, useContext } from 'react'; + import { IndexSettings } from './types'; const IndexSettingsContext = createContext(undefined); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor.tsx index e8fda90737708..292882f1c5b4b 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor.tsx @@ -14,24 +14,40 @@ import { TemplatesForm, MultipleMappingsWarning, } from './components'; -import { IndexSettings } from './types'; +import { + OnUpdateHandler, + IndexSettings, + Field, + Mappings, + MappingsConfiguration, + MappingsTemplates, +} from './types'; import { extractMappingsDefinition } from './lib'; -import { State } from './reducer'; -import { MappingsState, Props as MappingsStateProps, Types } from './mappings_state'; +import { useMappingsState } from './mappings_state_context'; +import { useMappingsStateListener } from './use_state_listener'; import { IndexSettingsProvider } from './index_settings_context'; +type TabName = 'fields' | 'advanced' | 'templates'; + +interface MappingsEditorParsedMetadata { + parsedDefaultValue?: { + configuration: MappingsConfiguration; + fields: { [key: string]: Field }; + templates: MappingsTemplates; + }; + multipleMappingsDeclared: boolean; +} + interface Props { - onChange: MappingsStateProps['onChange']; + onChange: OnUpdateHandler; value?: { [key: string]: any }; indexSettings?: IndexSettings; } -type TabName = 'fields' | 'advanced' | 'templates'; - export const MappingsEditor = React.memo(({ onChange, value, indexSettings }: Props) => { - const [selectedTab, selectTab] = useState('fields'); - - const { parsedDefaultValue, multipleMappingsDeclared } = useMemo(() => { + const { parsedDefaultValue, multipleMappingsDeclared } = useMemo< + MappingsEditorParsedMetadata + >(() => { const mappingsDefinition = extractMappingsDefinition(value); if (mappingsDefinition === null) { @@ -69,18 +85,28 @@ export const MappingsEditor = React.memo(({ onChange, value, indexSettings }: Pr return { parsedDefaultValue: parsed, multipleMappingsDeclared: false }; }, [value]); + /** + * Hook that will listen to: + * 1. "value" prop changes in order to reset the mappings editor + * 2. "state" changes in order to communicate any updates to the consumer + */ + useMappingsStateListener({ onChange, value: parsedDefaultValue }); + + const state = useMappingsState(); + const [selectedTab, selectTab] = useState('fields'); + useEffect(() => { if (multipleMappingsDeclared) { // We set the data getter here as the user won't be able to make any changes onChange({ - getData: () => value! as Types['Mappings'], + getData: () => value! as Mappings, validate: () => Promise.resolve(true), isValid: true, }); } }, [multipleMappingsDeclared, onChange, value]); - const changeTab = async (tab: TabName, state: State) => { + const changeTab = async (tab: TabName) => { if (selectedTab === 'advanced') { // When we navigate away we need to submit the form to validate if there are any errors. const { isValid: isConfigurationFormValid } = await state.configuration.submitForm!(); @@ -102,59 +128,53 @@ export const MappingsEditor = React.memo(({ onChange, value, indexSettings }: Pr selectTab(tab); }; + const tabToContentMap = { + fields: , + templates: , + advanced: , + }; + return (
{multipleMappingsDeclared ? ( ) : ( - - {({ state }) => { - const tabToContentMap = { - fields: , - templates: , - advanced: , - }; - - return ( -
- - changeTab('fields', state)} - isSelected={selectedTab === 'fields'} - data-test-subj="formTab" - > - {i18n.translate('xpack.idxMgmt.mappingsEditor.fieldsTabLabel', { - defaultMessage: 'Mapped fields', - })} - - changeTab('templates', state)} - isSelected={selectedTab === 'templates'} - data-test-subj="formTab" - > - {i18n.translate('xpack.idxMgmt.mappingsEditor.templatesTabLabel', { - defaultMessage: 'Dynamic templates', - })} - - changeTab('advanced', state)} - isSelected={selectedTab === 'advanced'} - data-test-subj="formTab" - > - {i18n.translate('xpack.idxMgmt.mappingsEditor.advancedTabLabel', { - defaultMessage: 'Advanced options', - })} - - - - - - {tabToContentMap[selectedTab]} -
- ); - }} -
+
+ + changeTab('fields')} + isSelected={selectedTab === 'fields'} + data-test-subj="formTab" + > + {i18n.translate('xpack.idxMgmt.mappingsEditor.fieldsTabLabel', { + defaultMessage: 'Mapped fields', + })} + + changeTab('templates')} + isSelected={selectedTab === 'templates'} + data-test-subj="formTab" + > + {i18n.translate('xpack.idxMgmt.mappingsEditor.templatesTabLabel', { + defaultMessage: 'Dynamic templates', + })} + + changeTab('advanced')} + isSelected={selectedTab === 'advanced'} + data-test-subj="formTab" + > + {i18n.translate('xpack.idxMgmt.mappingsEditor.advancedTabLabel', { + defaultMessage: 'Advanced options', + })} + + + + + + {tabToContentMap[selectedTab]} +
)}
diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor_context.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor_context.tsx new file mode 100644 index 0000000000000..596b49cc89ee8 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor_context.tsx @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; + +import { StateProvider } from './mappings_state_context'; + +export const MappingsEditorProvider: React.FC = ({ children }) => { + return {children}; +}; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state_context.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state_context.tsx new file mode 100644 index 0000000000000..a402dec250056 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state_context.tsx @@ -0,0 +1,77 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useReducer, createContext, useContext } from 'react'; + +import { reducer } from './reducer'; +import { State, Dispatch } from './types'; + +const StateContext = createContext(undefined); +const DispatchContext = createContext(undefined); + +export const StateProvider: React.FC = ({ children }) => { + const initialState: State = { + isValid: true, + configuration: { + defaultValue: {}, + data: { + raw: {}, + format: () => ({}), + }, + validate: () => Promise.resolve(true), + }, + templates: { + defaultValue: {}, + data: { + raw: {}, + format: () => ({}), + }, + validate: () => Promise.resolve(true), + }, + fields: { + byId: {}, + rootLevelFields: [], + aliases: {}, + maxNestedDepth: 0, + }, + documentFields: { + status: 'idle', + editor: 'default', + }, + fieldsJsonEditor: { + format: () => ({}), + isValid: true, + }, + search: { + term: '', + result: [], + }, + }; + + const [state, dispatch] = useReducer(reducer, initialState); + + return ( + + {children} + + ); +}; + +export const useMappingsState = () => { + const ctx = useContext(StateContext); + if (ctx === undefined) { + throw new Error('useMappingsState must be used within a '); + } + return ctx; +}; + +export const useDispatch = () => { + const ctx = useContext(DispatchContext); + if (ctx === undefined) { + throw new Error('useDispatch must be used within a '); + } + return ctx; +}; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/reducer.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/reducer.ts index 27f8b12493008..18a8270117ea4 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/reducer.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/reducer.ts @@ -3,8 +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 { OnFormUpdateArg, FormHook } from './shared_imports'; -import { Field, NormalizedFields, NormalizedField, FieldsEditor, SearchResult } from './types'; +import { Field, NormalizedFields, NormalizedField, State, Action } from './types'; import { getFieldMeta, getUniqueId, @@ -17,99 +16,6 @@ import { } from './lib'; import { PARAMETERS_DEFINITION } from './constants'; -export interface MappingsConfiguration { - enabled?: boolean; - throwErrorsForUnmappedFields?: boolean; - date_detection: boolean; - numeric_detection: boolean; - dynamic_date_formats: string[]; - _source: { - enabled?: boolean; - includes?: string[]; - excludes?: string[]; - }; - _meta?: string; -} - -export interface MappingsTemplates { - dynamic_templates: DynamicTemplate[]; -} - -interface DynamicTemplate { - [key: string]: { - mapping: { - [key: string]: any; - }; - match_mapping_type?: string; - match?: string; - unmatch?: string; - match_pattern?: string; - path_match?: string; - path_unmatch?: string; - }; -} - -export interface MappingsFields { - [key: string]: any; -} - -type DocumentFieldsStatus = 'idle' | 'editingField' | 'creatingField'; - -interface DocumentFieldsState { - status: DocumentFieldsStatus; - editor: FieldsEditor; - fieldToEdit?: string; - fieldToAddFieldTo?: string; -} - -interface ConfigurationFormState extends OnFormUpdateArg { - defaultValue: MappingsConfiguration; - submitForm?: FormHook['submit']; -} - -interface TemplatesFormState extends OnFormUpdateArg { - defaultValue: MappingsTemplates; - submitForm?: FormHook['submit']; -} - -export interface State { - isValid: boolean | undefined; - configuration: ConfigurationFormState; - documentFields: DocumentFieldsState; - fields: NormalizedFields; - fieldForm?: OnFormUpdateArg; - fieldsJsonEditor: { - format(): MappingsFields; - isValid: boolean; - }; - search: { - term: string; - result: SearchResult[]; - }; - templates: TemplatesFormState; -} - -export type Action = - | { type: 'editor.replaceMappings'; value: { [key: string]: any } } - | { type: 'configuration.update'; value: Partial } - | { type: 'configuration.save'; value: MappingsConfiguration } - | { type: 'templates.update'; value: Partial } - | { type: 'templates.save'; value: MappingsTemplates } - | { type: 'fieldForm.update'; value: OnFormUpdateArg } - | { type: 'field.add'; value: Field } - | { type: 'field.remove'; value: string } - | { type: 'field.edit'; value: Field } - | { type: 'field.toggleExpand'; value: { fieldId: string; isExpanded?: boolean } } - | { type: 'documentField.createField'; value?: string } - | { type: 'documentField.editField'; value: string } - | { type: 'documentField.changeStatus'; value: DocumentFieldsStatus } - | { type: 'documentField.changeEditor'; value: FieldsEditor } - | { type: 'fieldsJsonEditor.update'; value: { json: { [key: string]: any }; isValid: boolean } } - | { type: 'search:update'; value: string } - | { type: 'validity:update'; value: boolean }; - -export type Dispatch = (action: Action) => void; - export const addFieldToState = (field: Field, state: State): State => { const updatedFields = { ...state.fields }; const id = getUniqueId(); @@ -277,7 +183,7 @@ export const reducer = (state: State, action: Action): State => { }, documentFields: { ...state.documentFields, - status: 'idle', + ...action.value.documentFields, fieldToAddFieldTo: undefined, fieldToEdit: undefined, }, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/shared_imports.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/shared_imports.ts index 2979015c07455..097d039527950 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/shared_imports.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/shared_imports.ts @@ -49,4 +49,5 @@ export { export { JsonEditor, OnJsonEditorUpdateHandler, + GlobalFlyout, } from '../../../../../../../src/plugins/es_ui_shared/public'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/types.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/types/document_fields.ts similarity index 65% rename from x-pack/plugins/index_management/public/application/components/mappings_editor/types.ts rename to x-pack/plugins/index_management/public/application/components/mappings_editor/types/document_fields.ts index 5b18af68ed55b..a9f6d2ea03bdf 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/types.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/types/document_fields.ts @@ -3,10 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { ReactNode, OptionHTMLAttributes } from 'react'; +import { ReactNode } from 'react'; -import { FieldConfig } from './shared_imports'; -import { PARAMETERS_DEFINITION } from './constants'; +import { GenericObject } from './mappings_editor'; + +import { FieldConfig } from '../shared_imports'; +import { PARAMETERS_DEFINITION } from '../constants'; export interface DataTypeDefinition { label: string; @@ -203,100 +205,7 @@ export interface NormalizedField extends FieldMeta { export type ChildFieldName = 'properties' | 'fields'; -export type FieldsEditor = 'default' | 'json'; - -export type SelectOption = { - value: unknown; - text: T | ReactNode; -} & OptionHTMLAttributes; - -export interface SuperSelectOption { - value: unknown; - inputDisplay?: ReactNode; - dropdownDisplay?: ReactNode; - disabled?: boolean; - 'data-test-subj'?: string; -} - export interface AliasOption { id: string; label: string; } - -export interface IndexSettingsInterface { - analysis?: { - analyzer: { - [key: string]: { - type: string; - tokenizer: string; - char_filter?: string[]; - filter?: string[]; - position_increment_gap?: number; - }; - }; - }; -} - -/** - * When we define the index settings we can skip - * the "index" property and directly add the "analysis". - * ES always returns the settings wrapped under "index". - */ -export type IndexSettings = IndexSettingsInterface | { index: IndexSettingsInterface }; - -export interface ComboBoxOption { - label: string; - value?: unknown; -} - -export interface SearchResult { - display: JSX.Element; - field: NormalizedField; -} - -export interface SearchMetadata { - /** - * Whether or not the search term match some part of the field path. - */ - matchPath: boolean; - /** - * If the search term matches the field type we will give it a higher score. - */ - matchType: boolean; - /** - * If the last word of the search terms matches the field name - */ - matchFieldName: boolean; - /** - * If the search term matches the beginning of the path we will give it a higher score - */ - matchStartOfPath: boolean; - /** - * If the last word of the search terms fully matches the field name - */ - fullyMatchFieldName: boolean; - /** - * If the search term exactly matches the field type - */ - fullyMatchType: boolean; - /** - * If the search term matches the full field path - */ - fullyMatchPath: boolean; - /** - * The score of the result that will allow us to sort the list - */ - score: number; - /** - * The JSX with tag wrapping the matched string - */ - display: JSX.Element; - /** - * The field path substring that matches the search - */ - stringMatch: string | null; -} - -export interface GenericObject { - [key: string]: any; -} diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/types/index.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/types/index.ts new file mode 100644 index 0000000000000..cce2d550a68c1 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/types/index.ts @@ -0,0 +1,11 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export * from './mappings_editor'; + +export * from './document_fields'; + +export * from './state'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/types/mappings_editor.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/types/mappings_editor.ts new file mode 100644 index 0000000000000..1ca944024ae2b --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/types/mappings_editor.ts @@ -0,0 +1,110 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { ReactNode, OptionHTMLAttributes } from 'react'; + +import { NormalizedField } from './document_fields'; +import { Mappings } from './state'; + +export type OnUpdateHandler = (arg: OnUpdateHandlerArg) => void; + +export interface OnUpdateHandlerArg { + isValid?: boolean; + getData: () => Mappings | undefined; + validate: () => Promise; +} + +export type FieldsEditor = 'default' | 'json'; + +export interface IndexSettingsInterface { + analysis?: { + analyzer: { + [key: string]: { + type: string; + tokenizer: string; + char_filter?: string[]; + filter?: string[]; + position_increment_gap?: number; + }; + }; + }; +} + +/** + * When we define the index settings we can skip + * the "index" property and directly add the "analysis". + * ES always returns the settings wrapped under "index". + */ +export type IndexSettings = IndexSettingsInterface | { index: IndexSettingsInterface }; + +export type SelectOption = { + value: unknown; + text: T | ReactNode; +} & OptionHTMLAttributes; + +export interface ComboBoxOption { + label: string; + value?: unknown; +} + +export interface SuperSelectOption { + value: unknown; + inputDisplay?: ReactNode; + dropdownDisplay?: ReactNode; + disabled?: boolean; + 'data-test-subj'?: string; +} + +export interface SearchResult { + display: JSX.Element; + field: NormalizedField; +} + +export interface SearchMetadata { + /** + * Whether or not the search term match some part of the field path. + */ + matchPath: boolean; + /** + * If the search term matches the field type we will give it a higher score. + */ + matchType: boolean; + /** + * If the last word of the search terms matches the field name + */ + matchFieldName: boolean; + /** + * If the search term matches the beginning of the path we will give it a higher score + */ + matchStartOfPath: boolean; + /** + * If the last word of the search terms fully matches the field name + */ + fullyMatchFieldName: boolean; + /** + * If the search term exactly matches the field type + */ + fullyMatchType: boolean; + /** + * If the search term matches the full field path + */ + fullyMatchPath: boolean; + /** + * The score of the result that will allow us to sort the list + */ + score: number; + /** + * The JSX with tag wrapping the matched string + */ + display: JSX.Element; + /** + * The field path substring that matches the search + */ + stringMatch: string | null; +} + +export interface GenericObject { + [key: string]: any; +} diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/types/state.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/types/state.ts new file mode 100644 index 0000000000000..34df70374aa88 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/types/state.ts @@ -0,0 +1,107 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { FormHook, OnFormUpdateArg } from '../shared_imports'; +import { Field, NormalizedFields } from './document_fields'; +import { FieldsEditor, SearchResult } from './mappings_editor'; + +export type Mappings = MappingsTemplates & + MappingsConfiguration & { + properties?: MappingsFields; + }; + +export interface MappingsConfiguration { + enabled?: boolean; + throwErrorsForUnmappedFields?: boolean; + date_detection?: boolean; + numeric_detection?: boolean; + dynamic_date_formats?: string[]; + _source?: { + enabled?: boolean; + includes?: string[]; + excludes?: string[]; + }; + _meta?: string; +} + +export interface MappingsTemplates { + dynamic_templates?: DynamicTemplate[]; +} + +export interface DynamicTemplate { + [key: string]: { + mapping: { + [key: string]: any; + }; + match_mapping_type?: string; + match?: string; + unmatch?: string; + match_pattern?: string; + path_match?: string; + path_unmatch?: string; + }; +} + +export interface MappingsFields { + [key: string]: any; +} + +export type DocumentFieldsStatus = 'idle' | 'editingField' | 'creatingField'; + +export interface DocumentFieldsState { + status: DocumentFieldsStatus; + editor: FieldsEditor; + fieldToEdit?: string; + fieldToAddFieldTo?: string; +} + +export interface ConfigurationFormState extends OnFormUpdateArg { + defaultValue: MappingsConfiguration; + submitForm?: FormHook['submit']; +} + +interface TemplatesFormState extends OnFormUpdateArg { + defaultValue: MappingsTemplates; + submitForm?: FormHook['submit']; +} + +export interface State { + isValid: boolean | undefined; + configuration: ConfigurationFormState; + documentFields: DocumentFieldsState; + fields: NormalizedFields; + fieldForm?: OnFormUpdateArg; + fieldsJsonEditor: { + format(): MappingsFields; + isValid: boolean; + }; + search: { + term: string; + result: SearchResult[]; + }; + templates: TemplatesFormState; +} + +export type Action = + | { type: 'editor.replaceMappings'; value: { [key: string]: any } } + | { type: 'configuration.update'; value: Partial } + | { type: 'configuration.save'; value: MappingsConfiguration } + | { type: 'templates.update'; value: Partial } + | { type: 'templates.save'; value: MappingsTemplates } + | { type: 'fieldForm.update'; value: OnFormUpdateArg } + | { type: 'field.add'; value: Field } + | { type: 'field.remove'; value: string } + | { type: 'field.edit'; value: Field } + | { type: 'field.toggleExpand'; value: { fieldId: string; isExpanded?: boolean } } + | { type: 'documentField.createField'; value?: string } + | { type: 'documentField.editField'; value: string } + | { type: 'documentField.changeStatus'; value: DocumentFieldsStatus } + | { type: 'documentField.changeEditor'; value: FieldsEditor } + | { type: 'fieldsJsonEditor.update'; value: { json: { [key: string]: any }; isValid: boolean } } + | { type: 'search:update'; value: string } + | { type: 'validity:update'; value: boolean }; + +export type Dispatch = (action: Action) => void; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/use_state_listener.tsx similarity index 53% rename from x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state.tsx rename to x-pack/plugins/index_management/public/application/components/mappings_editor/use_state_listener.tsx index ad5056fa73ce1..f1ffd5356c977 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/use_state_listener.tsx @@ -3,92 +3,32 @@ * 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, { useReducer, useEffect, createContext, useContext, useMemo, useRef } from 'react'; +import { useEffect, useMemo } from 'react'; import { - reducer, + Field, + Mappings, MappingsConfiguration, - MappingsFields, MappingsTemplates, - State, - Dispatch, -} from './reducer'; -import { Field } from './types'; + OnUpdateHandler, +} from './types'; import { normalize, deNormalize, stripUndefinedValues } from './lib'; +import { useMappingsState, useDispatch } from './mappings_state_context'; -type Mappings = MappingsTemplates & - MappingsConfiguration & { - properties?: MappingsFields; - }; - -export interface Types { - Mappings: Mappings; - MappingsConfiguration: MappingsConfiguration; - MappingsFields: MappingsFields; - MappingsTemplates: MappingsTemplates; -} - -export interface OnUpdateHandlerArg { - isValid?: boolean; - getData: () => Mappings | undefined; - validate: () => Promise; -} - -export type OnUpdateHandler = (arg: OnUpdateHandlerArg) => void; - -const StateContext = createContext(undefined); -const DispatchContext = createContext(undefined); - -export interface Props { - children: (params: { state: State }) => React.ReactNode; - value: { +interface Args { + onChange: OnUpdateHandler; + value?: { templates: MappingsTemplates; configuration: MappingsConfiguration; fields: { [key: string]: Field }; }; - onChange: OnUpdateHandler; } -export const MappingsState = React.memo(({ children, onChange, value }: Props) => { - const didMountRef = useRef(false); +export const useMappingsStateListener = ({ onChange, value }: Args) => { + const state = useMappingsState(); + const dispatch = useDispatch(); - const parsedFieldsDefaultValue = useMemo(() => normalize(value.fields), [value.fields]); - - const initialState: State = { - isValid: true, - configuration: { - defaultValue: value.configuration, - data: { - raw: value.configuration, - format: () => value.configuration, - }, - validate: () => Promise.resolve(true), - }, - templates: { - defaultValue: value.templates, - data: { - raw: value.templates, - format: () => value.templates, - }, - validate: () => Promise.resolve(true), - }, - fields: parsedFieldsDefaultValue, - documentFields: { - status: parsedFieldsDefaultValue.rootLevelFields.length === 0 ? 'creatingField' : 'idle', - editor: 'default', - }, - fieldsJsonEditor: { - format: () => ({}), - isValid: true, - }, - search: { - term: '', - result: [], - }, - }; - - const [state, dispatch] = useReducer(reducer, initialState); + const parsedFieldsDefaultValue = useMemo(() => normalize(value?.fields), [value?.fields]); useEffect(() => { // If we are creating a new field, but haven't entered any name @@ -158,46 +98,28 @@ export const MappingsState = React.memo(({ children, onChange, value }: Props) = }, isValid: state.isValid, }); - }, [state, onChange]); + }, [state, onChange, dispatch]); useEffect(() => { /** * If the value has changed that probably means that we have loaded * new data from JSON. We need to update our state with the new mappings. */ - if (didMountRef.current) { - dispatch({ - type: 'editor.replaceMappings', - value: { - configuration: value.configuration, - templates: value.templates, - fields: parsedFieldsDefaultValue, - }, - }); - } else { - didMountRef.current = true; + if (value === undefined) { + return; } - }, [value, parsedFieldsDefaultValue]); - - return ( - - {children({ state })} - - ); -}); - -export const useMappingsState = () => { - const ctx = useContext(StateContext); - if (ctx === undefined) { - throw new Error('useMappingsState must be used within a '); - } - return ctx; -}; -export const useDispatch = () => { - const ctx = useContext(DispatchContext); - if (ctx === undefined) { - throw new Error('useDispatch must be used within a '); - } - return ctx; + dispatch({ + type: 'editor.replaceMappings', + value: { + configuration: value.configuration, + templates: value.templates, + fields: parsedFieldsDefaultValue, + documentFields: { + status: parsedFieldsDefaultValue.rootLevelFields.length === 0 ? 'creatingField' : 'idle', + editor: 'default', + }, + }, + }); + }, [value, parsedFieldsDefaultValue, dispatch]); }; diff --git a/x-pack/plugins/index_management/public/application/components/template_form/steps/step_components.tsx b/x-pack/plugins/index_management/public/application/components/template_form/steps/step_components.tsx index df0cc791384fe..ae831f4acf7ee 100644 --- a/x-pack/plugins/index_management/public/application/components/template_form/steps/step_components.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_form/steps/step_components.tsx @@ -39,7 +39,7 @@ const i18nTexts = { ), }; -export const StepComponents = ({ defaultValue = [], onChange, esDocsBase }: Props) => { +export const StepComponents = ({ defaultValue, onChange, esDocsBase }: Props) => { const [state, setState] = useState<{ isLoadingComponents: boolean; components: ComponentTemplateListItem[]; diff --git a/x-pack/plugins/index_management/public/application/components/template_form/steps/step_logistics.tsx b/x-pack/plugins/index_management/public/application/components/template_form/steps/step_logistics.tsx index f3d05ac38108a..fcc9795617ebb 100644 --- a/x-pack/plugins/index_management/public/application/components/template_form/steps/step_logistics.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_form/steps/step_logistics.tsx @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import React, { useEffect } from 'react'; +import React, { useEffect, useCallback } from 'react'; import { EuiFlexGroup, EuiFlexItem, @@ -153,25 +153,18 @@ export const StepLogistics: React.FunctionComponent = React.memo( serializer: formSerializer, deserializer: formDeserializer, }); + const { subscribe, submit, isSubmitted, isValid: isFormValid, getErrors: getFormErrors } = form; /** * When the consumer call validate() on this step, we submit the form so it enters the "isSubmitted" state * and we can display the form errors on top of the forms if there are any. */ - const validate = async () => { - return (await form.submit()).isValid; - }; + const validate = useCallback(async () => { + return (await submit()).isValid; + }, [submit]); useEffect(() => { - onChange({ - isValid: form.isValid, - validate, - getData: form.getFormData, - }); - }, [form.isValid, onChange]); // eslint-disable-line react-hooks/exhaustive-deps - - useEffect(() => { - const subscription = form.subscribe(({ data, isValid }) => { + const subscription = subscribe(({ data, isValid }) => { onChange({ isValid, validate, @@ -179,7 +172,7 @@ export const StepLogistics: React.FunctionComponent = React.memo( }); }); return subscription.unsubscribe; - }, [onChange]); // eslint-disable-line react-hooks/exhaustive-deps + }, [onChange, validate, subscribe]); const { name, indexPatterns, dataStream, order, priority, version } = getFieldsMeta( documentationService.getEsDocsBase() @@ -204,7 +197,7 @@ export const StepLogistics: React.FunctionComponent = React.memo( @@ -220,8 +213,8 @@ export const StepLogistics: React.FunctionComponent = React.memo(
{/* Name */} diff --git a/x-pack/plugins/index_management/public/application/components/template_form/steps/step_review.tsx b/x-pack/plugins/index_management/public/application/components/template_form/steps/step_review.tsx index 0f4b9de4f6cfa..1b4f19dda99f7 100644 --- a/x-pack/plugins/index_management/public/application/components/template_form/steps/step_review.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_form/steps/step_review.tsx @@ -24,6 +24,7 @@ import { serializers } from '../../../../shared_imports'; import { serializeLegacyTemplate, serializeTemplate } from '../../../../../common/lib'; import { TemplateDeserialized, getTemplateParameter } from '../../../../../common'; +import { SimulateTemplate } from '../../index_templates'; import { WizardSection } from '../template_form'; const { stripEmptyFields } = serializers; @@ -56,6 +57,27 @@ interface Props { navigateToStep: (stepId: WizardSection) => void; } +const PreviewTab = ({ template }: { template: { [key: string]: any } }) => { + return ( +
+ + + +

+ +

+
+ + + + +
+ ); +}; + export const StepReview: React.FunctionComponent = React.memo( ({ template, navigateToStep }) => { const { @@ -286,6 +308,33 @@ export const StepReview: React.FunctionComponent = React.memo( ); }; + const tabs = [ + { + id: 'summary', + name: i18n.translate('xpack.idxMgmt.templateForm.stepReview.summaryTabTitle', { + defaultMessage: 'Summary', + }), + content: , + }, + { + id: 'request', + name: i18n.translate('xpack.idxMgmt.templateForm.stepReview.requestTabTitle', { + defaultMessage: 'Request', + }), + content: , + }, + ]; + + if (!isLegacy) { + tabs.splice(1, 0, { + id: 'preview', + name: i18n.translate('xpack.idxMgmt.templateForm.stepReview.previewTabTitle', { + defaultMessage: 'Preview', + }), + content: , + }); + } + return (
@@ -331,25 +380,7 @@ export const StepReview: React.FunctionComponent = React.memo( ) : null} - , - }, - { - id: 'request', - name: i18n.translate('xpack.idxMgmt.templateForm.stepReview.requestTabTitle', { - defaultMessage: 'Request', - }), - content: , - }, - ]} - /> +
); } diff --git a/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx b/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx index f5c9be9292cd0..fb0ba0b68fa6c 100644 --- a/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx @@ -3,14 +3,19 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import React, { useCallback } from 'react'; +import React, { useState, useCallback } from 'react'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { EuiSpacer } from '@elastic/eui'; +import { EuiSpacer, EuiButton } from '@elastic/eui'; import { TemplateDeserialized } from '../../../../common'; -import { serializers, Forms } from '../../../shared_imports'; +import { serializers, Forms, GlobalFlyout } from '../../../shared_imports'; import { SectionError } from '../section_error'; +import { + SimulateTemplateFlyoutContent, + SimulateTemplateProps, + simulateTemplateFlyoutProps, +} from '../index_templates'; import { StepLogisticsContainer, StepComponentContainer, StepReviewContainer } from './steps'; import { CommonWizardSteps, @@ -22,8 +27,10 @@ import { documentationService } from '../../services/documentation'; const { stripEmptyFields } = serializers; const { FormWizard, FormWizardStep } = Forms; +const { useGlobalFlyout } = GlobalFlyout; interface Props { + title: string | JSX.Element; onSave: (template: TemplateDeserialized) => void; clearSaveError: () => void; isSaving: boolean; @@ -80,6 +87,7 @@ const wizardSections: { [id: string]: { id: WizardSection; label: string } } = { }; export const TemplateForm = ({ + title, defaultValue, isEditing, isSaving, @@ -88,6 +96,9 @@ export const TemplateForm = ({ clearSaveError, onSave, }: Props) => { + const [wizardContent, setWizardContent] = useState | null>(null); + const { addContent: addContentToGlobalFlyout, closeFlyout } = useGlobalFlyout(); + const indexTemplate = defaultValue ?? { name: '', indexPatterns: [], @@ -189,6 +200,10 @@ export const TemplateForm = ({ [] ); + const onWizardContentChange = useCallback((content: Forms.Content) => { + setWizardContent(content); + }, []); + const onSaveTemplate = useCallback( async (wizardData: WizardContent) => { const template = buildTemplateObject(indexTemplate)(wizardData); @@ -206,44 +221,101 @@ export const TemplateForm = ({ [indexTemplate, buildTemplateObject, onSave, clearSaveError] ); + const getSimulateTemplate = useCallback(async () => { + if (!wizardContent) { + return; + } + const isValid = await wizardContent.validate(); + if (!isValid) { + return; + } + const wizardData = wizardContent.getData(); + const template = buildTemplateObject(indexTemplate)(wizardData); + return template; + }, [buildTemplateObject, indexTemplate, wizardContent]); + + const showPreviewFlyout = () => { + addContentToGlobalFlyout({ + id: 'simulateTemplate', + Component: SimulateTemplateFlyoutContent, + props: { + getTemplate: getSimulateTemplate, + onClose: closeFlyout, + }, + flyoutProps: simulateTemplateFlyoutProps, + }); + }; + + const getRightContentWizardNav = (stepId: WizardSection) => { + if (isLegacy) { + return null; + } + + // Don't show "Preview template" button on logistics and review steps + if (stepId === 'logistics' || stepId === 'review') { + return null; + } + + return ( + + + + ); + }; + return ( - - defaultValue={wizardDefaultValue} - onSave={onSaveTemplate} - isEditing={isEditing} - isSaving={isSaving} - apiError={apiError} - texts={i18nTexts} - > - - - + <> + {/* Form header */} + {title} - {indexTemplate._kbnMeta.isLegacy !== true && ( - - + + + + defaultValue={wizardDefaultValue} + onSave={onSaveTemplate} + isEditing={isEditing} + isSaving={isSaving} + apiError={apiError} + texts={i18nTexts} + onChange={onWizardContentChange} + rightContentNav={getRightContentWizardNav} + > + + - )} - - - + {indexTemplate._kbnMeta.isLegacy !== true && ( + + + + )} - - - + + + + + + + - - - + + + - - - - + + + + + ); }; diff --git a/x-pack/plugins/index_management/public/application/index.tsx b/x-pack/plugins/index_management/public/application/index.tsx index ebc29ac86a17f..f881c2e01cefc 100644 --- a/x-pack/plugins/index_management/public/application/index.tsx +++ b/x-pack/plugins/index_management/public/application/index.tsx @@ -11,11 +11,14 @@ import { render, unmountComponentAtNode } from 'react-dom'; import { CoreStart } from '../../../../../src/core/public'; import { API_BASE_PATH } from '../../common'; +import { GlobalFlyout } from '../shared_imports'; import { AppContextProvider, AppDependencies } from './app_context'; import { App } from './app'; import { indexManagementStore } from './store'; -import { ComponentTemplatesProvider } from './components'; +import { ComponentTemplatesProvider, MappingsEditorProvider } from './components'; + +const { GlobalFlyoutProvider } = GlobalFlyout; export const renderApp = ( elem: HTMLElement | null, @@ -43,9 +46,13 @@ export const renderApp = ( - - - + + + + + + + , diff --git a/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/tabs/index.ts b/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/tabs/index.ts index 08ebda2b5e437..11a86e78be99c 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/tabs/index.ts +++ b/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/tabs/index.ts @@ -5,3 +5,4 @@ */ export { TabSummary } from './tab_summary'; +export { TabPreview } from './tab_preview'; diff --git a/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/tabs/tab_preview.tsx b/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/tabs/tab_preview.tsx new file mode 100644 index 0000000000000..ec52bcbab3b0b --- /dev/null +++ b/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/tabs/tab_preview.tsx @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiText, EuiSpacer } from '@elastic/eui'; +import { TemplateDeserialized } from '../../../../../../../common'; +import { SimulateTemplate } from '../../../../../components/index_templates'; + +interface Props { + templateDetails: TemplateDeserialized; +} + +export const TabPreview = ({ templateDetails }: Props) => { + return ( +
+ +

+ +

+
+ + + + +
+ ); +}; diff --git a/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/template_details.tsx b/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/template_details.tsx index faeca2f2487a8..c03f64880a700 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/template_details.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/template_details.tsx @@ -15,8 +15,6 @@ export const TemplateDetails = (props: Props) => { onClose={props.onClose} data-test-subj="templateDetails" aria-labelledby="templateDetailsFlyoutTitle" - size="m" - maxWidth={500} > diff --git a/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/template_details_content.tsx b/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/template_details_content.tsx index 5b726013a1d92..5bacffc4c2404 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/template_details_content.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/template_list/template_details/template_details_content.tsx @@ -29,6 +29,7 @@ import { UIM_TEMPLATE_DETAIL_PANEL_SUMMARY_TAB, UIM_TEMPLATE_DETAIL_PANEL_SETTINGS_TAB, UIM_TEMPLATE_DETAIL_PANEL_ALIASES_TAB, + UIM_TEMPLATE_DETAIL_PANEL_PREVIEW_TAB, } from '../../../../../../common/constants'; import { SendRequestResponse } from '../../../../../shared_imports'; import { TemplateDeleteModal, SectionLoading, SectionError, Error } from '../../../../components'; @@ -37,12 +38,13 @@ import { decodePathFromReactRouter } from '../../../../services/routing'; import { useServices } from '../../../../app_context'; import { TabAliases, TabMappings, TabSettings } from '../../../../components/shared'; import { TemplateTypeIndicator } from '../components'; -import { TabSummary } from './tabs'; +import { TabSummary, TabPreview } from './tabs'; const SUMMARY_TAB_ID = 'summary'; const MAPPINGS_TAB_ID = 'mappings'; const ALIASES_TAB_ID = 'aliases'; const SETTINGS_TAB_ID = 'settings'; +const PREVIEW_TAB_ID = 'preview'; const TABS = [ { @@ -69,6 +71,12 @@ const TABS = [ defaultMessage: 'Aliases', }), }, + { + id: PREVIEW_TAB_ID, + name: i18n.translate('xpack.idxMgmt.templateDetails.previewTabTitle', { + defaultMessage: 'Preview', + }), + }, ]; const tabToUiMetricMap: { [key: string]: string } = { @@ -76,6 +84,7 @@ const tabToUiMetricMap: { [key: string]: string } = { [SETTINGS_TAB_ID]: UIM_TEMPLATE_DETAIL_PANEL_SETTINGS_TAB, [MAPPINGS_TAB_ID]: UIM_TEMPLATE_DETAIL_PANEL_MAPPINGS_TAB, [ALIASES_TAB_ID]: UIM_TEMPLATE_DETAIL_PANEL_ALIASES_TAB, + [PREVIEW_TAB_ID]: UIM_TEMPLATE_DETAIL_PANEL_PREVIEW_TAB, }; export interface Props { @@ -161,6 +170,7 @@ export const TemplateDetailsContent = ({ [SETTINGS_TAB_ID]: , [MAPPINGS_TAB_ID]: , [ALIASES_TAB_ID]: , + [PREVIEW_TAB_ID]: , }; const tabContent = tabToComponentMap[activeTab]; @@ -191,7 +201,13 @@ export const TemplateDetailsContent = ({ {managedTemplateCallout} - {TABS.map((tab) => ( + {TABS.filter((tab) => { + // Legacy index templates don't have the "simulate" template API + if (isLegacy && tab.id === PREVIEW_TAB_ID) { + return false; + } + return true; + }).map((tab) => ( { uiMetricService.trackMetric('click', tabToUiMetricMap[tab.id]); diff --git a/x-pack/plugins/index_management/public/application/sections/template_clone/template_clone.tsx b/x-pack/plugins/index_management/public/application/sections/template_clone/template_clone.tsx index 82835c56a3877..2aaecbd64ee28 100644 --- a/x-pack/plugins/index_management/public/application/sections/template_clone/template_clone.tsx +++ b/x-pack/plugins/index_management/public/application/sections/template_clone/template_clone.tsx @@ -6,7 +6,7 @@ import React, { useEffect, useState } from 'react'; import { RouteComponentProps } from 'react-router-dom'; import { FormattedMessage } from '@kbn/i18n/react'; -import { EuiPageBody, EuiPageContent, EuiSpacer, EuiTitle } from '@elastic/eui'; +import { EuiPageBody, EuiPageContent, EuiTitle } from '@elastic/eui'; import { TemplateDeserialized } from '../../../../common'; import { TemplateForm, SectionLoading, SectionError, Error } from '../../components'; @@ -94,30 +94,30 @@ export const TemplateClone: React.FunctionComponent +

+ +

+ + } defaultValue={templateData} onSave={onSave} isSaving={isSaving} saveError={saveError} clearSaveError={clearSaveError} + isLegacy={isLegacy} /> ); } return ( - - -

- -

-
- - {content} -
+ {content}
); }; diff --git a/x-pack/plugins/index_management/public/application/sections/template_create/template_create.tsx b/x-pack/plugins/index_management/public/application/sections/template_create/template_create.tsx index fb82f52968eb4..691d2598d56d9 100644 --- a/x-pack/plugins/index_management/public/application/sections/template_create/template_create.tsx +++ b/x-pack/plugins/index_management/public/application/sections/template_create/template_create.tsx @@ -6,7 +6,7 @@ import React, { useEffect, useState } from 'react'; import { RouteComponentProps } from 'react-router-dom'; import { FormattedMessage } from '@kbn/i18n/react'; -import { EuiPageBody, EuiPageContent, EuiSpacer, EuiTitle } from '@elastic/eui'; +import { EuiPageBody, EuiPageContent, EuiTitle } from '@elastic/eui'; import { useLocation } from 'react-router-dom'; import { parse } from 'query-string'; @@ -51,23 +51,24 @@ export const TemplateCreate: React.FunctionComponent = ({ h return ( - -

- {isLegacy ? ( - - ) : ( - - )} -

-
- +

+ {isLegacy ? ( + + ) : ( + + )} +

+ + } onSave={onSave} isSaving={isSaving} saveError={saveError} diff --git a/x-pack/plugins/index_management/public/application/sections/template_edit/template_edit.tsx b/x-pack/plugins/index_management/public/application/sections/template_edit/template_edit.tsx index 29fd2e02120fc..6bdcd03fa5ca4 100644 --- a/x-pack/plugins/index_management/public/application/sections/template_edit/template_edit.tsx +++ b/x-pack/plugins/index_management/public/application/sections/template_edit/template_edit.tsx @@ -133,12 +133,24 @@ export const TemplateEdit: React.FunctionComponent )} +

+ +

+ + } defaultValue={template} onSave={onSave} isSaving={isSaving} saveError={saveError} clearSaveError={clearSaveError} isEditing={true} + isLegacy={isLegacy} /> ); @@ -147,19 +159,7 @@ export const TemplateEdit: React.FunctionComponent - - -

- -

-
- - {content} -
+ {content}
); }; diff --git a/x-pack/plugins/index_management/public/application/services/api.ts b/x-pack/plugins/index_management/public/application/services/api.ts index d7874ec2dcf32..546a0115ee4a9 100644 --- a/x-pack/plugins/index_management/public/application/services/api.ts +++ b/x-pack/plugins/index_management/public/application/services/api.ts @@ -30,6 +30,7 @@ import { UIM_TEMPLATE_CREATE, UIM_TEMPLATE_UPDATE, UIM_TEMPLATE_CLONE, + UIM_TEMPLATE_SIMULATE, } from '../../../common/constants'; import { TemplateDeserialized, TemplateListItem, DataStream } from '../../../common'; import { IndexMgmtMetricsType } from '../../types'; @@ -286,3 +287,14 @@ export async function updateTemplate(template: TemplateDeserialized) { return result; } + +export function simulateIndexTemplate(template: { [key: string]: any }) { + return sendRequest({ + path: `${API_BASE_PATH}/index_templates/simulate`, + method: 'post', + body: JSON.stringify(template), + }).then((result) => { + uiMetricService.trackMetric('count', UIM_TEMPLATE_SIMULATE); + return result; + }); +} diff --git a/x-pack/plugins/index_management/public/application/services/documentation.ts b/x-pack/plugins/index_management/public/application/services/documentation.ts index 972b4f4b25680..afc9c76f1afbe 100644 --- a/x-pack/plugins/index_management/public/application/services/documentation.ts +++ b/x-pack/plugins/index_management/public/application/services/documentation.ts @@ -40,8 +40,10 @@ class DocumentationService { return `${this.esDocsBase}/data-streams.html`; } - public getTemplatesDocumentationLink() { - return `${this.esDocsBase}/indices-templates.html`; + public getTemplatesDocumentationLink(isLegacy = false) { + return isLegacy + ? `${this.esDocsBase}/indices-templates-v1.html` + : `${this.esDocsBase}/indices-templates.html`; } public getIdxMgmtDocumentationLink() { diff --git a/x-pack/plugins/index_management/public/application/services/index.ts b/x-pack/plugins/index_management/public/application/services/index.ts index 2334d32adf131..a78e0bac14ae1 100644 --- a/x-pack/plugins/index_management/public/application/services/index.ts +++ b/x-pack/plugins/index_management/public/application/services/index.ts @@ -22,6 +22,7 @@ export { loadIndexMapping, loadIndexData, useLoadIndexTemplates, + simulateIndexTemplate, } from './api'; export { healthToColor } from './health_to_color'; export { sortTable } from './sort_table'; diff --git a/x-pack/plugins/index_management/public/shared_imports.ts b/x-pack/plugins/index_management/public/shared_imports.ts index 3f7fcf424f1f0..16dcab18c3caf 100644 --- a/x-pack/plugins/index_management/public/shared_imports.ts +++ b/x-pack/plugins/index_management/public/shared_imports.ts @@ -12,6 +12,7 @@ export { useRequest, Forms, extractQueryParams, + GlobalFlyout, } from '../../../../src/plugins/es_ui_shared/public/'; export { diff --git a/x-pack/plugins/index_management/server/client/elasticsearch.ts b/x-pack/plugins/index_management/server/client/elasticsearch.ts index 9f8bce241ae69..ed5ede07479ca 100644 --- a/x-pack/plugins/index_management/server/client/elasticsearch.ts +++ b/x-pack/plugins/index_management/server/client/elasticsearch.ts @@ -182,4 +182,14 @@ export const elasticsearchJsPlugin = (Client: any, config: any, components: any) ], method: 'HEAD', }); + + dataManagement.simulateTemplate = ca({ + urls: [ + { + fmt: '/_index_template/_simulate', + }, + ], + needBody: true, + method: 'POST', + }); }; diff --git a/x-pack/plugins/index_management/server/routes/api/templates/register_simulate_route.ts b/x-pack/plugins/index_management/server/routes/api/templates/register_simulate_route.ts new file mode 100644 index 0000000000000..9d078e135fd52 --- /dev/null +++ b/x-pack/plugins/index_management/server/routes/api/templates/register_simulate_route.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { schema, TypeOf } from '@kbn/config-schema'; + +import { RouteDependencies } from '../../../types'; +import { addBasePath } from '../index'; + +const bodySchema = schema.object({}, { unknowns: 'allow' }); + +export function registerSimulateRoute({ router, license, lib }: RouteDependencies) { + router.post( + { + path: addBasePath('/index_templates/simulate'), + validate: { body: bodySchema }, + }, + license.guardApiRoute(async (ctx, req, res) => { + const { callAsCurrentUser } = ctx.dataManagement!.client; + const template = req.body as TypeOf; + + try { + const templatePreview = await callAsCurrentUser('dataManagement.simulateTemplate', { + body: template, + }); + + return res.ok({ body: templatePreview }); + } catch (e) { + if (lib.isEsError(e)) { + return res.customError({ + statusCode: e.statusCode, + body: e, + }); + } + // Case: default + return res.internalError({ body: e }); + } + }) + ); +} diff --git a/x-pack/plugins/index_management/server/routes/api/templates/register_template_routes.ts b/x-pack/plugins/index_management/server/routes/api/templates/register_template_routes.ts index 2b657346a2f82..e25f2abdfee78 100644 --- a/x-pack/plugins/index_management/server/routes/api/templates/register_template_routes.ts +++ b/x-pack/plugins/index_management/server/routes/api/templates/register_template_routes.ts @@ -10,6 +10,7 @@ import { registerGetAllRoute, registerGetOneRoute } from './register_get_routes' import { registerDeleteRoute } from './register_delete_route'; import { registerCreateRoute } from './register_create_route'; import { registerUpdateRoute } from './register_update_route'; +import { registerSimulateRoute } from './register_simulate_route'; export function registerTemplateRoutes(dependencies: RouteDependencies) { registerGetAllRoute(dependencies); @@ -17,4 +18,5 @@ export function registerTemplateRoutes(dependencies: RouteDependencies) { registerDeleteRoute(dependencies); registerCreateRoute(dependencies); registerUpdateRoute(dependencies); + registerSimulateRoute(dependencies); } diff --git a/x-pack/plugins/infra/common/http_api/log_sources/get_log_source_status.ts b/x-pack/plugins/infra/common/http_api/log_sources/get_log_source_status.ts index b522d86987283..dc4e4f1ea6217 100644 --- a/x-pack/plugins/infra/common/http_api/log_sources/get_log_source_status.ts +++ b/x-pack/plugins/infra/common/http_api/log_sources/get_log_source_status.ts @@ -40,9 +40,17 @@ const logIndexFieldRT = rt.strict({ export type LogIndexField = rt.TypeOf; +const logIndexStatusRT = rt.keyof({ + missing: null, + empty: null, + available: null, +}); + +export type LogIndexStatus = rt.TypeOf; + const logSourceStatusRT = rt.strict({ logIndexFields: rt.array(logIndexFieldRT), - logIndicesExist: rt.boolean, + logIndexStatus: logIndexStatusRT, }); export type LogSourceStatus = rt.TypeOf; diff --git a/x-pack/plugins/infra/common/http_api/snapshot_api.ts b/x-pack/plugins/infra/common/http_api/snapshot_api.ts index 9ddbcb17089f3..11cb57238f917 100644 --- a/x-pack/plugins/infra/common/http_api/snapshot_api.ts +++ b/x-pack/plugins/infra/common/http_api/snapshot_api.ts @@ -107,6 +107,7 @@ export const SnapshotRequestRT = rt.intersection([ region: rt.string, filterQuery: rt.union([rt.string, rt.null]), includeTimeseries: rt.boolean, + overrideCompositeSize: rt.number, }), ]); diff --git a/x-pack/plugins/infra/public/alerting/inventory/components/alert_flyout.tsx b/x-pack/plugins/infra/public/alerting/inventory/components/alert_flyout.tsx index 7e85a2bdf7e9b..804ff9602c81c 100644 --- a/x-pack/plugins/infra/public/alerting/inventory/components/alert_flyout.tsx +++ b/x-pack/plugins/infra/public/alerting/inventory/components/alert_flyout.tsx @@ -44,7 +44,7 @@ export const AlertFlyout = (props: Props) => { setAddFlyoutVisibility={props.setVisible} alertTypeId={METRIC_INVENTORY_THRESHOLD_ALERT_TYPE_ID} canChangeTrigger={false} - consumer={'metrics'} + consumer={'infrastructure'} /> )} diff --git a/x-pack/plugins/infra/public/alerting/inventory/components/expression.tsx b/x-pack/plugins/infra/public/alerting/inventory/components/expression.tsx index 8d36262b55792..583cbe18ee9db 100644 --- a/x-pack/plugins/infra/public/alerting/inventory/components/expression.tsx +++ b/x-pack/plugins/infra/public/alerting/inventory/components/expression.tsx @@ -364,7 +364,7 @@ export const Expressions: React.FC = (props) => { { setAddFlyoutVisibility={props.setVisible} alertTypeId={METRIC_THRESHOLD_ALERT_TYPE_ID} canChangeTrigger={false} - consumer={'metrics'} + consumer={'infrastructure'} /> )} diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/index.ts b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/index.ts index afad55dd22d43..485ef71e0ca36 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/index.ts +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/index.ts @@ -6,4 +6,3 @@ export * from './log_analysis_job_problem_indicator'; export * from './notices_section'; -export * from './recreate_job_button'; diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/job_configuration_outdated_callout.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/job_configuration_outdated_callout.tsx index a8a7ec4f5f44f..0489bd7d9929a 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/job_configuration_outdated_callout.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/job_configuration_outdated_callout.tsx @@ -11,10 +11,12 @@ import React from 'react'; import { RecreateJobCallout } from './recreate_job_callout'; export const JobConfigurationOutdatedCallout: React.FC<{ + hasSetupCapabilities: boolean; moduleName: string; onRecreateMlJob: () => void; -}> = ({ moduleName, onRecreateMlJob }) => ( +}> = ({ hasSetupCapabilities, moduleName, onRecreateMlJob }) => ( void; -}> = ({ moduleName, onRecreateMlJob }) => ( +}> = ({ hasSetupCapabilities, moduleName, onRecreateMlJob }) => ( = ({ hasOutdatedJobConfigurations, hasOutdatedJobDefinitions, + hasSetupCapabilities, hasStoppedJobs, isFirstUse, moduleName, @@ -32,12 +34,14 @@ export const LogAnalysisJobProblemIndicator: React.FC<{ <> {hasOutdatedJobDefinitions ? ( ) : null} {hasOutdatedJobConfigurations ? ( diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/notices_section.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/notices_section.tsx index aa72281b9fbdb..2535058322cba 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/notices_section.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/notices_section.tsx @@ -12,6 +12,7 @@ import { CategoryQualityWarnings } from './quality_warning_notices'; export const CategoryJobNoticesSection: React.FC<{ hasOutdatedJobConfigurations: boolean; hasOutdatedJobDefinitions: boolean; + hasSetupCapabilities: boolean; hasStoppedJobs: boolean; isFirstUse: boolean; moduleName: string; @@ -21,6 +22,7 @@ export const CategoryJobNoticesSection: React.FC<{ }> = ({ hasOutdatedJobConfigurations, hasOutdatedJobDefinitions, + hasSetupCapabilities, hasStoppedJobs, isFirstUse, moduleName, @@ -32,6 +34,7 @@ export const CategoryJobNoticesSection: React.FC<{ > = (props) => ( - - - -); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/recreate_job_callout.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/recreate_job_callout.tsx index 5b872d4ee5147..cdf030a849fa1 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/recreate_job_callout.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/recreate_job_callout.tsx @@ -4,17 +4,21 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; import { EuiCallOut } from '@elastic/eui'; - -import { RecreateJobButton } from './recreate_job_button'; +import React from 'react'; +import { RecreateJobButton } from '../log_analysis_setup/create_job_button'; export const RecreateJobCallout: React.FC<{ + hasSetupCapabilities?: boolean; onRecreateMlJob: () => void; title?: React.ReactNode; -}> = ({ children, onRecreateMlJob, title }) => ( +}> = ({ children, hasSetupCapabilities, onRecreateMlJob, title }) => (

{children}

- +
); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/create_job_button.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/create_job_button.tsx new file mode 100644 index 0000000000000..1e4473d359bba --- /dev/null +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/create_job_button.tsx @@ -0,0 +1,49 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiButton, PropsOf } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import React from 'react'; +import { MissingSetupPrivilegesToolTip } from './missing_setup_privileges_tooltip'; + +export const CreateJobButton: React.FunctionComponent< + { + hasSetupCapabilities?: boolean; + } & PropsOf +> = ({ hasSetupCapabilities = true, children, ...buttonProps }) => { + const button = ( + + {children ?? ( + + )} + + ); + + return hasSetupCapabilities ? ( + button + ) : ( + + {button} + + ); +}; + +export const RecreateJobButton: React.FunctionComponent> = ({ + children, + ...otherProps +}) => ( + + {children ?? ( + + )} + +); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_privileges_messages.ts b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_privileges_messages.ts new file mode 100644 index 0000000000000..cca8fc03f7c2a --- /dev/null +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_privileges_messages.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; + +export const missingMlPrivilegesTitle = i18n.translate( + 'xpack.infra.logs.analysis.missingMlPrivilegesTitle', + { + defaultMessage: 'Additional Machine Learning privileges required', + } +); + +export const missingMlResultsPrivilegesDescription = i18n.translate( + 'xpack.infra.logs.analysis.missingMlResultsPrivilegesDescription', + { + defaultMessage: + 'This feature makes use of Machine Learning jobs, which require at least the read permission for the Machine Learning app in order to access their status and results.', + } +); + +export const missingMlSetupPrivilegesDescription = i18n.translate( + 'xpack.infra.logs.analysis.missingMlSetupPrivilegesDescription', + { + defaultMessage: + 'This feature makes use of Machine Learning jobs, which require all permissions for the Machine Learning app in order to be set up.', + } +); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_results_privileges_prompt.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_results_privileges_prompt.tsx index 2d378508e2b58..3aa8b544b7b54 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_results_privileges_prompt.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_results_privileges_prompt.tsx @@ -4,34 +4,19 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiEmptyPrompt, EuiCode } from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiEmptyPrompt } from '@elastic/eui'; import React from 'react'; - import { euiStyled } from '../../../../../observability/public'; +import { + missingMlPrivilegesTitle, + missingMlResultsPrivilegesDescription, +} from './missing_privileges_messages'; import { UserManagementLink } from './user_management_link'; export const MissingResultsPrivilegesPrompt: React.FunctionComponent = () => ( - - - } - body={ -

- machine_learning_user, - }} - /> -

- } + title={

{missingMlPrivilegesTitle}

} + body={

{missingMlResultsPrivilegesDescription}

} actions={} /> ); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_setup_privileges_prompt.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_setup_privileges_prompt.tsx index db89ff415a6f7..6a5a1da890418 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_setup_privileges_prompt.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_setup_privileges_prompt.tsx @@ -4,34 +4,19 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiEmptyPrompt, EuiCode } from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiEmptyPrompt } from '@elastic/eui'; import React from 'react'; - import { euiStyled } from '../../../../../observability/public'; +import { + missingMlPrivilegesTitle, + missingMlSetupPrivilegesDescription, +} from './missing_privileges_messages'; import { UserManagementLink } from './user_management_link'; export const MissingSetupPrivilegesPrompt: React.FunctionComponent = () => ( - - - } - body={ -

- machine_learning_admin, - }} - /> -

- } + title={

{missingMlPrivilegesTitle}

} + body={

{missingMlSetupPrivilegesDescription}

} actions={} /> ); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_setup_privileges_tooltip.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_setup_privileges_tooltip.tsx new file mode 100644 index 0000000000000..ccd207129e471 --- /dev/null +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/missing_setup_privileges_tooltip.tsx @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiToolTip, PropsOf } from '@elastic/eui'; +import React from 'react'; +import { + missingMlPrivilegesTitle, + missingMlSetupPrivilegesDescription, +} from './missing_privileges_messages'; + +export const MissingSetupPrivilegesToolTip: React.FC, + 'content' | 'title' +>> = (props) => ( + +); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx index 8239ab4a730ff..2c68aceccaa43 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx @@ -6,6 +6,7 @@ import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import React, { useCallback } from 'react'; +import { useLogAnalysisCapabilitiesContext } from '../../../../containers/logs/log_analysis'; import { logEntryCategoriesModule, useLogEntryCategoriesModuleContext, @@ -20,6 +21,7 @@ import type { ModuleId } from './setup_flyout_state'; export const LogAnalysisModuleList: React.FC<{ onViewModuleSetup: (module: ModuleId) => void; }> = ({ onViewModuleSetup }) => { + const { hasLogAnalysisSetupCapabilities } = useLogAnalysisCapabilitiesContext(); const { setupStatus: logEntryRateSetupStatus } = useLogEntryRateModuleContext(); const { setupStatus: logEntryCategoriesSetupStatus } = useLogEntryCategoriesModuleContext(); @@ -35,6 +37,7 @@ export const LogAnalysisModuleList: React.FC<{ void; -}> = ({ moduleDescription, moduleName, moduleStatus, onViewSetup }) => { - const icon = +}> = ({ hasSetupCapabilities, moduleDescription, moduleName, moduleStatus, onViewSetup }) => { + const moduleIcon = moduleStatus.type === 'required' ? ( ) : ( ); - const footerContent = + + const moduleSetupButton = moduleStatus.type === 'required' ? ( - + - + ) : ( - + ); return ( {footerContent}
} - icon={icon} + footer={
{moduleSetupButton}
} + icon={moduleIcon} title={moduleName} /> ); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/user_management_link.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/user_management_link.tsx index 49ab25297c687..66fac524b0230 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/user_management_link.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/user_management_link.tsx @@ -11,8 +11,8 @@ import { useLinkProps } from '../../../hooks/use_link_props'; export const UserManagementLink: React.FunctionComponent = (props) => { const linkProps = useLinkProps({ - app: 'kibana', - hash: '/management/security/users', + app: 'management', + pathname: '/security/users', }); return ( diff --git a/x-pack/plugins/infra/public/components/saved_views/manage_views_flyout.tsx b/x-pack/plugins/infra/public/components/saved_views/manage_views_flyout.tsx index fa9b45558e491..698034f8154d1 100644 --- a/x-pack/plugins/infra/public/components/saved_views/manage_views_flyout.tsx +++ b/x-pack/plugins/infra/public/components/saved_views/manage_views_flyout.tsx @@ -96,6 +96,10 @@ export function SavedViewManageViewsFlyout({ const renderDeleteAction = useCallback( (item: SavedView) => { + if (item.id === '0') { + return <>; + } + return ( (props: Props) { /> - + (props: Props) { {currentView ? currentView.name : i18n.translate('xpack.infra.savedView.unknownView', { - defaultMessage: 'Unknown', + defaultMessage: 'No view seleted', })} diff --git a/x-pack/plugins/infra/public/containers/saved_view/saved_view.tsx b/x-pack/plugins/infra/public/containers/saved_view/saved_view.tsx index 58fecdd54e303..3f38d8b97a296 100644 --- a/x-pack/plugins/infra/public/containers/saved_view/saved_view.tsx +++ b/x-pack/plugins/infra/public/containers/saved_view/saved_view.tsx @@ -50,7 +50,7 @@ export const useSavedView = (props: Props) => { const { data, loading, find, error: errorOnFind, hasView } = useFindSavedObject< SavedViewSavedObject >(viewType); - + const [shouldLoadDefault] = useState(props.shouldLoadDefault); const [currentView, setCurrentView] = useState | null>(null); const [loadingDefaultView, setLoadingDefaultView] = useState(null); const { create, error: errorOnCreate, data: createdViewData, createdId } = useCreateSavedObject( @@ -211,8 +211,6 @@ export const useSavedView = (props: Props) => { }, [setCurrentView, defaultViewId, defaultViewState]); useEffect(() => { - const shouldLoadDefault = props.shouldLoadDefault; - if (loadingDefaultView || currentView || !shouldLoadDefault) { return; } @@ -225,7 +223,7 @@ export const useSavedView = (props: Props) => { } }, [ loadDefaultView, - props.shouldLoadDefault, + shouldLoadDefault, setDefault, loadingDefaultView, currentView, @@ -246,7 +244,7 @@ export const useSavedView = (props: Props) => { errorOnUpdate, errorOnFind, errorOnCreate: createError, - shouldLoadDefault: props.shouldLoadDefault, + shouldLoadDefault, makeDefault, sourceIsLoading, deleteView, diff --git a/x-pack/plugins/infra/public/metrics_overview_fetchers.test.ts b/x-pack/plugins/infra/public/metrics_overview_fetchers.test.ts index 88bc426e9a0f7..135b4ea9a5335 100644 --- a/x-pack/plugins/infra/public/metrics_overview_fetchers.test.ts +++ b/x-pack/plugins/infra/public/metrics_overview_fetchers.test.ts @@ -75,6 +75,7 @@ describe('Metrics UI Observability Homepage Functions', () => { groupBy: [], nodeType: 'host', includeTimeseries: true, + overrideCompositeSize: 5, timerange: { from: startTime.valueOf(), to: endTime.valueOf(), diff --git a/x-pack/plugins/infra/public/metrics_overview_fetchers.ts b/x-pack/plugins/infra/public/metrics_overview_fetchers.ts index 4eaf903e17608..79e0850635138 100644 --- a/x-pack/plugins/infra/public/metrics_overview_fetchers.ts +++ b/x-pack/plugins/infra/public/metrics_overview_fetchers.ts @@ -87,6 +87,7 @@ export const createMetricsFetchData = ( groupBy: [], nodeType: 'host', includeTimeseries: true, + overrideCompositeSize: 5, timerange: { from: start, to: end, diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx index 5e602e1f63862..028dd0d3a1a7b 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx @@ -23,6 +23,7 @@ import { StringTimeRange, useLogEntryCategoriesResultsUrlState, } from './use_log_entry_categories_results_url_state'; +import { useLogAnalysisCapabilitiesContext } from '../../../containers/logs/log_analysis/log_analysis_capabilities'; const JOB_STATUS_POLLING_INTERVAL = 30000; @@ -36,6 +37,8 @@ export const LogEntryCategoriesResultsContent: React.FunctionComponent = ({ availableDatasets, + hasSetupCapabilities, isLoadingDatasets = false, isLoadingTopCategories = false, jobId, @@ -51,7 +53,11 @@ export const TopCategoriesSection: React.FunctionComponent<{ - + diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx index fb1dc7717fed0..65cc4a6c4a704 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx @@ -15,7 +15,9 @@ import { CategoryJobNoticesSection, LogAnalysisJobProblemIndicator, } from '../../../components/logging/log_analysis_job_status'; +import { DatasetsSelector } from '../../../components/logging/log_analysis_results/datasets_selector'; import { useLogAnalysisSetupFlyoutStateContext } from '../../../components/logging/log_analysis_setup/setup_flyout'; +import { useLogAnalysisCapabilitiesContext } from '../../../containers/logs/log_analysis/log_analysis_capabilities'; import { useLogEntryCategoriesModuleContext } from '../../../containers/logs/log_analysis/modules/log_entry_categories'; import { useLogEntryRateModuleContext } from '../../../containers/logs/log_analysis/modules/log_entry_rate'; import { useLogSourceContext } from '../../../containers/logs/log_source'; @@ -27,7 +29,6 @@ import { StringTimeRange, useLogAnalysisResultsUrlState, } from './use_log_entry_rate_results_url_state'; -import { DatasetsSelector } from '../../../components/logging/log_analysis_results/datasets_selector'; export const SORT_DEFAULTS = { direction: 'desc' as const, @@ -44,6 +45,8 @@ export const LogEntryRateResultsContent: React.FunctionComponent = () => { const { sourceId } = useLogSourceContext(); + const { hasLogAnalysisSetupCapabilities } = useLogAnalysisCapabilitiesContext(); + const { hasOutdatedJobConfigurations: hasOutdatedLogEntryRateJobConfigurations, hasOutdatedJobDefinitions: hasOutdatedLogEntryRateJobDefinitions, @@ -223,6 +226,7 @@ export const LogEntryRateResultsContent: React.FunctionComponent = () => { { { return ; } else if (hasFailedLoadingSource) { return ; - } else if (sourceStatus?.logIndicesExist) { + } else if (sourceStatus?.logIndexStatus !== 'missing') { return ; } else { return ; diff --git a/x-pack/plugins/infra/public/pages/logs/stream/page_providers.tsx b/x-pack/plugins/infra/public/pages/logs/stream/page_providers.tsx index 82c21f663bc96..1a1cc13576556 100644 --- a/x-pack/plugins/infra/public/pages/logs/stream/page_providers.tsx +++ b/x-pack/plugins/infra/public/pages/logs/stream/page_providers.tsx @@ -107,7 +107,7 @@ export const LogsPageProviders: React.FunctionComponent = ({ children }) => { const { sourceStatus } = useLogSourceContext(); // The providers assume the source is loaded, so short-circuit them otherwise - if (!sourceStatus?.logIndicesExist) { + if (sourceStatus?.logIndexStatus === 'missing') { return <>{children}; } diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx index fddd92128708a..ad92c054ee459 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx @@ -55,7 +55,8 @@ export const Layout = () => { sourceId, currentTime, accountId, - region + region, + false ); const options = { diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/index.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/index.tsx index cd875ae54071c..20efca79650a1 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/index.tsx @@ -57,7 +57,8 @@ export const MetricsExplorerPage = ({ source, derivedIndexPattern }: MetricsExpl // load metrics explorer data after default view loaded, unless we're not loading a view loadData(); } - }, [loadData, currentView, shouldLoadDefault]); + /* eslint-disable-next-line react-hooks/exhaustive-deps */ + }, [loadData, shouldLoadDefault]); return ( diff --git a/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts b/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts index 53f7e00a3354c..3716e618068a3 100644 --- a/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts +++ b/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts @@ -43,7 +43,7 @@ export function getLogsHasDataFetcher( return async () => { const [core] = await getStartServices(); const sourceStatus = await callFetchLogSourceStatusAPI(DEFAULT_SOURCE_ID, core.http.fetch); - return sourceStatus.data.logIndicesExist; + return sourceStatus.data.logIndexStatus === 'available'; }; } diff --git a/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts b/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts index 6f9e41fbd08f3..a2b4e162756e3 100644 --- a/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts +++ b/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts @@ -3,17 +3,18 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ + +import { CoreStart } from 'kibana/public'; import { coreMock } from 'src/core/public/mocks'; import { dataPluginMock } from 'src/plugins/data/public/mocks'; -import { CoreStart } from 'kibana/public'; -import { getLogsHasDataFetcher } from './logs_overview_fetchers'; -import { InfraClientStartDeps, InfraClientStartExports } from '../types'; import { callFetchLogSourceStatusAPI } from '../containers/logs/log_source/api/fetch_log_source_status'; +import { InfraClientStartDeps, InfraClientStartExports } from '../types'; +import { getLogsHasDataFetcher } from './logs_overview_fetchers'; -// Note -// Calls to `.mock*` functions will fail the typecheck because how jest does the mocking. -// The calls will be preluded with a `@ts-expect-error` jest.mock('../containers/logs/log_source/api/fetch_log_source_status'); +const mockedCallFetchLogSourceStatusAPI = callFetchLogSourceStatusAPI as jest.MockedFunction< + typeof callFetchLogSourceStatusAPI +>; function setup() { const core = coreMock.createStart(); @@ -33,36 +34,47 @@ function setup() { describe('Logs UI Observability Homepage Functions', () => { describe('getLogsHasDataFetcher()', () => { beforeEach(() => { - // @ts-expect-error - callFetchLogSourceStatusAPI.mockReset(); + mockedCallFetchLogSourceStatusAPI.mockReset(); }); - it('should return true when some index is present', async () => { + it('should return true when non-empty indices exist', async () => { const { mockedGetStartServices } = setup(); - // @ts-expect-error - callFetchLogSourceStatusAPI.mockResolvedValue({ - data: { logIndexFields: [], logIndicesExist: true }, + mockedCallFetchLogSourceStatusAPI.mockResolvedValue({ + data: { logIndexFields: [], logIndexStatus: 'available' }, }); const hasData = getLogsHasDataFetcher(mockedGetStartServices); const response = await hasData(); - expect(callFetchLogSourceStatusAPI).toHaveBeenCalledTimes(1); + expect(mockedCallFetchLogSourceStatusAPI).toHaveBeenCalledTimes(1); expect(response).toBe(true); }); - it('should return false when no index is present', async () => { + it('should return false when only empty indices exist', async () => { + const { mockedGetStartServices } = setup(); + + mockedCallFetchLogSourceStatusAPI.mockResolvedValue({ + data: { logIndexFields: [], logIndexStatus: 'empty' }, + }); + + const hasData = getLogsHasDataFetcher(mockedGetStartServices); + const response = await hasData(); + + expect(mockedCallFetchLogSourceStatusAPI).toHaveBeenCalledTimes(1); + expect(response).toBe(false); + }); + + it('should return false when no index exists', async () => { const { mockedGetStartServices } = setup(); - // @ts-expect-error - callFetchLogSourceStatusAPI.mockResolvedValue({ - data: { logIndexFields: [], logIndicesExist: false }, + mockedCallFetchLogSourceStatusAPI.mockResolvedValue({ + data: { logIndexFields: [], logIndexStatus: 'missing' }, }); const hasData = getLogsHasDataFetcher(mockedGetStartServices); const response = await hasData(); - expect(callFetchLogSourceStatusAPI).toHaveBeenCalledTimes(1); + expect(mockedCallFetchLogSourceStatusAPI).toHaveBeenCalledTimes(1); expect(response).toBe(false); }); }); diff --git a/x-pack/plugins/infra/server/features.ts b/x-pack/plugins/infra/server/features.ts index fa228e03194a9..3e32cebf19ac2 100644 --- a/x-pack/plugins/infra/server/features.ts +++ b/x-pack/plugins/infra/server/features.ts @@ -5,6 +5,9 @@ */ import { i18n } from '@kbn/i18n'; +import { LOG_DOCUMENT_COUNT_ALERT_TYPE_ID } from '../common/alerting/logs/types'; +import { METRIC_INVENTORY_THRESHOLD_ALERT_TYPE_ID } from './lib/alerting/inventory_metric_threshold/types'; +import { METRIC_THRESHOLD_ALERT_TYPE_ID } from './lib/alerting/metric_threshold/types'; export const METRICS_FEATURE = { id: 'infrastructure', @@ -14,46 +17,44 @@ export const METRICS_FEATURE = { order: 700, icon: 'metricsApp', navLinkId: 'metrics', - app: ['infra', 'kibana'], + app: ['infra', 'metrics', 'kibana'], catalogue: ['infraops'], + management: { + insightsAndAlerting: ['triggersActions'], + }, + alerting: [METRIC_THRESHOLD_ALERT_TYPE_ID, METRIC_INVENTORY_THRESHOLD_ALERT_TYPE_ID], privileges: { all: { - app: ['infra', 'kibana'], + app: ['infra', 'metrics', 'kibana'], catalogue: ['infraops'], - api: ['infra', 'actions-read', 'actions-all', 'alerting-read', 'alerting-all'], + api: ['infra'], savedObject: { - all: ['infrastructure-ui-source', 'alert', 'action', 'action_task_params'], + all: ['infrastructure-ui-source'], read: ['index-pattern'], }, - ui: [ - 'show', - 'configureSource', - 'save', - 'alerting:show', - 'actions:show', - 'alerting:save', - 'actions:save', - 'alerting:delete', - 'actions:delete', - ], + alerting: { + all: [METRIC_THRESHOLD_ALERT_TYPE_ID, METRIC_INVENTORY_THRESHOLD_ALERT_TYPE_ID], + }, + management: { + insightsAndAlerting: ['triggersActions'], + }, + ui: ['show', 'configureSource', 'save'], }, read: { - app: ['infra', 'kibana'], + app: ['infra', 'metrics', 'kibana'], catalogue: ['infraops'], - api: ['infra', 'actions-read', 'actions-all', 'alerting-read', 'alerting-all'], + api: ['infra'], savedObject: { - all: ['alert', 'action', 'action_task_params'], + all: [], read: ['infrastructure-ui-source', 'index-pattern'], }, - ui: [ - 'show', - 'alerting:show', - 'actions:show', - 'alerting:save', - 'actions:save', - 'alerting:delete', - 'actions:delete', - ], + alerting: { + all: [METRIC_THRESHOLD_ALERT_TYPE_ID, METRIC_INVENTORY_THRESHOLD_ALERT_TYPE_ID], + }, + management: { + insightsAndAlerting: ['triggersActions'], + }, + ui: ['show'], }, }, }; @@ -66,23 +67,30 @@ export const LOGS_FEATURE = { order: 800, icon: 'logsApp', navLinkId: 'logs', - app: ['infra', 'kibana'], + app: ['infra', 'logs', 'kibana'], catalogue: ['infralogging'], + alerting: [LOG_DOCUMENT_COUNT_ALERT_TYPE_ID], privileges: { all: { - app: ['infra', 'kibana'], + app: ['infra', 'logs', 'kibana'], catalogue: ['infralogging'], api: ['infra'], savedObject: { all: ['infrastructure-ui-source'], read: [], }, + alerting: { + all: [LOG_DOCUMENT_COUNT_ALERT_TYPE_ID], + }, ui: ['show', 'configureSource', 'save'], }, read: { - app: ['infra', 'kibana'], + app: ['infra', 'logs', 'kibana'], catalogue: ['infralogging'], api: ['infra'], + alerting: { + all: [LOG_DOCUMENT_COUNT_ALERT_TYPE_ID], + }, savedObject: { all: [], read: ['infrastructure-ui-source'], diff --git a/x-pack/plugins/infra/server/graphql/source_status/resolvers.ts b/x-pack/plugins/infra/server/graphql/source_status/resolvers.ts index 848d66058e64c..bd92dd0f7da8b 100644 --- a/x-pack/plugins/infra/server/graphql/source_status/resolvers.ts +++ b/x-pack/plugins/infra/server/graphql/source_status/resolvers.ts @@ -73,7 +73,7 @@ export const createSourceStatusResolvers = (libs: { return await libs.sourceStatus.hasLogAlias(req, source.id); }, async logIndicesExist(source, args, { req }) { - return await libs.sourceStatus.hasLogIndices(req, source.id); + return (await libs.sourceStatus.getLogIndexStatus(req, source.id)) !== 'missing'; }, async logIndices(source, args, { req }) { return await libs.sourceStatus.getLogIndexNames(req, source.id); diff --git a/x-pack/plugins/infra/server/lib/adapters/framework/adapter_types.ts b/x-pack/plugins/infra/server/lib/adapters/framework/adapter_types.ts index 018e5098a4291..117749ae87bbe 100644 --- a/x-pack/plugins/infra/server/lib/adapters/framework/adapter_types.ts +++ b/x-pack/plugins/infra/server/lib/adapters/framework/adapter_types.ts @@ -38,6 +38,7 @@ export interface CallWithRequestParams extends GenericParams { fields?: string | string[]; path?: string; query?: string | object; + track_total_hits?: boolean | number; } export type InfraResponse = Lifecycle.ReturnValue; diff --git a/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts index 9bc58604f12a5..2a61e64c94fcd 100644 --- a/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts @@ -5,7 +5,7 @@ */ import { RequestHandlerContext } from 'src/core/server'; -import { InfraSourceStatusAdapter } from '../../source_status'; +import { InfraSourceStatusAdapter, SourceIndexStatus } from '../../source_status'; import { InfraDatabaseGetIndicesResponse } from '../framework'; import { KibanaFramework } from '../framework/kibana_framework_adapter'; @@ -40,7 +40,10 @@ export class InfraElasticsearchSourceStatusAdapter implements InfraSourceStatusA }); } - public async hasIndices(requestContext: RequestHandlerContext, indexNames: string) { + public async getIndexStatus( + requestContext: RequestHandlerContext, + indexNames: string + ): Promise { return await this.framework .callWithRequest(requestContext, 'search', { ignore_unavailable: true, @@ -48,12 +51,23 @@ export class InfraElasticsearchSourceStatusAdapter implements InfraSourceStatusA index: indexNames, size: 0, terminate_after: 1, + track_total_hits: 1, }) .then( - (response) => response._shards.total > 0, + (response) => { + if (response._shards.total <= 0) { + return 'missing'; + } + + if (response.hits.total.value > 0) { + return 'available'; + } + + return 'empty'; + }, (err) => { if (err.status === 404) { - return false; + return 'missing'; } throw err; } diff --git a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_alert_type.ts b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_alert_type.ts index 85b38f48d9f22..fa5277cb09987 100644 --- a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_alert_type.ts +++ b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_alert_type.ts @@ -40,7 +40,7 @@ export const registerMetricInventoryThresholdAlertType = (libs: InfraBackendLibs }, defaultActionGroupId: FIRED_ACTIONS.id, actionGroups: [FIRED_ACTIONS], - producer: 'metrics', + producer: 'infrastructure', executor: createInventoryMetricThresholdExecutor(libs), actionVariables: { context: [ diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_alert_type.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_alert_type.ts index 529a1d176c437..51a127e9345b4 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_alert_type.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_alert_type.ts @@ -117,6 +117,6 @@ export function registerMetricThresholdAlertType(libs: InfraBackendLibs) { { name: 'threshold', description: thresholdActionVariableDescription }, ], }, - producer: 'metrics', + producer: 'infrastructure', }; } diff --git a/x-pack/plugins/infra/server/lib/log_analysis/common.ts b/x-pack/plugins/infra/server/lib/log_analysis/common.ts index 218281d875a46..4d2be94c7cd62 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/common.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/common.ts @@ -14,7 +14,6 @@ import { logEntryDatasetsResponseRT, } from './queries/log_entry_data_sets'; import { decodeOrThrow } from '../../../common/runtime_types'; -import { NoLogAnalysisResultsIndexError } from './errors'; import { startTracingSpan, TracingSpan } from '../../../common/performance_tracing'; export async function fetchMlJob(mlAnomalyDetectors: MlAnomalyDetectors, jobId: string) { @@ -67,16 +66,8 @@ export async function getLogEntryDatasets( ) ); - if (logEntryDatasetsResponse._shards.total === 0) { - throw new NoLogAnalysisResultsIndexError( - `Failed to find ml indices for jobs: ${jobIds.join(', ')}.` - ); - } - - const { - after_key: afterKey, - buckets: latestBatchBuckets, - } = logEntryDatasetsResponse.aggregations.dataset_buckets; + const { after_key: afterKey, buckets: latestBatchBuckets = [] } = + logEntryDatasetsResponse.aggregations?.dataset_buckets ?? {}; logEntryDatasetBuckets = [...logEntryDatasetBuckets, ...latestBatchBuckets]; afterLatestBatchKey = afterKey; diff --git a/x-pack/plugins/infra/server/lib/log_analysis/errors.ts b/x-pack/plugins/infra/server/lib/log_analysis/errors.ts index 09fee8844fbc5..a6d0db25084e8 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/errors.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/errors.ts @@ -6,13 +6,6 @@ /* eslint-disable max-classes-per-file */ -export class NoLogAnalysisResultsIndexError extends Error { - constructor(message?: string) { - super(message); - Object.setPrototypeOf(this, new.target.prototype); - } -} - export class NoLogAnalysisMlJobError extends Error { constructor(message?: string) { super(message); diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts index a455a03d936a5..ff9e3c7d2167c 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts @@ -15,11 +15,7 @@ import { import { startTracingSpan } from '../../../common/performance_tracing'; import { decodeOrThrow } from '../../../common/runtime_types'; import type { MlAnomalyDetectors, MlSystem } from '../../types'; -import { - InsufficientLogAnalysisMlJobConfigurationError, - NoLogAnalysisResultsIndexError, - UnknownCategoryError, -} from './errors'; +import { InsufficientLogAnalysisMlJobConfigurationError, UnknownCategoryError } from './errors'; import { createLogEntryCategoriesQuery, logEntryCategoriesResponseRT, @@ -235,38 +231,33 @@ async function fetchTopLogEntryCategories( const esSearchSpan = finalizeEsSearchSpan(); - if (topLogEntryCategoriesResponse._shards.total === 0) { - throw new NoLogAnalysisResultsIndexError( - `Failed to find ml result index for job ${logEntryCategoriesCountJobId}.` - ); - } - - const topLogEntryCategories = topLogEntryCategoriesResponse.aggregations.terms_category_id.buckets.map( - (topCategoryBucket) => { - const maximumAnomalyScoresByDataset = topCategoryBucket.filter_record.terms_dataset.buckets.reduce< - Record - >( - (accumulatedMaximumAnomalyScores, datasetFromRecord) => ({ - ...accumulatedMaximumAnomalyScores, - [datasetFromRecord.key]: datasetFromRecord.maximum_record_score.value ?? 0, - }), - {} - ); - - return { - categoryId: parseCategoryId(topCategoryBucket.key), - logEntryCount: topCategoryBucket.filter_model_plot.sum_actual.value ?? 0, - datasets: topCategoryBucket.filter_model_plot.terms_dataset.buckets - .map((datasetBucket) => ({ - name: datasetBucket.key, - maximumAnomalyScore: maximumAnomalyScoresByDataset[datasetBucket.key] ?? 0, - })) - .sort(compareDatasetsByMaximumAnomalyScore) - .reverse(), - maximumAnomalyScore: topCategoryBucket.filter_record.maximum_record_score.value ?? 0, - }; - } - ); + const topLogEntryCategories = + topLogEntryCategoriesResponse.aggregations?.terms_category_id.buckets.map( + (topCategoryBucket) => { + const maximumAnomalyScoresByDataset = topCategoryBucket.filter_record.terms_dataset.buckets.reduce< + Record + >( + (accumulatedMaximumAnomalyScores, datasetFromRecord) => ({ + ...accumulatedMaximumAnomalyScores, + [datasetFromRecord.key]: datasetFromRecord.maximum_record_score.value ?? 0, + }), + {} + ); + + return { + categoryId: parseCategoryId(topCategoryBucket.key), + logEntryCount: topCategoryBucket.filter_model_plot.sum_actual.value ?? 0, + datasets: topCategoryBucket.filter_model_plot.terms_dataset.buckets + .map((datasetBucket) => ({ + name: datasetBucket.key, + maximumAnomalyScore: maximumAnomalyScoresByDataset[datasetBucket.key] ?? 0, + })) + .sort(compareDatasetsByMaximumAnomalyScore) + .reverse(), + maximumAnomalyScore: topCategoryBucket.filter_record.maximum_record_score.value ?? 0, + }; + } + ) ?? []; return { topLogEntryCategories, diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_rate_analysis.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_rate_analysis.ts index 7bfc85ba78a0e..ce3acd0dba8cf 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_rate_analysis.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_rate_analysis.ts @@ -4,10 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pipe } from 'fp-ts/lib/pipeable'; -import { map, fold } from 'fp-ts/lib/Either'; -import { identity } from 'fp-ts/lib/function'; -import { throwErrors, createPlainError } from '../../../common/runtime_types'; +import { decodeOrThrow } from '../../../common/runtime_types'; import { logRateModelPlotResponseRT, createLogEntryRateQuery, @@ -15,7 +12,6 @@ import { CompositeTimestampPartitionKey, } from './queries'; import { getJobId } from '../../../common/log_analysis'; -import { NoLogAnalysisResultsIndexError } from './errors'; import type { MlSystem } from '../../types'; const COMPOSITE_AGGREGATION_BATCH_SIZE = 1000; @@ -50,22 +46,14 @@ export async function getLogEntryRateBuckets( ) ); - if (mlModelPlotResponse._shards.total === 0) { - throw new NoLogAnalysisResultsIndexError( - `Failed to query ml result index for job ${logRateJobId}.` - ); - } - - const { after_key: afterKey, buckets: latestBatchBuckets } = pipe( - logRateModelPlotResponseRT.decode(mlModelPlotResponse), - map((response) => response.aggregations.timestamp_partition_buckets), - fold(throwErrors(createPlainError), identity) - ); + const { after_key: afterKey, buckets: latestBatchBuckets = [] } = + decodeOrThrow(logRateModelPlotResponseRT)(mlModelPlotResponse).aggregations + ?.timestamp_partition_buckets ?? {}; mlModelPlotBuckets = [...mlModelPlotBuckets, ...latestBatchBuckets]; afterLatestBatchKey = afterKey; - if (latestBatchBuckets.length < COMPOSITE_AGGREGATION_BATCH_SIZE) { + if (afterKey == null || latestBatchBuckets.length < COMPOSITE_AGGREGATION_BATCH_SIZE) { break; } } diff --git a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_data_sets.ts b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_data_sets.ts index 7627ccd8c4996..53971a91d86b1 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_data_sets.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_data_sets.ts @@ -67,7 +67,7 @@ export type LogEntryDatasetBucket = rt.TypeOf; export const logEntryDatasetsResponseRT = rt.intersection([ commonSearchSuccessResponseFieldsRT, - rt.type({ + rt.partial({ aggregations: rt.type({ dataset_buckets: rt.intersection([ rt.type({ diff --git a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_rate.ts b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_rate.ts index 52edcf09cdfc2..e82dd8ef4443c 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_rate.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_rate.ts @@ -162,7 +162,7 @@ export const logRateModelPlotBucketRT = rt.type({ export type LogRateModelPlotBucket = rt.TypeOf; -export const logRateModelPlotResponseRT = rt.type({ +export const logRateModelPlotResponseRT = rt.partial({ aggregations: rt.type({ timestamp_partition_buckets: rt.intersection([ rt.type({ diff --git a/x-pack/plugins/infra/server/lib/log_analysis/queries/top_log_entry_categories.ts b/x-pack/plugins/infra/server/lib/log_analysis/queries/top_log_entry_categories.ts index 355dde9ec7c4a..5d3d9bc8b4036 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/queries/top_log_entry_categories.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/queries/top_log_entry_categories.ts @@ -159,7 +159,7 @@ export type LogEntryCategoryBucket = rt.TypeOf; export const topLogEntryCategoriesResponseRT = rt.intersection([ commonSearchSuccessResponseFieldsRT, - rt.type({ + rt.partial({ aggregations: rt.type({ terms_category_id: rt.type({ buckets: rt.array(logEntryCategoryBucketRT), diff --git a/x-pack/plugins/infra/server/lib/snapshot/snapshot.ts b/x-pack/plugins/infra/server/lib/snapshot/snapshot.ts index 9ca10d5e39da7..5f359b0523d9f 100644 --- a/x-pack/plugins/infra/server/lib/snapshot/snapshot.ts +++ b/x-pack/plugins/infra/server/lib/snapshot/snapshot.ts @@ -86,7 +86,7 @@ const requestGroupedNodes = async ( aggregations: { nodes: { composite: { - size: SNAPSHOT_COMPOSITE_REQUEST_SIZE, + size: options.overrideCompositeSize || SNAPSHOT_COMPOSITE_REQUEST_SIZE, sources: getGroupedNodesSources(options), }, aggs: { @@ -142,7 +142,7 @@ const requestNodeMetrics = async ( aggregations: { nodes: { composite: { - size: SNAPSHOT_COMPOSITE_REQUEST_SIZE, + size: options.overrideCompositeSize || SNAPSHOT_COMPOSITE_REQUEST_SIZE, sources: getMetricsSources(options), }, aggregations: { diff --git a/x-pack/plugins/infra/server/lib/source_status.ts b/x-pack/plugins/infra/server/lib/source_status.ts index 9bb953845e5a1..c383d01933562 100644 --- a/x-pack/plugins/infra/server/lib/source_status.ts +++ b/x-pack/plugins/infra/server/lib/source_status.ts @@ -69,19 +69,19 @@ export class InfraSourceStatus { ); return hasAlias; } - public async hasLogIndices( + public async getLogIndexStatus( requestContext: RequestHandlerContext, sourceId: string - ): Promise { + ): Promise { const sourceConfiguration = await this.libs.sources.getSourceConfiguration( requestContext.core.savedObjects.client, sourceId ); - const hasIndices = await this.adapter.hasIndices( + const indexStatus = await this.adapter.getIndexStatus( requestContext, sourceConfiguration.configuration.logAlias ); - return hasIndices; + return indexStatus; } public async hasMetricIndices( requestContext: RequestHandlerContext, @@ -91,16 +91,21 @@ export class InfraSourceStatus { requestContext.core.savedObjects.client, sourceId ); - const hasIndices = await this.adapter.hasIndices( + const indexStatus = await this.adapter.getIndexStatus( requestContext, sourceConfiguration.configuration.metricAlias ); - return hasIndices; + return indexStatus !== 'missing'; } } +export type SourceIndexStatus = 'missing' | 'empty' | 'available'; + export interface InfraSourceStatusAdapter { getIndexNames(requestContext: RequestHandlerContext, aliasName: string): Promise; hasAlias(requestContext: RequestHandlerContext, aliasName: string): Promise; - hasIndices(requestContext: RequestHandlerContext, indexNames: string): Promise; + getIndexStatus( + requestContext: RequestHandlerContext, + indexNames: string + ): Promise; } diff --git a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_anomalies_datasets.ts b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_anomalies_datasets.ts index d3d0862eee9aa..f1f1a1681a901 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_anomalies_datasets.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_anomalies_datasets.ts @@ -12,10 +12,7 @@ import { } from '../../../../common/http_api/log_analysis'; import { createValidationFunction } from '../../../../common/runtime_types'; import type { InfraBackendLibs } from '../../../lib/infra_types'; -import { - getLogEntryAnomaliesDatasets, - NoLogAnalysisResultsIndexError, -} from '../../../lib/log_analysis'; +import { getLogEntryAnomaliesDatasets } from '../../../lib/log_analysis'; import { assertHasInfraMlPlugins } from '../../../utils/request_context'; export const initGetLogEntryAnomaliesDatasetsRoute = ({ framework }: InfraBackendLibs) => { @@ -58,10 +55,6 @@ export const initGetLogEntryAnomaliesDatasetsRoute = ({ framework }: InfraBacken throw error; } - if (error instanceof NoLogAnalysisResultsIndexError) { - return response.notFound({ body: { message: error.message } }); - } - return response.customError({ statusCode: error.statusCode ?? 500, body: { diff --git a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_categories.ts b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_categories.ts index f9f31f28dffeb..f57132ef1b505 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_categories.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_categories.ts @@ -12,10 +12,7 @@ import { } from '../../../../common/http_api/log_analysis'; import { createValidationFunction } from '../../../../common/runtime_types'; import type { InfraBackendLibs } from '../../../lib/infra_types'; -import { - getTopLogEntryCategories, - NoLogAnalysisResultsIndexError, -} from '../../../lib/log_analysis'; +import { getTopLogEntryCategories } from '../../../lib/log_analysis'; import { assertHasInfraMlPlugins } from '../../../utils/request_context'; export const initGetLogEntryCategoriesRoute = ({ framework }: InfraBackendLibs) => { @@ -69,10 +66,6 @@ export const initGetLogEntryCategoriesRoute = ({ framework }: InfraBackendLibs) throw error; } - if (error instanceof NoLogAnalysisResultsIndexError) { - return response.notFound({ body: { message: error.message } }); - } - return response.customError({ statusCode: error.statusCode ?? 500, body: { diff --git a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_category_datasets.ts b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_category_datasets.ts index 69b1e942464fd..b99ff920f81e4 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_category_datasets.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_category_datasets.ts @@ -12,10 +12,7 @@ import { } from '../../../../common/http_api/log_analysis'; import { createValidationFunction } from '../../../../common/runtime_types'; import type { InfraBackendLibs } from '../../../lib/infra_types'; -import { - getLogEntryCategoryDatasets, - NoLogAnalysisResultsIndexError, -} from '../../../lib/log_analysis'; +import { getLogEntryCategoryDatasets } from '../../../lib/log_analysis'; import { assertHasInfraMlPlugins } from '../../../utils/request_context'; export const initGetLogEntryCategoryDatasetsRoute = ({ framework }: InfraBackendLibs) => { @@ -58,10 +55,6 @@ export const initGetLogEntryCategoryDatasetsRoute = ({ framework }: InfraBackend throw error; } - if (error instanceof NoLogAnalysisResultsIndexError) { - return response.notFound({ body: { message: error.message } }); - } - return response.customError({ statusCode: error.statusCode ?? 500, body: { diff --git a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_category_examples.ts b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_category_examples.ts index 8baeaac3d1699..11098ebe5c65b 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_category_examples.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_category_examples.ts @@ -12,10 +12,7 @@ import { } from '../../../../common/http_api/log_analysis'; import { createValidationFunction } from '../../../../common/runtime_types'; import type { InfraBackendLibs } from '../../../lib/infra_types'; -import { - getLogEntryCategoryExamples, - NoLogAnalysisResultsIndexError, -} from '../../../lib/log_analysis'; +import { getLogEntryCategoryExamples } from '../../../lib/log_analysis'; import { assertHasInfraMlPlugins } from '../../../utils/request_context'; export const initGetLogEntryCategoryExamplesRoute = ({ framework, sources }: InfraBackendLibs) => { @@ -68,10 +65,6 @@ export const initGetLogEntryCategoryExamplesRoute = ({ framework, sources }: Inf throw error; } - if (error instanceof NoLogAnalysisResultsIndexError) { - return response.notFound({ body: { message: error.message } }); - } - return response.customError({ statusCode: error.statusCode ?? 500, body: { diff --git a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_examples.ts b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_examples.ts index be4caee769506..7838a64a6045e 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_examples.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_examples.ts @@ -7,7 +7,7 @@ import Boom from 'boom'; import { createValidationFunction } from '../../../../common/runtime_types'; import { InfraBackendLibs } from '../../../lib/infra_types'; -import { NoLogAnalysisResultsIndexError, getLogEntryExamples } from '../../../lib/log_analysis'; +import { getLogEntryExamples } from '../../../lib/log_analysis'; import { assertHasInfraMlPlugins } from '../../../utils/request_context'; import { getLogEntryExamplesRequestPayloadRT, @@ -68,10 +68,6 @@ export const initGetLogEntryExamplesRoute = ({ framework, sources }: InfraBacken throw error; } - if (error instanceof NoLogAnalysisResultsIndexError) { - return response.notFound({ body: { message: error.message } }); - } - return response.customError({ statusCode: error.statusCode ?? 500, body: { diff --git a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_rate.ts b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_rate.ts index 3b05f6ed23aae..cd23c0193e291 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_rate.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_rate.ts @@ -13,7 +13,7 @@ import { GetLogEntryRateSuccessResponsePayload, } from '../../../../common/http_api/log_analysis'; import { createValidationFunction } from '../../../../common/runtime_types'; -import { NoLogAnalysisResultsIndexError, getLogEntryRateBuckets } from '../../../lib/log_analysis'; +import { getLogEntryRateBuckets } from '../../../lib/log_analysis'; import { assertHasInfraMlPlugins } from '../../../utils/request_context'; export const initGetLogEntryRateRoute = ({ framework }: InfraBackendLibs) => { @@ -56,10 +56,6 @@ export const initGetLogEntryRateRoute = ({ framework }: InfraBackendLibs) => { throw error; } - if (error instanceof NoLogAnalysisResultsIndexError) { - return response.notFound({ body: { message: error.message } }); - } - return response.customError({ statusCode: error.statusCode ?? 500, body: { diff --git a/x-pack/plugins/infra/server/routes/log_sources/status.ts b/x-pack/plugins/infra/server/routes/log_sources/status.ts index 4cd85ecfe23c1..193c3541d740b 100644 --- a/x-pack/plugins/infra/server/routes/log_sources/status.ts +++ b/x-pack/plugins/infra/server/routes/log_sources/status.ts @@ -31,16 +31,17 @@ export const initLogSourceStatusRoutes = ({ const { sourceId } = request.params; try { - const logIndicesExist = await sourceStatus.hasLogIndices(requestContext, sourceId); - const logIndexFields = logIndicesExist - ? await fields.getFields(requestContext, sourceId, InfraIndexType.LOGS) - : []; + const logIndexStatus = await sourceStatus.getLogIndexStatus(requestContext, sourceId); + const logIndexFields = + logIndexStatus !== 'missing' + ? await fields.getFields(requestContext, sourceId, InfraIndexType.LOGS) + : []; return response.ok({ body: getLogSourceStatusSuccessResponsePayloadRT.encode({ data: { - logIndicesExist, logIndexFields, + logIndexStatus, }, }), }); diff --git a/x-pack/plugins/infra/server/routes/snapshot/index.ts b/x-pack/plugins/infra/server/routes/snapshot/index.ts index 7c81c6eef675f..e99103080463e 100644 --- a/x-pack/plugins/infra/server/routes/snapshot/index.ts +++ b/x-pack/plugins/infra/server/routes/snapshot/index.ts @@ -40,6 +40,7 @@ export const initSnapshotRoute = (libs: InfraBackendLibs) => { accountId, region, includeTimeseries, + overrideCompositeSize, } = pipe( SnapshotRequestRT.decode(request.body), fold(throwErrors(Boom.badRequest), identity) @@ -59,6 +60,7 @@ export const initSnapshotRoute = (libs: InfraBackendLibs) => { metrics, timerange, includeTimeseries, + overrideCompositeSize, }; const searchES = ( diff --git a/x-pack/plugins/infra/server/routes/source/index.ts b/x-pack/plugins/infra/server/routes/source/index.ts index 2843897071e19..6069d3a35e54c 100644 --- a/x-pack/plugins/infra/server/routes/source/index.ts +++ b/x-pack/plugins/infra/server/routes/source/index.ts @@ -37,9 +37,9 @@ export const initSourceRoute = (libs: InfraBackendLibs) => { try { const { type, sourceId } = request.params; - const [source, logIndicesExist, metricIndicesExist, indexFields] = await Promise.all([ + const [source, logIndexStatus, metricIndicesExist, indexFields] = await Promise.all([ libs.sources.getSourceConfiguration(requestContext.core.savedObjects.client, sourceId), - libs.sourceStatus.hasLogIndices(requestContext, sourceId), + libs.sourceStatus.getLogIndexStatus(requestContext, sourceId), libs.sourceStatus.hasMetricIndices(requestContext, sourceId), libs.fields.getFields(requestContext, sourceId, typeToInfraIndexType(type)), ]); @@ -49,7 +49,7 @@ export const initSourceRoute = (libs: InfraBackendLibs) => { } const status = { - logIndicesExist, + logIndicesExist: logIndexStatus !== 'missing', metricIndicesExist, indexFields, }; @@ -83,7 +83,7 @@ export const initSourceRoute = (libs: InfraBackendLibs) => { const hasData = type === 'metrics' ? await libs.sourceStatus.hasMetricIndices(requestContext, sourceId) - : await libs.sourceStatus.hasLogIndices(requestContext, sourceId); + : (await libs.sourceStatus.getLogIndexStatus(requestContext, sourceId)) !== 'missing'; return response.ok({ body: { hasData }, diff --git a/x-pack/plugins/ingest_manager/README.md b/x-pack/plugins/ingest_manager/README.md index a523ddeb7c499..9fd23e3d41dde 100644 --- a/x-pack/plugins/ingest_manager/README.md +++ b/x-pack/plugins/ingest_manager/README.md @@ -45,63 +45,26 @@ One common development workflow is: This plugin follows the `common`, `server`, `public` structure from the [Architecture Style Guide ](https://github.com/elastic/kibana/blob/master/style_guides/architecture_style_guide.md#file-and-folder-structure). We also follow the pattern of developing feature branches under your personal fork of Kibana. -### API Tests +### Tests -#### Ingest & Fleet +#### API integration tests -1. In one terminal, change to the `x-pack` directory and start the test server with +You need to have `docker` to run ingest manager api integration tests - ``` - node scripts/functional_tests_server.js --config test/api_integration/config.ts - ``` +1. In one terminal, run the tests from the Kibana root directory with -1. in a second terminal, run the tests from the Kibana root directory with ``` - node scripts/functional_test_runner.js --config x-pack/test/api_integration/config.ts + INGEST_MANAGEMENT_PACKAGE_REGISTRY_PORT=12345 yarn test:ftr:server --config x-pack/test/ingest_manager_api_integration/config.ts ``` -#### EPM - -1. In one terminal, change to the `x-pack` directory and start the test server with +1. in a second terminal, run the tests from the Kibana root directory with ``` - node scripts/functional_tests_server.js --config test/epm_api_integration/config.ts + INGEST_MANAGEMENT_PACKAGE_REGISTRY_PORT=12345 yarn test:ftr:runner --config x-pack/test/ingest_manager_api_integration/config.ts ``` -1. in a second terminal, run the tests from the Kibana root directory with + Optionally you can filter which tests you want to run using `--grep` + ``` - node scripts/functional_test_runner.js --config x-pack/test/epm_api_integration/config.ts + INGEST_MANAGEMENT_PACKAGE_REGISTRY_PORT=12345 yarn test:ftr:runner --config x-pack/test/ingest_manager_api_integration/config.ts --grep='fleet' ``` - -### Staying up-to-date with `master` - -While we're developing in the `feature-ingest` feature branch, here's is more information on keeping up to date with upstream kibana. - -
- merge upstream master into feature-ingest - -```bash -## checkout feature branch to your fork -git checkout -B feature-ingest origin/feature-ingest - -## make sure your feature branch is current with upstream feature branch -git pull upstream feature-ingest - -## pull in changes from upstream master -git pull upstream master - -## push changes to your remote -git push origin - -# /!\ Open a DRAFT PR /!\ -# Normal PRs will re-notify authors of commits already merged -# Draft PR will trigger CI run. Once CI is green ... -# /!\ DO NOT USE THE GITHUB UI TO MERGE THE PR /!\ - -## push your changes to upstream feature branch from the terminal; not GitHub UI -git push upstream -``` - -
- -See https://github.com/elastic/kibana/pull/37950 for an example. diff --git a/x-pack/plugins/ingest_manager/common/openapi/spec_oas3.json b/x-pack/plugins/ingest_manager/common/openapi/spec_oas3.json index 4b10dab5d1ae5..cfae2c450c824 100644 --- a/x-pack/plugins/ingest_manager/common/openapi/spec_oas3.json +++ b/x-pack/plugins/ingest_manager/common/openapi/spec_oas3.json @@ -922,7 +922,7 @@ }, "parameters": [] }, - "/packageConfigs": { + "/package_configs": { "get": { "summary": "PackageConfigs - List", "tags": [], @@ -1237,7 +1237,7 @@ ] } }, - "/packageConfigs/{packageConfigId}": { + "/package_configs/{packageConfigId}": { "get": { "summary": "PackageConfigs - Info", "tags": [], @@ -4203,6 +4203,7 @@ "FAILED", "STOPPING", "STOPPED", + "DEGRADED", "DATA_DUMP", "ACKNOWLEDGED", "UNKNOWN" diff --git a/x-pack/plugins/ingest_manager/common/types/index.ts b/x-pack/plugins/ingest_manager/common/types/index.ts index d7edc04a35799..7acef263f973a 100644 --- a/x-pack/plugins/ingest_manager/common/types/index.ts +++ b/x-pack/plugins/ingest_manager/common/types/index.ts @@ -22,8 +22,7 @@ export interface IngestManagerConfigType { host?: string; ca_sha256?: string; }; - agentConfigRollupRateLimitIntervalMs: number; - agentConfigRollupRateLimitRequestPerInterval: number; + agentConfigRolloutConcurrency: number; }; } diff --git a/x-pack/plugins/ingest_manager/common/types/models/agent.ts b/x-pack/plugins/ingest_manager/common/types/models/agent.ts index d3789c58a2c22..f31d33e73c76f 100644 --- a/x-pack/plugins/ingest_manager/common/types/models/agent.ts +++ b/x-pack/plugins/ingest_manager/common/types/models/agent.ts @@ -53,6 +53,7 @@ export interface NewAgentEvent { | 'FAILED' | 'STOPPING' | 'STOPPED' + | 'DEGRADED' // Action results | 'DATA_DUMP' // Actions diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_flyout.tsx index 03c70f71529c9..110d6de02c12b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_flyout.tsx @@ -73,7 +73,7 @@ export const AlphaFlyout: React.FunctionComponent = ({ onClose }) => { - + = ({ kibanaUrl, apiKey, kibanaCASha256, }) => { - const command = ` -./elastic-agent enroll ${kibanaUrl} ${apiKey.api_key}${ + const enrollArgs = `${kibanaUrl} ${apiKey.api_key}${ kibanaCASha256 ? ` --ca_sha256=${kibanaCASha256}` : '' - } + }`; + const macOsLinuxTarCommand = `./elastic-agent enroll ${enrollArgs} ./elastic-agent run`; + + const linuxDebRpmCommand = `./elastic-agent enroll ${enrollArgs} +systemctl enable elastic-agent +systemctl start elastic-agent`; + + const windowsCommand = `./elastic-agent enroll ${enrollArgs} +./install-service-elastic-agent.ps1`; + return ( <> + + + +

+ +

+
+ + + {windowsCommand} + + + +

+ +

+
+ + + {linuxDebRpmCommand} + + + +

+ +

+
+ + + agent enroll, + command: ./elastic-agent run, }} /> - - -
{command}
+ + + {macOsLinuxTarCommand} - - - {(copy) => ( - - - - )} - ); }; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx index c79077e68afb0..e8081e097fd42 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx @@ -254,7 +254,7 @@ export const SettingFlyout: React.FunctionComponent = ({ onClose }) => { - + = ({ childr + + + } onCancel={closeModal} onConfirm={copyAgentConfig} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx index ad04e78bdcd11..b60c36b282a0d 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx @@ -13,10 +13,10 @@ import { EuiFormRow, EuiHorizontalRule, EuiSpacer, - EuiSwitch, EuiText, EuiComboBox, EuiIconTip, + EuiCheckbox, EuiCheckboxGroup, EuiButton, } from '@elastic/eui'; @@ -221,16 +221,48 @@ export const AgentConfigForm: React.FunctionComponent = ({ options={[ { id: 'logs', - label: i18n.translate( - 'xpack.ingestManager.agentConfigForm.monitoringLogsFieldLabel', - { defaultMessage: 'Collect agent logs' } + label: ( + <> + {' '} + + ), }, { id: 'metrics', - label: i18n.translate( - 'xpack.ingestManager.agentConfigForm.monitoringMetricsFieldLabel', - { defaultMessage: 'Collect agent metrics' } + label: ( + <> + {' '} + + ), }, ]} @@ -315,16 +347,14 @@ export const AgentConfigForm: React.FunctionComponent = ({ {!isEditing ? ( - - + } > - = ({ )} position="right" type="iInCircle" + color="subdued" /> } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_yaml_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_yaml_flyout.tsx index 6cf60fe1dc507..9c2d09b02665f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_yaml_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_yaml_flyout.tsx @@ -72,7 +72,7 @@ export const ConfigYamlFlyout = memo<{ configId: string; onClose: () => void }>( - + - + {agentConfig.name}, - }} - /> + values={{ + configName: {agentConfig.name}, + }} + /> +
- {agentConfig?.name || '-'} + + {agentConfig?.name || '-'} + ) : undefined; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_config.tsx index 98f04dbd92659..fd3a64bc760a0 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_config.tsx @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import React, { useState, Fragment, memo, useMemo } from 'react'; +import styled from 'styled-components'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiFlexGrid, @@ -21,6 +22,10 @@ import { } from '../services'; import { PackageConfigInputVarField } from './package_config_input_var_field'; +const FlexItemWithMaxWidth = styled(EuiFlexItem)` + max-width: calc(50% - ${(props) => props.theme.eui.euiSizeL}); +`; + export const PackageConfigInputConfig: React.FunctionComponent<{ packageInputVars?: RegistryVarsEntry[]; packageConfigInput: PackageConfigInput; @@ -88,7 +93,7 @@ export const PackageConfigInputConfig: React.FunctionComponent<{ - + {requiredVars.map((varDef) => { const { name: varName, type: varType } = varDef; @@ -176,7 +181,7 @@ export const PackageConfigInputConfig: React.FunctionComponent<{ ) : null} - + ); } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_define_package_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_define_package_config.tsx index a04d023ebcc48..f487b4e5235e7 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_define_package_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_define_package_config.tsx @@ -47,9 +47,17 @@ export const StepDefinePackageConfig: React.FunctionComponent<{ .sort(); updatePackageConfig({ - name: `${packageInfo.name}-${ - dsWithMatchingNames.length ? dsWithMatchingNames[dsWithMatchingNames.length - 1] + 1 : 1 - }`, + name: + // For Endpoint packages, the user must fill in the name, thus we don't attempt to generate + // a default one here. + // FIXME: Improve package configs name uniqueness - https://github.com/elastic/kibana/issues/72948 + packageInfo.name !== 'endpoint' + ? `${packageInfo.name}-${ + dsWithMatchingNames.length + ? dsWithMatchingNames[dsWithMatchingNames.length - 1] + 1 + : 1 + }` + : '', package: { name: packageInfo.name, title: packageInfo.title, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_config.tsx index 91c80b7eee4c8..6f06530100d71 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_config.tsx @@ -3,17 +3,19 @@ * 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, Fragment } from 'react'; +import React, { useEffect, useState } from 'react'; +import styled from 'styled-components'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiFlexGroup, EuiFlexItem, - EuiSelectable, - EuiSpacer, + EuiComboBox, + EuiComboBoxOptionOption, EuiTextColor, EuiPortal, - EuiButtonEmpty, + EuiFormRow, + EuiLink, } from '@elastic/eui'; import { Error } from '../../../components'; import { AgentConfig, PackageInfo, GetAgentConfigsResponseItem } from '../../../types'; @@ -23,9 +25,30 @@ import { useGetAgentConfigs, sendGetOneAgentConfig, useCapabilities, + useFleetStatus, } from '../../../hooks'; import { CreateAgentConfigFlyout } from '../list_page/components'; +const AgentConfigWrapper = styled(EuiFormRow)` + .euiFormRow__label { + width: 100%; + } +`; + +// Custom styling for drop down list items due to: +// 1) the max-width and overflow properties is added to prevent long config +// names/descriptions from overflowing the flex items +// 2) max-width is built from the grow property on the flex items because the value +// changes based on if Fleet is enabled/setup or not +const AgentConfigNameColumn = styled(EuiFlexItem)` + max-width: ${(props) => `${((props.grow as number) / 9) * 100}%`}; + overflow: hidden; +`; +const AgentConfigDescriptionColumn = styled(EuiFlexItem)` + max-width: ${(props) => `${((props.grow as number) / 9) * 100}%`}; + overflow: hidden; +`; + export const StepSelectConfig: React.FunctionComponent<{ pkgkey: string; updatePackageInfo: (packageInfo: PackageInfo | undefined) => void; @@ -33,6 +56,8 @@ export const StepSelectConfig: React.FunctionComponent<{ updateAgentConfig: (config: AgentConfig | undefined) => void; setIsLoadingSecondStep: (isLoading: boolean) => void; }> = ({ pkgkey, updatePackageInfo, agentConfig, updateAgentConfig, setIsLoadingSecondStep }) => { + const { isReady: isFleetReady } = useFleetStatus(); + // Selected config state const [selectedConfigId, setSelectedConfigId] = useState( agentConfig ? agentConfig.id : undefined @@ -106,6 +131,40 @@ export const StepSelectConfig: React.FunctionComponent<{ } }, [selectedConfigId, agentConfig, updateAgentConfig, setIsLoadingSecondStep]); + const agentConfigOptions: Array> = packageInfoData + ? agentConfigs.map((agentConf) => { + const alreadyHasLimitedPackage = + (isLimitedPackage && + doesAgentConfigAlreadyIncludePackage(agentConf, packageInfoData.response.name)) || + false; + return { + label: agentConf.name, + value: agentConf.id, + disabled: alreadyHasLimitedPackage, + 'data-test-subj': 'agentConfigItem', + }; + }) + : []; + + const selectedConfigOption = agentConfigOptions.find( + (option) => option.value === selectedConfigId + ); + + // Try to select default agent config + useEffect(() => { + if (!selectedConfigId && agentConfigs.length && agentConfigOptions.length) { + const defaultAgentConfig = agentConfigs.find((config) => config.is_default); + if (defaultAgentConfig) { + const defaultAgentConfigOption = agentConfigOptions.find( + (option) => option.value === defaultAgentConfig.id + ); + if (defaultAgentConfigOption && !defaultAgentConfigOption.disabled) { + setSelectedConfigId(defaultAgentConfig.id); + } + } + } + }, [agentConfigs, agentConfigOptions, selectedConfigId]); + // Display package error if there is one if (packageInfoError) { return ( @@ -154,77 +213,95 @@ export const StepSelectConfig: React.FunctionComponent<{ ) : null} - { - const alreadyHasLimitedPackage = - (isLimitedPackage && - packageInfoData && - doesAgentConfigAlreadyIncludePackage(agentConf, packageInfoData.response.name)) || - false; - return { - label: agentConf.name, - key: agentConf.id, - checked: selectedConfigId === agentConf.id ? 'on' : undefined, - disabled: alreadyHasLimitedPackage, - 'data-test-subj': 'agentConfigItem', - }; - })} - renderOption={(option) => ( - - {option.label} + - - {agentConfigsById[option.key!].description} - + - - - +
+ setIsCreateAgentConfigFlyoutOpen(true)} + > + + +
- )} - listProps={{ - bordered: true, - }} - searchProps={{ - placeholder: i18n.translate( - 'xpack.ingestManager.createPackageConfig.StepSelectConfig.filterAgentConfigsInputPlaceholder', + } + helpText={ + isFleetReady && selectedConfigId ? ( + + ) : null + } + > + { - const selectedOption = options.find((option) => option.checked === 'on'); - if (selectedOption) { - if (selectedOption.key !== selectedConfigId) { - setSelectedConfigId(selectedOption.key); + )} + singleSelection={{ asPlainText: true }} + isClearable={false} + fullWidth={true} + isLoading={isAgentConfigsLoading || isPackageInfoLoading} + options={agentConfigOptions} + renderOption={(option: EuiComboBoxOptionOption) => { + return ( + + + {option.label} + + + + {agentConfigsById[option.value!].description} + + + {isFleetReady ? ( + + + + + + ) : null} + + ); + }} + selectedOptions={selectedConfigOption ? [selectedConfigOption] : []} + onChange={(options) => { + const selectedOption = options[0] || undefined; + if (selectedOption) { + if (selectedOption.value !== selectedConfigId) { + setSelectedConfigId(selectedOption.value); + } + } else { + setSelectedConfigId(undefined); } - } else { - setSelectedConfigId(undefined); - } - }} - > - {(list, search) => ( - - {search} - - {list} - - )} -
+ }} + /> +
{/* Display selected agent config error if there is one */} {selectedConfigError ? ( @@ -240,22 +317,6 @@ export const StepSelectConfig: React.FunctionComponent<{ /> ) : null} - -
- setIsCreateAgentConfigFlyoutOpen(true)} - flush="left" - size="s" - > - - -
-
); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/package_configs_table.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/package_configs_table.tsx index 4da4e2cc68c9d..1aa0fd1220833 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/package_configs_table.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/package_configs_table.tsx @@ -104,6 +104,11 @@ export const PackageConfigsTable: React.FunctionComponent = ({ defaultMessage: 'Name', } ), + render: (value: string) => ( + + {value} + + ), }, { field: 'description', @@ -113,7 +118,11 @@ export const PackageConfigsTable: React.FunctionComponent = ({ defaultMessage: 'Description', } ), - truncateText: true, + render: (value: string) => ( + + {value} + + ), }, { field: 'packageTitle', diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx index 4ae16eb91e582..0e65cb80f07c4 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx @@ -74,7 +74,7 @@ export const AgentConfigDetailsPage: React.FunctionComponent = () => { - +

{(agentConfig && agentConfig.name) || ( { {agentConfig && agentConfig.description ? ( - + {agentConfig.description} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx index 37fce340da6ea..749716b473c85 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx @@ -19,6 +19,7 @@ import { EuiButton, EuiText, EuiFlyoutProps, + EuiSpacer, } from '@elastic/eui'; import { NewAgentConfig, AgentConfig } from '../../../../types'; import { useCapabilities, useCore, sendCreateAgentConfig } from '../../../../hooks'; @@ -70,11 +71,14 @@ export const CreateAgentConfigFlyout: React.FunctionComponent = ({ />

+ - +

+ +

); @@ -95,7 +99,7 @@ export const CreateAgentConfigFlyout: React.FunctionComponent = ({ - onClose()} flush="left"> + onClose()} flush="left"> = ({ ); return ( - + onClose()} size="l" maxWidth={400} {...restOfProps}> {header} {body} {footer} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx index 4e79bd4fa7997..229adb946412b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx @@ -158,10 +158,9 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Description', }), width: '35%', - truncateText: true, - render: (description: AgentConfig['description']) => ( - - {description} + render: (value: string) => ( + + {value} ), }, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx index a6e458a4615cd..39e6d90e64bea 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx @@ -75,7 +75,6 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { field: 'dataset', sortable: true, width: '25%', - truncateText: true, name: i18n.translate('xpack.ingestManager.dataStreamList.datasetColumnTitle', { defaultMessage: 'Dataset', }), @@ -83,7 +82,6 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { { field: 'type', sortable: true, - truncateText: true, name: i18n.translate('xpack.ingestManager.dataStreamList.typeColumnTitle', { defaultMessage: 'Type', }), @@ -91,7 +89,6 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { { field: 'namespace', sortable: true, - truncateText: true, name: i18n.translate('xpack.ingestManager.dataStreamList.namespaceColumnTitle', { defaultMessage: 'Namespace', }), @@ -102,7 +99,6 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { { field: 'package', sortable: true, - truncateText: true, name: i18n.translate('xpack.ingestManager.dataStreamList.integrationColumnTitle', { defaultMessage: 'Integration', }), diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx index 7afc57b30cef4..0f48a230bbf5c 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx @@ -53,6 +53,7 @@ export const AgentDetailsActionMenu: React.FunctionComponent<{ onClick={() => { setIsReassignFlyoutOpen(true); }} + disabled={!agent.active} key="reassignConfig" > + {agentConfig.name || agent.config_id} ) : ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/agent_events_table.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/agent_events_table.tsx index 5be728b88c3e4..5806cbdcd6811 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/agent_events_table.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/agent_events_table.tsx @@ -153,8 +153,11 @@ export const AgentEventsTable: React.FunctionComponent<{ agent: Agent }> = ({ ag name: i18n.translate('xpack.ingestManager.agentEventsList.messageColumnTitle', { defaultMessage: 'Message', }), - render: (message: string) => {message}, - truncateText: true, + render: (value: string) => ( + + {value} + + ), }, { align: RIGHT_ALIGNMENT, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/type_labels.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/type_labels.tsx index e9cb59be37892..43e4d696ded66 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/type_labels.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/type_labels.tsx @@ -95,6 +95,14 @@ export const SUBTYPE_LABEL: { [key in AgentEvent['subtype']]: JSX.Element } = { /> ), + DEGRADED: ( + + + + ), DATA_DUMP: ( { ) : agentConfigData?.item ? ( {agentConfigData.item.name || agentData.item.config_id} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/index.tsx index 3743f9b39191b..c52f8447214a0 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/index.tsx @@ -23,7 +23,6 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage, FormattedRelative } from '@kbn/i18n/react'; -import { CSSProperties } from 'styled-components'; import { AgentEnrollmentFlyout } from '../components'; import { Agent, AgentConfig } from '../../../types'; import { @@ -40,11 +39,6 @@ import { AgentStatusKueryHelper } from '../../../services'; import { AGENT_SAVED_OBJECT_TYPE } from '../../../constants'; import { AgentReassignConfigFlyout, AgentHealth, AgentUnenrollProvider } from '../components'; -const NO_WRAP_TRUNCATE_STYLE: CSSProperties = Object.freeze({ - overflow: 'hidden', - textOverflow: 'ellipsis', - whiteSpace: 'nowrap', -}); const REFRESH_INTERVAL_MS = 5000; const statusFilters = [ @@ -96,6 +90,7 @@ const RowActions = React.memo<{ agent: Agent; onReassignClick: () => void; refre onClick={() => { onReassignClick(); }} + disabled={!agent.active} key="reassignConfig" > void; refre defaultMessage="Assign new agent config" /> , - {(unenrollAgentsPrompt) => ( { unenrollAgentsPrompt([agent.id], 1, () => { @@ -279,10 +273,10 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { const configName = agentConfigs.find((p) => p.id === configId)?.name; return ( - + {configName || configId} @@ -542,9 +536,9 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { ), }} /> - ) : !isLoading && totalAgents === 0 ? ( + ) : ( emptyPrompt - ) : undefined + ) } items={totalAgents ? agents : []} itemId="id" diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx index 09b00240dc127..e98ebb7cadc7c 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx @@ -39,71 +39,105 @@ export const EnrollmentStepAgentConfig: React.FC = (props) => { enrollmentAPIKeyId?: string; }>({}); - useEffect(() => { - if (agentConfigs && agentConfigs.length && !selectedState.agentConfigId) { - setSelectedState({ - ...selectedState, - agentConfigId: agentConfigs[0].id, - }); - } - }, [agentConfigs, selectedState]); + useEffect( + function triggerOnConfigChangeEffect() { + if (onConfigChange && selectedState.agentConfigId) { + onConfigChange(selectedState.agentConfigId); + } + }, + [selectedState.agentConfigId, onConfigChange] + ); - useEffect(() => { - if (onConfigChange && selectedState.agentConfigId) { - onConfigChange(selectedState.agentConfigId); - } - }, [selectedState.agentConfigId, onConfigChange]); + useEffect( + function triggerOnKeyChangeEffect() { + if (!withKeySelection || !onKeyChange) { + return; + } - useEffect(() => { - if (!withKeySelection) { - return; - } - if (!selectedState.agentConfigId) { - setEnrollmentAPIKeys([]); - return; - } + if (selectedState.enrollmentAPIKeyId) { + onKeyChange(selectedState.enrollmentAPIKeyId); + } + }, + [withKeySelection, onKeyChange, selectedState.enrollmentAPIKeyId] + ); - async function fetchEnrollmentAPIKeys() { - try { - const res = await sendGetEnrollmentAPIKeys({ - page: 1, - perPage: 10000, - }); - if (res.error) { - throw res.error; + useEffect( + function useDefaultConfigEffect() { + if (agentConfigs && agentConfigs.length && !selectedState.agentConfigId) { + const defaultConfig = agentConfigs.find((config) => config.is_default); + if (defaultConfig) { + setSelectedState({ + ...selectedState, + agentConfigId: defaultConfig.id, + }); } + } + }, + [agentConfigs, selectedState] + ); - if (!res.data) { - throw new Error('No data while fetching enrollment API keys'); + useEffect( + function useEnrollmentKeysForConfigEffect() { + if (!withKeySelection) { + return; + } + if (!selectedState.agentConfigId) { + setEnrollmentAPIKeys([]); + return; + } + + async function fetchEnrollmentAPIKeys() { + try { + const res = await sendGetEnrollmentAPIKeys({ + page: 1, + perPage: 10000, + }); + if (res.error) { + throw res.error; + } + + if (!res.data) { + throw new Error('No data while fetching enrollment API keys'); + } + + setEnrollmentAPIKeys( + res.data.list.filter((key) => key.config_id === selectedState.agentConfigId) + ); + } catch (error) { + notifications.toasts.addError(error, { + title: 'Error', + }); } + } + fetchEnrollmentAPIKeys(); + }, + [withKeySelection, selectedState.agentConfigId, notifications.toasts] + ); - setEnrollmentAPIKeys( - res.data.list.filter((key) => key.config_id === selectedState.agentConfigId) - ); - } catch (error) { - notifications.toasts.addError(error, { - title: 'Error', + useEffect( + function useDefaultEnrollmentKeyForConfigEffect() { + if (!withKeySelection) { + return; + } + if ( + !selectedState.enrollmentAPIKeyId && + enrollmentAPIKeys.length > 0 && + enrollmentAPIKeys[0].config_id === selectedState.agentConfigId + ) { + const enrollmentAPIKeyId = enrollmentAPIKeys[0].id; + setSelectedState({ + agentConfigId: selectedState.agentConfigId, + enrollmentAPIKeyId, }); } - } - fetchEnrollmentAPIKeys(); - }, [withKeySelection, selectedState.agentConfigId, notifications.toasts]); - - // Select first API key when config change - React.useEffect(() => { - if (!withKeySelection || !onKeyChange) { - return; - } - if (!selectedState.enrollmentAPIKeyId && enrollmentAPIKeys.length > 0) { - const enrollmentAPIKeyId = enrollmentAPIKeys[0].id; - setSelectedState({ - agentConfigId: selectedState.agentConfigId, - enrollmentAPIKeyId, - }); - onKeyChange(enrollmentAPIKeyId); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [enrollmentAPIKeys, selectedState.enrollmentAPIKeyId, selectedState.agentConfigId]); + }, + [ + withKeySelection, + enrollmentAPIKeys, + selectedState.enrollmentAPIKeyId, + selectedState.agentConfigId, + ] + ); return ( <> @@ -174,7 +208,6 @@ export const EnrollmentStepAgentConfig: React.FC = (props) => { ...selectedState, enrollmentAPIKeyId: e.target.value, }); - onKeyChange(e.target.value); }} /> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/index.tsx index 2c66001cc8c08..9c7bea51f46ea 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/index.tsx @@ -70,7 +70,7 @@ export const AgentEnrollmentFlyout: React.FunctionComponent = ({ - + = ({ agentCo title: i18n.translate('xpack.ingestManager.agentEnrollment.stepCheckForDataTitle', { defaultMessage: 'Check for data', }), - status: 'incomplete', children: ( <> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx index 592ca7f7b8380..c067de1cfea5a 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx @@ -122,7 +122,7 @@ export const AgentReassignConfigFlyout: React.FunctionComponent = ({ onCl - + = ({ - + = ({ apiKeyId }) => { const { notifications } = useCore(); const [state, setState] = useState<'VISIBLE' | 'HIDDEN' | 'LOADING'>('HIDDEN'); @@ -66,24 +61,42 @@ const ApiKeyField: React.FunctionComponent<{ apiKeyId: string }> = ({ apiKeyId } }; return ( - - - {state === 'VISIBLE' ? ( - - {key} - - ) : ( - ••••••••••••••••••••• - )} + + + + {state === 'VISIBLE' + ? key + : '•••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••'} + - + + + ); @@ -120,7 +133,23 @@ const DeleteButton: React.FunctionComponent<{ apiKey: EnrollmentAPIKey; refresh: onConfirm={onConfirm} /> )} - setState('CONFIRM_VISIBLE')} iconType="trash" color="danger" /> + + setState('CONFIRM_VISIBLE')} + iconType="trash" + color="danger" + /> + ); }; @@ -152,15 +181,11 @@ export const EnrollmentTokenListPage: React.FunctionComponent<{}> = () => { name: i18n.translate('xpack.ingestManager.enrollmentTokensList.nameTitle', { defaultMessage: 'Name', }), - truncateText: true, - textOnly: true, - render: (name: string) => { - return ( - - {name} - - ); - }, + render: (value: string) => ( + + {value} + + ), }, { field: 'id', @@ -179,7 +204,12 @@ export const EnrollmentTokenListPage: React.FunctionComponent<{}> = () => { }), render: (configId: string) => { const config = agentConfigs.find((c) => c.id === configId); - return <>{config ? config.name : configId}; + const value = config ? config.name : configId; + return ( + + {value} + + ); }, }, { @@ -200,12 +230,9 @@ export const EnrollmentTokenListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Active', }), width: '70px', + align: 'center' as HorizontalAlignment, render: (active: boolean) => { - return ( - - - - ); + return ; }, }, { @@ -242,7 +269,7 @@ export const EnrollmentTokenListPage: React.FunctionComponent<{}> = () => { /> - + - + diff --git a/x-pack/plugins/ingest_manager/server/index.ts b/x-pack/plugins/ingest_manager/server/index.ts index 6c72218abc531..40e0153a26581 100644 --- a/x-pack/plugins/ingest_manager/server/index.ts +++ b/x-pack/plugins/ingest_manager/server/index.ts @@ -35,8 +35,7 @@ export const config = { host: schema.maybe(schema.string()), ca_sha256: schema.maybe(schema.string()), }), - agentConfigRollupRateLimitIntervalMs: schema.number({ defaultValue: 5000 }), - agentConfigRollupRateLimitRequestPerInterval: schema.number({ defaultValue: 50 }), + agentConfigRolloutConcurrency: schema.number({ defaultValue: 10 }), }), }), }; diff --git a/x-pack/plugins/ingest_manager/server/mocks.ts b/x-pack/plugins/ingest_manager/server/mocks.ts index f305d9dd0c1a7..52cd294783087 100644 --- a/x-pack/plugins/ingest_manager/server/mocks.ts +++ b/x-pack/plugins/ingest_manager/server/mocks.ts @@ -18,6 +18,7 @@ export const createAppContextStartContractMock = (): IngestManagerAppContext => logger: loggingSystemMock.create().get(), isProductionMode: true, kibanaVersion: '8.0.0', + kibanaBranch: 'master', }; }; diff --git a/x-pack/plugins/ingest_manager/server/plugin.ts b/x-pack/plugins/ingest_manager/server/plugin.ts index 69af475886bb9..e7495df254a09 100644 --- a/x-pack/plugins/ingest_manager/server/plugin.ts +++ b/x-pack/plugins/ingest_manager/server/plugin.ts @@ -85,6 +85,7 @@ export interface IngestManagerAppContext { savedObjects: SavedObjectsServiceStart; isProductionMode: boolean; kibanaVersion: string; + kibanaBranch: string; cloud?: CloudSetup; logger?: Logger; httpSetup?: HttpServiceSetup; @@ -145,6 +146,7 @@ export class IngestManagerPlugin private isProductionMode: boolean; private kibanaVersion: string; + private kibanaBranch: string; private httpSetup: HttpServiceSetup | undefined; private encryptedSavedObjectsSetup: EncryptedSavedObjectsPluginSetup | undefined; @@ -152,6 +154,7 @@ export class IngestManagerPlugin this.config$ = this.initializerContext.config.create(); this.isProductionMode = this.initializerContext.env.mode.prod; this.kibanaVersion = this.initializerContext.env.packageInfo.version; + this.kibanaBranch = this.initializerContext.env.packageInfo.branch; this.logger = this.initializerContext.logger.get(); } @@ -257,6 +260,7 @@ export class IngestManagerPlugin savedObjects: core.savedObjects, isProductionMode: this.isProductionMode, kibanaVersion: this.kibanaVersion, + kibanaBranch: this.kibanaBranch, httpSetup: this.httpSetup, cloud: this.cloud, logger: this.logger, diff --git a/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts index e485fad09ba99..6cfe3d5b76266 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts @@ -48,7 +48,7 @@ export const getAgentHandler: RequestHandler { @@ -33,3 +37,183 @@ describe('registerLimitedConcurrencyRoutes', () => { expect(mockSetup.http.registerOnPreAuth).toHaveBeenCalledTimes(1); }); }); + +// assertions for calls to .decrease are commented out because it's called on the +// "req.events.aborted$ observable (which) will never emit from a mocked request in a jest unit test environment" +// https://github.com/elastic/kibana/pull/72338#issuecomment-661908791 +describe('preAuthHandler', () => { + test(`ignores routes when !isMatch`, async () => { + const mockMaxCounter = { + increase: jest.fn(), + decrease: jest.fn(), + lessThanMax: jest.fn(), + }; + const preAuthHandler = createLimitedPreAuthHandler({ + isMatch: jest.fn().mockImplementation(() => false), + maxCounter: mockMaxCounter, + }); + + const mockRequest = httpServerMock.createKibanaRequest({ + path: '/no/match', + }); + const mockResponse = httpServerMock.createResponseFactory(); + const mockPreAuthToolkit = httpServiceMock.createOnPreAuthToolkit(); + + await preAuthHandler(mockRequest, mockResponse, mockPreAuthToolkit); + + expect(mockMaxCounter.increase).not.toHaveBeenCalled(); + expect(mockMaxCounter.decrease).not.toHaveBeenCalled(); + expect(mockMaxCounter.lessThanMax).not.toHaveBeenCalled(); + expect(mockPreAuthToolkit.next).toHaveBeenCalledTimes(1); + }); + + test(`ignores routes which don't have the correct tag`, async () => { + const mockMaxCounter = { + increase: jest.fn(), + decrease: jest.fn(), + lessThanMax: jest.fn(), + }; + const preAuthHandler = createLimitedPreAuthHandler({ + isMatch: isLimitedRoute, + maxCounter: mockMaxCounter, + }); + + const mockRequest = httpServerMock.createKibanaRequest({ + path: '/no/match', + }); + const mockResponse = httpServerMock.createResponseFactory(); + const mockPreAuthToolkit = httpServiceMock.createOnPreAuthToolkit(); + + await preAuthHandler(mockRequest, mockResponse, mockPreAuthToolkit); + + expect(mockMaxCounter.increase).not.toHaveBeenCalled(); + expect(mockMaxCounter.decrease).not.toHaveBeenCalled(); + expect(mockMaxCounter.lessThanMax).not.toHaveBeenCalled(); + expect(mockPreAuthToolkit.next).toHaveBeenCalledTimes(1); + }); + + test(`processes routes which have the correct tag`, async () => { + const mockMaxCounter = { + increase: jest.fn(), + decrease: jest.fn(), + lessThanMax: jest.fn().mockImplementation(() => true), + }; + const preAuthHandler = createLimitedPreAuthHandler({ + isMatch: isLimitedRoute, + maxCounter: mockMaxCounter, + }); + + const mockRequest = httpServerMock.createKibanaRequest({ + path: '/should/match', + routeTags: ['ingest:limited-concurrency'], + }); + const mockResponse = httpServerMock.createResponseFactory(); + const mockPreAuthToolkit = httpServiceMock.createOnPreAuthToolkit(); + + await preAuthHandler(mockRequest, mockResponse, mockPreAuthToolkit); + + // will call lessThanMax because isMatch succeeds + expect(mockMaxCounter.lessThanMax).toHaveBeenCalledTimes(1); + // will not error because lessThanMax is true + expect(mockResponse.customError).not.toHaveBeenCalled(); + expect(mockPreAuthToolkit.next).toHaveBeenCalledTimes(1); + }); + + test(`updates the counter when isMatch & lessThanMax`, async () => { + const mockMaxCounter = { + increase: jest.fn(), + decrease: jest.fn(), + lessThanMax: jest.fn().mockImplementation(() => true), + }; + const preAuthHandler = createLimitedPreAuthHandler({ + isMatch: jest.fn().mockImplementation(() => true), + maxCounter: mockMaxCounter, + }); + + const mockRequest = httpServerMock.createKibanaRequest(); + const mockResponse = httpServerMock.createResponseFactory(); + const mockPreAuthToolkit = httpServiceMock.createOnPreAuthToolkit(); + + await preAuthHandler(mockRequest, mockResponse, mockPreAuthToolkit); + + expect(mockMaxCounter.increase).toHaveBeenCalled(); + // expect(mockMaxCounter.decrease).toHaveBeenCalled(); + expect(mockPreAuthToolkit.next).toHaveBeenCalledTimes(1); + }); + + test(`lessThanMax ? next : error`, async () => { + const mockMaxCounter = { + increase: jest.fn(), + decrease: jest.fn(), + lessThanMax: jest + .fn() + // call 1 + .mockImplementationOnce(() => true) + // calls 2, 3, 4 + .mockImplementationOnce(() => false) + .mockImplementationOnce(() => false) + .mockImplementationOnce(() => false) + // calls 5+ + .mockImplementationOnce(() => true) + .mockImplementation(() => true), + }; + + const preAuthHandler = createLimitedPreAuthHandler({ + isMatch: isLimitedRoute, + maxCounter: mockMaxCounter, + }); + + function makeRequestExpectNext() { + const request = httpServerMock.createKibanaRequest({ + path: '/should/match/', + routeTags: ['ingest:limited-concurrency'], + }); + const response = httpServerMock.createResponseFactory(); + const toolkit = httpServiceMock.createOnPreAuthToolkit(); + + preAuthHandler(request, response, toolkit); + expect(toolkit.next).toHaveBeenCalledTimes(1); + expect(response.customError).not.toHaveBeenCalled(); + } + + function makeRequestExpectError() { + const request = httpServerMock.createKibanaRequest({ + path: '/should/match/', + routeTags: ['ingest:limited-concurrency'], + }); + const response = httpServerMock.createResponseFactory(); + const toolkit = httpServiceMock.createOnPreAuthToolkit(); + + preAuthHandler(request, response, toolkit); + expect(toolkit.next).not.toHaveBeenCalled(); + expect(response.customError).toHaveBeenCalledTimes(1); + expect(response.customError).toHaveBeenCalledWith({ + statusCode: 429, + body: 'Too Many Requests', + }); + } + + // request 1 succeeds + makeRequestExpectNext(); + expect(mockMaxCounter.increase).toHaveBeenCalledTimes(1); + // expect(mockMaxCounter.decrease).toHaveBeenCalledTimes(1); + + // requests 2, 3, 4 fail + makeRequestExpectError(); + makeRequestExpectError(); + makeRequestExpectError(); + + // requests 5+ succeed + makeRequestExpectNext(); + expect(mockMaxCounter.increase).toHaveBeenCalledTimes(2); + // expect(mockMaxCounter.decrease).toHaveBeenCalledTimes(2); + + makeRequestExpectNext(); + expect(mockMaxCounter.increase).toHaveBeenCalledTimes(3); + // expect(mockMaxCounter.decrease).toHaveBeenCalledTimes(3); + + makeRequestExpectNext(); + expect(mockMaxCounter.increase).toHaveBeenCalledTimes(4); + // expect(mockMaxCounter.decrease).toHaveBeenCalledTimes(4); + }); +}); diff --git a/x-pack/plugins/ingest_manager/server/routes/limited_concurrency.ts b/x-pack/plugins/ingest_manager/server/routes/limited_concurrency.ts index ec8e2f6c8d436..11fdc944e031d 100644 --- a/x-pack/plugins/ingest_manager/server/routes/limited_concurrency.ts +++ b/x-pack/plugins/ingest_manager/server/routes/limited_concurrency.ts @@ -12,7 +12,8 @@ import { } from 'kibana/server'; import { LIMITED_CONCURRENCY_ROUTE_TAG } from '../../common'; import { IngestManagerConfigType } from '../index'; -class MaxCounter { + +export class MaxCounter { constructor(private readonly max: number = 1) {} private counter = 0; valueOf() { @@ -33,40 +34,56 @@ class MaxCounter { } } -function shouldHandleRequest(request: KibanaRequest) { +export type IMaxCounter = Pick; + +export function isLimitedRoute(request: KibanaRequest) { const tags = request.route.options.tags; - return tags.includes(LIMITED_CONCURRENCY_ROUTE_TAG); + return !!tags.includes(LIMITED_CONCURRENCY_ROUTE_TAG); } -export function registerLimitedConcurrencyRoutes(core: CoreSetup, config: IngestManagerConfigType) { - const max = config.fleet.maxConcurrentConnections; - if (!max) return; - - const counter = new MaxCounter(max); - core.http.registerOnPreAuth(function preAuthHandler( +export function createLimitedPreAuthHandler({ + isMatch, + maxCounter, +}: { + isMatch: (request: KibanaRequest) => boolean; + maxCounter: IMaxCounter; +}) { + return function preAuthHandler( request: KibanaRequest, response: LifecycleResponseFactory, toolkit: OnPreAuthToolkit ) { - if (!shouldHandleRequest(request)) { + if (!isMatch(request)) { return toolkit.next(); } - if (!counter.lessThanMax()) { + if (!maxCounter.lessThanMax()) { return response.customError({ body: 'Too Many Requests', statusCode: 429, }); } - counter.increase(); + maxCounter.increase(); // requests.events.aborted$ has a bug (but has test which explicitly verifies) where it's fired even when the request completes // https://github.com/elastic/kibana/pull/70495#issuecomment-656288766 request.events.aborted$.toPromise().then(() => { - counter.decrease(); + maxCounter.decrease(); }); return toolkit.next(); - }); + }; +} + +export function registerLimitedConcurrencyRoutes(core: CoreSetup, config: IngestManagerConfigType) { + const max = config.fleet.maxConcurrentConnections; + if (!max) return; + + core.http.registerOnPreAuth( + createLimitedPreAuthHandler({ + isMatch: isLimitedRoute, + maxCounter: new MaxCounter(max), + }) + ); } diff --git a/x-pack/plugins/ingest_manager/server/routes/package_config/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/package_config/handlers.ts index 6b0c2fe9c2ff7..d2820cdbeb6c8 100644 --- a/x-pack/plugins/ingest_manager/server/routes/package_config/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/package_config/handlers.ts @@ -5,7 +5,7 @@ */ import { TypeOf } from '@kbn/config-schema'; import Boom from 'boom'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler, SavedObjectsErrorHelpers } from '../../../../../../src/core/server'; import { appContextService, packageConfigService } from '../../services'; import { getPackageInfo } from '../../services/epm/packages'; import { @@ -49,8 +49,12 @@ export const getOnePackageConfigHandler: RequestHandler> = async (context, request, response) => { const soClient = context.core.savedObjects.client; + const { packageConfigId } = request.params; + const notFoundResponse = () => + response.notFound({ body: { message: `Package config ${packageConfigId} not found` } }); + try { - const packageConfig = await packageConfigService.get(soClient, request.params.packageConfigId); + const packageConfig = await packageConfigService.get(soClient, packageConfigId); if (packageConfig) { return response.ok({ body: { @@ -58,17 +62,18 @@ export const getOnePackageConfigHandler: RequestHandler { - const { id: packageConfigId, ...newPackageConfig } = packageConfig; + const { id: packageConfigId, version, ...newPackageConfig } = packageConfig; return newPackageConfig; } ); - await packageConfigService.bulkCreate( - soClient, - newPackageConfigs, - newAgentConfig.id, - options - ); + await packageConfigService.bulkCreate(soClient, newPackageConfigs, newAgentConfig.id, { + ...options, + bumpConfigRevision: false, + }); } // Get updated config @@ -336,7 +334,7 @@ class AgentConfigService { throw new Error('Agent configuration not found'); } - const defaultConfigId = await this.getDefaultAgentConfigId(soClient); + const { id: defaultConfigId } = await this.ensureDefaultAgentConfig(soClient); if (id === defaultConfigId) { throw new Error('The default agent configuration cannot be deleted'); } diff --git a/x-pack/plugins/ingest_manager/server/services/agents/checkin/rxjs_utils.test.ts b/x-pack/plugins/ingest_manager/server/services/agents/checkin/rxjs_utils.test.ts new file mode 100644 index 0000000000000..70207dcf325c4 --- /dev/null +++ b/x-pack/plugins/ingest_manager/server/services/agents/checkin/rxjs_utils.test.ts @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as Rx from 'rxjs'; +import { share } from 'rxjs/operators'; +import { createSubscriberConcurrencyLimiter } from './rxjs_utils'; + +function createSpyObserver(o: Rx.Observable): [Rx.Subscription, jest.Mock] { + const spy = jest.fn(); + const observer = o.subscribe(spy); + return [observer, spy]; +} + +describe('createSubscriberConcurrencyLimiter', () => { + it('should not publish to more than n concurrent subscriber', async () => { + const subject = new Rx.Subject(); + const sharedObservable = subject.pipe(share()); + + const limiter = createSubscriberConcurrencyLimiter(2); + + const [observer1, spy1] = createSpyObserver(sharedObservable.pipe(limiter())); + const [observer2, spy2] = createSpyObserver(sharedObservable.pipe(limiter())); + const [observer3, spy3] = createSpyObserver(sharedObservable.pipe(limiter())); + const [observer4, spy4] = createSpyObserver(sharedObservable.pipe(limiter())); + subject.next('test1'); + + expect(spy1).toBeCalled(); + expect(spy2).toBeCalled(); + expect(spy3).not.toBeCalled(); + expect(spy4).not.toBeCalled(); + + observer1.unsubscribe(); + expect(spy3).toBeCalled(); + expect(spy4).not.toBeCalled(); + + observer2.unsubscribe(); + expect(spy4).toBeCalled(); + + observer3.unsubscribe(); + observer4.unsubscribe(); + }); +}); diff --git a/x-pack/plugins/ingest_manager/server/services/agents/checkin/rxjs_utils.ts b/x-pack/plugins/ingest_manager/server/services/agents/checkin/rxjs_utils.ts index a806169019a1e..dc0ed35207e46 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/checkin/rxjs_utils.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/checkin/rxjs_utils.ts @@ -43,34 +43,23 @@ export const toPromiseAbortable = ( } }); -export function createLimiter(ratelimitIntervalMs: number, ratelimitRequestPerInterval: number) { - function createCurrentInterval() { - return { - startedAt: Rx.asyncScheduler.now(), - numRequests: 0, - }; - } - - let currentInterval: { startedAt: number; numRequests: number } = createCurrentInterval(); +export function createSubscriberConcurrencyLimiter(maxConcurrency: number) { let observers: Array<[Rx.Subscriber, any]> = []; - let timerSubscription: Rx.Subscription | undefined; + let activeObservers: Array> = []; - function createTimeout() { - if (timerSubscription) { + function processNext() { + if (activeObservers.length >= maxConcurrency) { return; } - timerSubscription = Rx.asyncScheduler.schedule(() => { - timerSubscription = undefined; - currentInterval = createCurrentInterval(); - for (const [waitingObserver, value] of observers) { - if (currentInterval.numRequests >= ratelimitRequestPerInterval) { - createTimeout(); - continue; - } - currentInterval.numRequests++; - waitingObserver.next(value); - } - }, ratelimitIntervalMs); + const observerValuePair = observers.shift(); + + if (!observerValuePair) { + return; + } + + const [observer, value] = observerValuePair; + activeObservers.push(observer); + observer.next(value); } return function limit(): Rx.MonoTypeOperatorFunction { @@ -78,14 +67,8 @@ export function createLimiter(ratelimitIntervalMs: number, ratelimitRequestPerIn new Rx.Observable((observer) => { const subscription = observable.subscribe({ next(value) { - if (currentInterval.numRequests < ratelimitRequestPerInterval) { - currentInterval.numRequests++; - observer.next(value); - return; - } - observers = [...observers, [observer, value]]; - createTimeout(); + processNext(); }, error(err) { observer.error(err); @@ -96,8 +79,10 @@ export function createLimiter(ratelimitIntervalMs: number, ratelimitRequestPerIn }); return () => { + activeObservers = activeObservers.filter((o) => o !== observer); observers = observers.filter((o) => o[0] !== observer); subscription.unsubscribe(); + processNext(); }; }); }; diff --git a/x-pack/plugins/ingest_manager/server/services/agents/checkin/state.ts b/x-pack/plugins/ingest_manager/server/services/agents/checkin/state.ts index 69d61171b21fc..63f22b82611c2 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/checkin/state.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/checkin/state.ts @@ -13,9 +13,11 @@ import { AGENT_UPDATE_LAST_CHECKIN_INTERVAL_MS } from '../../../constants'; function agentCheckinStateFactory() { const agentConnected = agentCheckinStateConnectedAgentsFactory(); - const newActions = agentCheckinStateNewActionsFactory(); + let newActions: ReturnType; let interval: NodeJS.Timeout; + function start() { + newActions = agentCheckinStateNewActionsFactory(); interval = setInterval(async () => { try { await agentConnected.updateLastCheckinAt(); @@ -31,15 +33,20 @@ function agentCheckinStateFactory() { } } return { - subscribeToNewActions: ( + subscribeToNewActions: async ( soClient: SavedObjectsClientContract, agent: Agent, options?: { signal: AbortSignal } - ) => - agentConnected.wrapPromise( + ) => { + if (!newActions) { + throw new Error('Agent checkin state not initialized'); + } + + return agentConnected.wrapPromise( agent.id, newActions.subscribeToNewActions(soClient, agent, options) - ), + ); + }, start, stop, }; diff --git a/x-pack/plugins/ingest_manager/server/services/agents/checkin/state_new_actions.ts b/x-pack/plugins/ingest_manager/server/services/agents/checkin/state_new_actions.ts index 5ceb774a1946c..53270afe453c4 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/checkin/state_new_actions.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/checkin/state_new_actions.ts @@ -28,7 +28,7 @@ import * as APIKeysService from '../../api_keys'; import { AGENT_SAVED_OBJECT_TYPE, AGENT_UPDATE_ACTIONS_INTERVAL_MS } from '../../../constants'; import { createAgentAction, getNewActionsSince } from '../actions'; import { appContextService } from '../../app_context'; -import { toPromiseAbortable, AbortError, createLimiter } from './rxjs_utils'; +import { toPromiseAbortable, AbortError, createSubscriberConcurrencyLimiter } from './rxjs_utils'; function getInternalUserSOClient() { const fakeRequest = ({ @@ -134,9 +134,8 @@ export function agentCheckinStateNewActionsFactory() { const agentConfigs$ = new Map>(); const newActions$ = createNewActionsSharedObservable(); // Rx operators - const rateLimiter = createLimiter( - appContextService.getConfig()?.fleet.agentConfigRollupRateLimitIntervalMs || 5000, - appContextService.getConfig()?.fleet.agentConfigRollupRateLimitRequestPerInterval || 50 + const concurrencyLimiter = createSubscriberConcurrencyLimiter( + appContextService.getConfig()?.fleet.agentConfigRolloutConcurrency ?? 10 ); async function subscribeToNewActions( @@ -155,10 +154,11 @@ export function agentCheckinStateNewActionsFactory() { if (!agentConfig$) { throw new Error(`Invalid state no observable for config ${configId}`); } + const stream$ = agentConfig$.pipe( timeout(appContextService.getConfig()?.fleet.pollingRequestTimeout || 0), filter((config) => shouldCreateAgentConfigAction(agent, config)), - rateLimiter(), + concurrencyLimiter(), mergeMap((config) => createAgentActionFromConfig(soClient, agent, config)), merge(newActions$), mergeMap(async (data) => { diff --git a/x-pack/plugins/ingest_manager/server/services/app_context.ts b/x-pack/plugins/ingest_manager/server/services/app_context.ts index 4d109b73d12d9..bdc7a443ba6dd 100644 --- a/x-pack/plugins/ingest_manager/server/services/app_context.ts +++ b/x-pack/plugins/ingest_manager/server/services/app_context.ts @@ -24,6 +24,7 @@ class AppContextService { private savedObjects: SavedObjectsServiceStart | undefined; private isProductionMode: boolean = false; private kibanaVersion: string | undefined; + private kibanaBranch: string | undefined; private cloud?: CloudSetup; private logger: Logger | undefined; private httpSetup?: HttpServiceSetup; @@ -38,6 +39,7 @@ class AppContextService { this.cloud = appContext.cloud; this.logger = appContext.logger; this.kibanaVersion = appContext.kibanaVersion; + this.kibanaBranch = appContext.kibanaBranch; this.httpSetup = appContext.httpSetup; if (appContext.config$) { @@ -125,6 +127,13 @@ class AppContextService { return this.kibanaVersion; } + public getKibanaBranch() { + if (!this.kibanaBranch) { + throw new Error('Kibana branch is not set.'); + } + return this.kibanaBranch; + } + public addExternalCallback(type: ExternalCallback[0], callback: ExternalCallback[1]) { if (!this.externalCallbacks.has(type)) { this.externalCallbacks.set(type, new Set()); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/agent/agent.test.ts b/x-pack/plugins/ingest_manager/server/services/epm/agent/agent.test.ts index 635dce93f0027..54b40400bb4e7 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/agent/agent.test.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/agent/agent.test.ts @@ -84,6 +84,67 @@ foo: bar }); }); + describe('contains blocks', () => { + const streamTemplate = ` +input: log +paths: +{{#each paths}} + - {{this}} +{{/each}} +exclude_files: [".gz$"] +tags: +{{#each tags}} + - {{this}} +{{/each}} +{{#contains "forwarded" tags}} +publisher_pipeline.disable_host: true +{{/contains}} +processors: + - add_locale: ~ +password: {{password}} +{{#if password}} +hidden_password: {{password}} +{{/if}} + `; + + it('should support when a value is not contained in the array', () => { + const vars = { + paths: { value: ['/usr/local/var/log/nginx/access.log'] }, + password: { type: 'password', value: '' }, + tags: { value: ['foo', 'bar', 'forwarded'] }, + }; + + const output = createStream(vars, streamTemplate); + expect(output).toEqual({ + input: 'log', + paths: ['/usr/local/var/log/nginx/access.log'], + exclude_files: ['.gz$'], + processors: [{ add_locale: null }], + password: '', + 'publisher_pipeline.disable_host': true, + tags: ['foo', 'bar', 'forwarded'], + }); + }); + + it('should support when a value is contained in the array', () => { + const vars = { + paths: { value: ['/usr/local/var/log/nginx/access.log'] }, + password: { type: 'password', value: '' }, + tags: { value: ['foo', 'bar'] }, + }; + + const output = createStream(vars, streamTemplate); + expect(output).toEqual({ + input: 'log', + paths: ['/usr/local/var/log/nginx/access.log'], + exclude_files: ['.gz$'], + processors: [{ add_locale: null }], + password: '', + tags: ['foo', 'bar'], + }); + }); + }); + it('should support optional yaml values at root level', () => { const streamTemplate = ` input: logs diff --git a/x-pack/plugins/ingest_manager/server/services/epm/agent/agent.ts b/x-pack/plugins/ingest_manager/server/services/epm/agent/agent.ts index d697ad0576396..88c54d213554c 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/agent/agent.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/agent/agent.ts @@ -8,10 +8,12 @@ import Handlebars from 'handlebars'; import { safeLoad, safeDump } from 'js-yaml'; import { PackageConfigConfigRecord } from '../../../../common'; +const handlebars = Handlebars.create(); + export function createStream(variables: PackageConfigConfigRecord, streamTemplate: string) { const { vars, yamlValues } = buildTemplateVariables(variables, streamTemplate); - const template = Handlebars.compile(streamTemplate, { noEscape: true }); + const template = handlebars.compile(streamTemplate, { noEscape: true }); let stream = template(vars); stream = replaceRootLevelYamlVariables(yamlValues, stream); @@ -87,6 +89,16 @@ function buildTemplateVariables(variables: PackageConfigConfigRecord, streamTemp return { vars, yamlValues }; } +function containsHelper(this: any, item: string, list: string[], options: any) { + if (Array.isArray(list) && list.includes(item)) { + if (options && options.fn) { + return options.fn(this); + } + } + return ''; +} +handlebars.registerHelper('contains', containsHelper); + function replaceRootLevelYamlVariables(yamlVariables: { [k: string]: any }, yamlTemplate: string) { if (Object.keys(yamlVariables).length === 0 || !yamlTemplate) { return yamlTemplate; diff --git a/x-pack/plugins/ingest_manager/server/services/epm/registry/index.ts b/x-pack/plugins/ingest_manager/server/services/epm/registry/index.ts index 7fb13e5e671d0..c7f2df38fe41a 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/registry/index.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/registry/index.ts @@ -40,6 +40,8 @@ export const pkgToPkgKey = ({ name, version }: { name: string; version: string } export async function fetchList(params?: SearchParams): Promise { const registryUrl = getRegistryUrl(); const url = new URL(`${registryUrl}/search`); + const kibanaVersion = appContextService.getKibanaVersion().split('-')[0]; // may be x.y.z-SNAPSHOT + const kibanaBranch = appContextService.getKibanaBranch(); if (params) { if (params.category) { url.searchParams.set('category', params.category); @@ -48,8 +50,9 @@ export async function fetchList(params?: SearchParams): Promise { const registryUrl = getRegistryUrl(); + const kibanaVersion = appContextService.getKibanaVersion().split('-')[0]; // may be x.y.z-SNAPSHOT + const kibanaBranch = appContextService.getKibanaBranch(); const url = new URL( `${registryUrl}/search?package=${packageName}&internal=true&experimental=true` ); - const kibanaVersion = appContextService.getKibanaVersion().split('-')[0]; // may be 8.0.0-SNAPSHOT - if (kibanaVersion) { + + // on master, request all packages regardless of version + if (kibanaVersion && kibanaBranch !== 'master') { url.searchParams.set('kibana.version', kibanaVersion); } const res = await fetchUrl(url.toString()); diff --git a/x-pack/plugins/ingest_manager/server/services/package_config.ts b/x-pack/plugins/ingest_manager/server/services/package_config.ts index c2d465cf7c73f..5d1c5d1717714 100644 --- a/x-pack/plugins/ingest_manager/server/services/package_config.ts +++ b/x-pack/plugins/ingest_manager/server/services/package_config.ts @@ -121,7 +121,7 @@ class PackageConfigService { options?: { user?: AuthenticatedUser; bumpConfigRevision?: boolean } ): Promise { const isoDate = new Date().toISOString(); - const { saved_objects: newSos } = await soClient.bulkCreate( + const { saved_objects } = await soClient.bulkCreate( packageConfigs.map((packageConfig) => ({ type: SAVED_OBJECT_TYPE, attributes: { @@ -136,6 +136,9 @@ class PackageConfigService { })) ); + // Filter out invalid SOs + const newSos = saved_objects.filter((so) => !so.error && so.attributes); + // Assign it to the given agent config await agentConfigService.assignPackageConfigs( soClient, diff --git a/x-pack/plugins/ingest_manager/server/types/models/agent.ts b/x-pack/plugins/ingest_manager/server/types/models/agent.ts index 1b396db9b0c88..ea5eacc8e63d0 100644 --- a/x-pack/plugins/ingest_manager/server/types/models/agent.ts +++ b/x-pack/plugins/ingest_manager/server/types/models/agent.ts @@ -22,13 +22,16 @@ const AgentEventBase = { ]), subtype: schema.oneOf([ // State - schema.literal('RUNNING'), - schema.literal('STARTING'), - schema.literal('IN_PROGRESS'), - schema.literal('CONFIG'), - schema.literal('FAILED'), - schema.literal('STOPPING'), - schema.literal('STOPPED'), + schema.oneOf([ + schema.literal('RUNNING'), + schema.literal('STARTING'), + schema.literal('IN_PROGRESS'), + schema.literal('CONFIG'), + schema.literal('FAILED'), + schema.literal('STOPPING'), + schema.literal('STOPPED'), + schema.literal('DEGRADED'), + ]), // Action results schema.literal('DATA_DUMP'), // Actions diff --git a/x-pack/plugins/lens/public/app_plugin/app.test.tsx b/x-pack/plugins/lens/public/app_plugin/app.test.tsx index 3bd12a87456a0..a72f4f429a1be 100644 --- a/x-pack/plugins/lens/public/app_plugin/app.test.tsx +++ b/x-pack/plugins/lens/public/app_plugin/app.test.tsx @@ -95,6 +95,14 @@ function createMockFilterManager() { }; } +function createMockQueryString() { + return { + getQuery: jest.fn(() => ({ query: '', language: 'kuery' })), + setQuery: jest.fn(), + getDefaultQuery: jest.fn(() => ({ query: '', language: 'kuery' })), + }; +} + function createMockTimefilter() { const unsubscribe = jest.fn(); @@ -148,6 +156,7 @@ describe('Lens App', () => { timefilter: { timefilter: createMockTimefilter(), }, + queryString: createMockQueryString(), state$: new Observable(), }, indexPatterns: { diff --git a/x-pack/plugins/lens/public/app_plugin/app.tsx b/x-pack/plugins/lens/public/app_plugin/app.tsx index 9b8b9a8531cf0..2a7eaff32fa08 100644 --- a/x-pack/plugins/lens/public/app_plugin/app.tsx +++ b/x-pack/plugins/lens/public/app_plugin/app.tsx @@ -36,7 +36,6 @@ import { IndexPattern as IndexPatternInstance, IndexPatternsContract, SavedQuery, - UI_SETTINGS, } from '../../../../../src/plugins/data/public'; interface State { @@ -44,6 +43,7 @@ interface State { isLoading: boolean; isSaveModalVisible: boolean; indexPatternsForTopNav: IndexPatternInstance[]; + originatingApp?: string; persistedDoc?: Document; lastKnownDoc?: Document; @@ -82,21 +82,18 @@ export function App({ onAppLeave: AppMountParameters['onAppLeave']; history: History; }) { - const language = - storage.get('kibana.userQueryLanguage') || - core.uiSettings.get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE); - const [state, setState] = useState(() => { const currentRange = data.query.timefilter.timefilter.getTime(); return { isLoading: !!docId, isSaveModalVisible: false, indexPatternsForTopNav: [], - query: { query: '', language }, + query: data.query.queryString.getDefaultQuery(), dateRange: { fromDate: currentRange.from, toDate: currentRange.to, }, + originatingApp, filters: [], indicateNoData: false, }; @@ -321,9 +318,14 @@ export function App({ .then(({ id }) => { // Prevents unnecessary network request and disables save button const newDoc = { ...doc, id }; + const currentOriginatingApp = state.originatingApp; setState((s) => ({ ...s, isSaveModalVisible: false, + originatingApp: + saveProps.newCopyOnSave && !saveProps.returnToOrigin + ? undefined + : currentOriginatingApp, persistedDoc: newDoc, lastKnownDoc: newDoc, })); @@ -368,7 +370,7 @@ export function App({
{ if (isSaveable && lastKnownDoc) { setState((s) => ({ ...s, isSaveModalVisible: true })); @@ -466,12 +468,7 @@ export function App({ ...s, savedQuery: undefined, filters: data.query.filterManager.getGlobalFilters(), - query: { - query: '', - language: - storage.get('kibana.userQueryLanguage') || - core.uiSettings.get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE), - }, + query: data.query.queryString.getDefaultQuery(), })); }} query={state.query} @@ -523,7 +520,7 @@ export function App({
{lastKnownDoc && state.isSaveModalVisible && ( runSave(props)} onClose={() => setState((s) => ({ ...s, isSaveModalVisible: false }))} documentInfo={{ diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/editor_frame.test.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/editor_frame.test.tsx index ad4f6e74c9e92..2f7a78197b2b2 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/editor_frame.test.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/editor_frame.test.tsx @@ -1007,7 +1007,8 @@ describe('editor_frame', () => { expect(mockVisualization2.initialize).toHaveBeenCalledWith( expect.objectContaining({ datasourceLayers: expect.objectContaining({ first: mockDatasource.publicAPIMock }), - }) + }), + undefined ); expect(mockVisualization2.getConfiguration).toHaveBeenCalledWith( expect.objectContaining({ state: { initial: true } }) diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.test.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.test.tsx index ceced2a7a353c..c78de9d140f76 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.test.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.test.tsx @@ -480,6 +480,34 @@ describe('chart_switch', () => { expect(frame.removeLayers).not.toHaveBeenCalled(); }); + it('should not remove layers and initialize with existing state when switching between subtypes without data', () => { + const dispatch = jest.fn(); + const frame = mockFrame(['a']); + frame.datasourceLayers.a.getTableSpec = jest.fn().mockReturnValue([]); + const visualizations = mockVisualizations(); + visualizations.visC.getSuggestions = jest.fn().mockReturnValue([]); + visualizations.visC.switchVisualizationType = jest.fn(() => 'switched'); + + const component = mount( + + ); + + switchTo('subvisC3', component); + + expect(visualizations.visC.switchVisualizationType).toHaveBeenCalledWith('subvisC3', { + type: 'subvisC1', + }); + expect(frame.removeLayers).not.toHaveBeenCalled(); + }); + it('should switch to the updated datasource state', () => { const dispatch = jest.fn(); const visualizations = mockVisualizations(); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.tsx index 51b4a347af6f1..a0d803d05d98b 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.tsx @@ -160,12 +160,16 @@ export function ChartSwitch(props: Props) { : () => { return switchVisType( subVisualizationId, - newVisualization.initialize(props.framePublicAPI) + newVisualization.initialize( + props.framePublicAPI, + props.visualizationId === newVisualization.id ? props.visualizationState : undefined + ) ); }, keptLayerIds: topSuggestion ? topSuggestion.keptLayerIds : [], datasourceState: topSuggestion ? topSuggestion.datasourceState : undefined, datasourceId: topSuggestion ? topSuggestion.datasourceId : undefined, + sameDatasources: dataLoss === 'nothing' && props.visualizationId === newVisualization.id, }; } diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.tsx index f6e15002ca66c..411488abce77f 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.tsx @@ -63,7 +63,7 @@ export function WorkspacePanelWrapper({ clearStagedPreview: false, }); }, - [dispatch] + [dispatch, activeVisualization] ); return ( <> diff --git a/x-pack/plugins/lens/public/pie_visualization/pie_visualization.tsx b/x-pack/plugins/lens/public/pie_visualization/pie_visualization.tsx index 4f0c081d8be00..369ab28293fbc 100644 --- a/x-pack/plugins/lens/public/pie_visualization/pie_visualization.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/pie_visualization.tsx @@ -13,7 +13,7 @@ import { toExpression, toPreviewExpression } from './to_expression'; import { LayerState, PieVisualizationState } from './types'; import { suggestions } from './suggestions'; import { CHART_NAMES, MAX_PIE_BUCKETS, MAX_TREEMAP_BUCKETS } from './constants'; -import { SettingsWidget } from './settings_widget'; +import { PieToolbar } from './toolbar'; function newLayerState(layerId: string): LayerState { return { @@ -204,10 +204,10 @@ export const pieVisualization: Visualization - + , domElement ); diff --git a/x-pack/plugins/lens/public/pie_visualization/register_expression.tsx b/x-pack/plugins/lens/public/pie_visualization/register_expression.tsx index cea84db8b2794..89d93ab79233f 100644 --- a/x-pack/plugins/lens/public/pie_visualization/register_expression.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/register_expression.tsx @@ -7,6 +7,7 @@ import React from 'react'; import ReactDOM from 'react-dom'; import { i18n } from '@kbn/i18n'; +import { Position } from '@elastic/charts'; import { I18nProvider } from '@kbn/i18n/react'; import { IInterpreterRenderHandlers, @@ -73,6 +74,11 @@ export const pie: ExpressionFunctionDefinition< types: ['boolean'], help: '', }, + legendPosition: { + types: ['string'], + options: [Position.Top, Position.Right, Position.Bottom, Position.Left], + help: '', + }, percentDecimals: { types: ['number'], help: '', diff --git a/x-pack/plugins/lens/public/pie_visualization/render_function.test.tsx b/x-pack/plugins/lens/public/pie_visualization/render_function.test.tsx index cfbeb27efb3d0..38ef44a2fef18 100644 --- a/x-pack/plugins/lens/public/pie_visualization/render_function.test.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/render_function.test.tsx @@ -65,6 +65,13 @@ describe('PieVisualization component', () => { }; } + test('it shows legend on correct side', () => { + const component = shallow( + + ); + expect(component.find(Settings).prop('legendPosition')).toEqual('top'); + }); + test('it shows legend for 2 groups using default legendDisplay', () => { const component = shallow(); expect(component.find(Settings).prop('showLegend')).toEqual(true); diff --git a/x-pack/plugins/lens/public/pie_visualization/render_function.tsx b/x-pack/plugins/lens/public/pie_visualization/render_function.tsx index f349cc4dfd648..79986986b217d 100644 --- a/x-pack/plugins/lens/public/pie_visualization/render_function.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/render_function.tsx @@ -22,6 +22,7 @@ import { PartitionFillLabel, RecursivePartial, LayerValue, + Position, } from '@elastic/charts'; import { FormatFactory, LensFilterEvent } from '../types'; import { VisualizationContainer } from '../visualization_container'; @@ -55,6 +56,7 @@ export function PieComponent( numberDisplay, categoryDisplay, legendDisplay, + legendPosition, nestedLegend, percentDecimals, hideLabels, @@ -237,6 +239,7 @@ export function PieComponent( (legendDisplay === 'show' || (legendDisplay === 'default' && columnGroups.length > 1 && shape !== 'treemap')) } + legendPosition={legendPosition || Position.Right} legendMaxDepth={nestedLegend ? undefined : 1 /* Color is based only on first layer */} onElementClick={(args) => { const context = getFilterContext( diff --git a/x-pack/plugins/lens/public/pie_visualization/settings_widget.scss b/x-pack/plugins/lens/public/pie_visualization/settings_widget.scss deleted file mode 100644 index 4fa328d8a904d..0000000000000 --- a/x-pack/plugins/lens/public/pie_visualization/settings_widget.scss +++ /dev/null @@ -1,3 +0,0 @@ -.lnsPieSettingsWidget { - min-width: $euiSizeXL * 10; -} diff --git a/x-pack/plugins/lens/public/pie_visualization/settings_widget.tsx b/x-pack/plugins/lens/public/pie_visualization/settings_widget.tsx deleted file mode 100644 index e5fde12f74b42..0000000000000 --- a/x-pack/plugins/lens/public/pie_visualization/settings_widget.tsx +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { - EuiForm, - EuiFormRow, - EuiSuperSelect, - EuiRange, - EuiSwitch, - EuiHorizontalRule, - EuiSpacer, - EuiButtonGroup, -} from '@elastic/eui'; -import { DEFAULT_PERCENT_DECIMALS } from './constants'; -import { PieVisualizationState, SharedLayerState } from './types'; -import { VisualizationLayerWidgetProps } from '../types'; -import './settings_widget.scss'; - -const numberOptions: Array<{ value: SharedLayerState['numberDisplay']; inputDisplay: string }> = [ - { - value: 'hidden', - inputDisplay: i18n.translate('xpack.lens.pieChart.hiddenNumbersLabel', { - defaultMessage: 'Hide from chart', - }), - }, - { - value: 'percent', - inputDisplay: i18n.translate('xpack.lens.pieChart.showPercentValuesLabel', { - defaultMessage: 'Show percent', - }), - }, - { - value: 'value', - inputDisplay: i18n.translate('xpack.lens.pieChart.showFormatterValuesLabel', { - defaultMessage: 'Show value', - }), - }, -]; - -const categoryOptions: Array<{ - value: SharedLayerState['categoryDisplay']; - inputDisplay: string; -}> = [ - { - value: 'default', - inputDisplay: i18n.translate('xpack.lens.pieChart.showCategoriesLabel', { - defaultMessage: 'Inside or outside', - }), - }, - { - value: 'inside', - inputDisplay: i18n.translate('xpack.lens.pieChart.fitInsideOnlyLabel', { - defaultMessage: 'Inside only', - }), - }, - { - value: 'hide', - inputDisplay: i18n.translate('xpack.lens.pieChart.categoriesInLegendLabel', { - defaultMessage: 'Hide labels', - }), - }, -]; - -const categoryOptionsTreemap: Array<{ - value: SharedLayerState['categoryDisplay']; - inputDisplay: string; -}> = [ - { - value: 'default', - inputDisplay: i18n.translate('xpack.lens.pieChart.showTreemapCategoriesLabel', { - defaultMessage: 'Show labels', - }), - }, - { - value: 'hide', - inputDisplay: i18n.translate('xpack.lens.pieChart.categoriesInLegendLabel', { - defaultMessage: 'Hide labels', - }), - }, -]; - -const legendOptions: Array<{ - value: SharedLayerState['legendDisplay']; - label: string; - id: string; -}> = [ - { - id: 'pieLegendDisplay-default', - value: 'default', - label: i18n.translate('xpack.lens.pieChart.defaultLegendLabel', { - defaultMessage: 'auto', - }), - }, - { - id: 'pieLegendDisplay-show', - value: 'show', - label: i18n.translate('xpack.lens.pieChart.alwaysShowLegendLabel', { - defaultMessage: 'show', - }), - }, - { - id: 'pieLegendDisplay-hide', - value: 'hide', - label: i18n.translate('xpack.lens.pieChart.hideLegendLabel', { - defaultMessage: 'hide', - }), - }, -]; - -export function SettingsWidget(props: VisualizationLayerWidgetProps) { - const { state, setState } = props; - const layer = state.layers[0]; - if (!layer) { - return null; - } - - return ( - - - { - setState({ - ...state, - layers: [{ ...layer, categoryDisplay: option }], - }); - }} - /> - - - { - setState({ - ...state, - layers: [{ ...layer, numberDisplay: option }], - }); - }} - /> - - - - { - setState({ - ...state, - layers: [{ ...layer, percentDecimals: Number(e.currentTarget.value) }], - }); - }} - /> - - - -
- value === layer.legendDisplay)!.id} - onChange={(optionId) => { - setState({ - ...state, - layers: [ - { - ...layer, - legendDisplay: legendOptions.find(({ id }) => id === optionId)!.value, - }, - ], - }); - }} - buttonSize="compressed" - isFullWidth - /> - - - { - setState({ ...state, layers: [{ ...layer, nestedLegend: !layer.nestedLegend }] }); - }} - /> -
-
-
- ); -} diff --git a/x-pack/plugins/lens/public/pie_visualization/to_expression.ts b/x-pack/plugins/lens/public/pie_visualization/to_expression.ts index cf9d311dfd504..fbc47e8bfb00f 100644 --- a/x-pack/plugins/lens/public/pie_visualization/to_expression.ts +++ b/x-pack/plugins/lens/public/pie_visualization/to_expression.ts @@ -41,6 +41,7 @@ function expressionHelper( numberDisplay: [layer.numberDisplay], categoryDisplay: [layer.categoryDisplay], legendDisplay: [layer.legendDisplay], + legendPosition: [layer.legendPosition || 'right'], percentDecimals: [layer.percentDecimals ?? DEFAULT_PERCENT_DECIMALS], nestedLegend: [!!layer.nestedLegend], }, diff --git a/x-pack/plugins/lens/public/pie_visualization/toolbar.scss b/x-pack/plugins/lens/public/pie_visualization/toolbar.scss new file mode 100644 index 0000000000000..3cfbe6480c61b --- /dev/null +++ b/x-pack/plugins/lens/public/pie_visualization/toolbar.scss @@ -0,0 +1,3 @@ +.lnsPieToolbar__popover { + width: $euiFormMaxWidth; +} diff --git a/x-pack/plugins/lens/public/pie_visualization/toolbar.tsx b/x-pack/plugins/lens/public/pie_visualization/toolbar.tsx new file mode 100644 index 0000000000000..9c3d0d0f34814 --- /dev/null +++ b/x-pack/plugins/lens/public/pie_visualization/toolbar.tsx @@ -0,0 +1,281 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import './toolbar.scss'; +import React, { useState } from 'react'; +import { i18n } from '@kbn/i18n'; +import { + EuiFlexGroup, + EuiFlexItem, + EuiPopover, + EuiSelect, + EuiFormRow, + EuiSuperSelect, + EuiRange, + EuiSwitch, + EuiHorizontalRule, + EuiSpacer, + EuiButtonGroup, +} from '@elastic/eui'; +import { Position } from '@elastic/charts'; +import { DEFAULT_PERCENT_DECIMALS } from './constants'; +import { PieVisualizationState, SharedLayerState } from './types'; +import { VisualizationToolbarProps } from '../types'; +import { ToolbarButton } from '../toolbar_button'; + +const numberOptions: Array<{ value: SharedLayerState['numberDisplay']; inputDisplay: string }> = [ + { + value: 'hidden', + inputDisplay: i18n.translate('xpack.lens.pieChart.hiddenNumbersLabel', { + defaultMessage: 'Hide from chart', + }), + }, + { + value: 'percent', + inputDisplay: i18n.translate('xpack.lens.pieChart.showPercentValuesLabel', { + defaultMessage: 'Show percent', + }), + }, + { + value: 'value', + inputDisplay: i18n.translate('xpack.lens.pieChart.showFormatterValuesLabel', { + defaultMessage: 'Show value', + }), + }, +]; + +const categoryOptions: Array<{ + value: SharedLayerState['categoryDisplay']; + inputDisplay: string; +}> = [ + { + value: 'default', + inputDisplay: i18n.translate('xpack.lens.pieChart.showCategoriesLabel', { + defaultMessage: 'Inside or outside', + }), + }, + { + value: 'inside', + inputDisplay: i18n.translate('xpack.lens.pieChart.fitInsideOnlyLabel', { + defaultMessage: 'Inside only', + }), + }, + { + value: 'hide', + inputDisplay: i18n.translate('xpack.lens.pieChart.categoriesInLegendLabel', { + defaultMessage: 'Hide labels', + }), + }, +]; + +const categoryOptionsTreemap: Array<{ + value: SharedLayerState['categoryDisplay']; + inputDisplay: string; +}> = [ + { + value: 'default', + inputDisplay: i18n.translate('xpack.lens.pieChart.showTreemapCategoriesLabel', { + defaultMessage: 'Show labels', + }), + }, + { + value: 'hide', + inputDisplay: i18n.translate('xpack.lens.pieChart.categoriesInLegendLabel', { + defaultMessage: 'Hide labels', + }), + }, +]; + +const legendOptions: Array<{ + value: SharedLayerState['legendDisplay']; + label: string; + id: string; +}> = [ + { + id: 'pieLegendDisplay-default', + value: 'default', + label: i18n.translate('xpack.lens.pieChart.legendVisibility.auto', { + defaultMessage: 'auto', + }), + }, + { + id: 'pieLegendDisplay-show', + value: 'show', + label: i18n.translate('xpack.lens.pieChart.legendVisibility.show', { + defaultMessage: 'show', + }), + }, + { + id: 'pieLegendDisplay-hide', + value: 'hide', + label: i18n.translate('xpack.lens.pieChart.legendVisibility.hide', { + defaultMessage: 'hide', + }), + }, +]; + +export function PieToolbar(props: VisualizationToolbarProps) { + const [open, setOpen] = useState(false); + const { state, setState } = props; + const layer = state.layers[0]; + if (!layer) { + return null; + } + return ( + + + { + setOpen(!open); + }} + > + {i18n.translate('xpack.lens.pieChart.settingsLabel', { defaultMessage: 'Settings' })} + + } + isOpen={open} + closePopover={() => { + setOpen(false); + }} + anchorPosition="downRight" + > + + { + setState({ + ...state, + layers: [{ ...layer, categoryDisplay: option }], + }); + }} + /> + + + { + setState({ + ...state, + layers: [{ ...layer, numberDisplay: option }], + }); + }} + /> + + + + { + setState({ + ...state, + layers: [{ ...layer, percentDecimals: Number(e.currentTarget.value) }], + }); + }} + /> + + + +
+ value === layer.legendDisplay)!.id} + onChange={(optionId) => { + setState({ + ...state, + layers: [ + { + ...layer, + legendDisplay: legendOptions.find(({ id }) => id === optionId)!.value, + }, + ], + }); + }} + buttonSize="compressed" + isFullWidth + /> + + + { + setState({ ...state, layers: [{ ...layer, nestedLegend: !layer.nestedLegend }] }); + }} + /> +
+
+ + { + setState({ + ...state, + layers: [{ ...layer, legendPosition: e.target.value as Position }], + }); + }} + /> + +
+
+
+ ); +} diff --git a/x-pack/plugins/lens/public/pie_visualization/types.ts b/x-pack/plugins/lens/public/pie_visualization/types.ts index 60b6564248640..74156bce2ea70 100644 --- a/x-pack/plugins/lens/public/pie_visualization/types.ts +++ b/x-pack/plugins/lens/public/pie_visualization/types.ts @@ -13,6 +13,7 @@ export interface SharedLayerState { numberDisplay: 'hidden' | 'percent' | 'value'; categoryDisplay: 'default' | 'inside' | 'hide'; legendDisplay: 'default' | 'show' | 'hide'; + legendPosition?: 'left' | 'right' | 'top' | 'bottom'; nestedLegend?: boolean; percentDecimals?: number; } diff --git a/x-pack/plugins/lens/public/xy_visualization/__snapshots__/to_expression.test.ts.snap b/x-pack/plugins/lens/public/xy_visualization/__snapshots__/to_expression.test.ts.snap index d7d76bdd1f44a..b5783803b803c 100644 --- a/x-pack/plugins/lens/public/xy_visualization/__snapshots__/to_expression.test.ts.snap +++ b/x-pack/plugins/lens/public/xy_visualization/__snapshots__/to_expression.test.ts.snap @@ -64,6 +64,7 @@ Object { "position": Array [ "bottom", ], + "showSingleSeries": Array [], }, "function": "lens_xy_legendConfig", "type": "function", diff --git a/x-pack/plugins/lens/public/xy_visualization/to_expression.ts b/x-pack/plugins/lens/public/xy_visualization/to_expression.ts index 3b9406cedd499..b17704b38cdec 100644 --- a/x-pack/plugins/lens/public/xy_visualization/to_expression.ts +++ b/x-pack/plugins/lens/public/xy_visualization/to_expression.ts @@ -127,6 +127,9 @@ export const buildExpression = ( function: 'lens_xy_legendConfig', arguments: { isVisible: [state.legend.isVisible], + showSingleSeries: state.legend.showSingleSeries + ? [state.legend.showSingleSeries] + : [], position: [state.legend.position], }, }, diff --git a/x-pack/plugins/lens/public/xy_visualization/types.ts b/x-pack/plugins/lens/public/xy_visualization/types.ts index 08f29c65b26d0..605119535d1f0 100644 --- a/x-pack/plugins/lens/public/xy_visualization/types.ts +++ b/x-pack/plugins/lens/public/xy_visualization/types.ts @@ -19,8 +19,18 @@ import { VisualizationType } from '../index'; import { FittingFunction } from './fitting_functions'; export interface LegendConfig { + /** + * Flag whether the legend should be shown. If there is just a single series, it will be hidden + */ isVisible: boolean; + /** + * Position of the legend relative to the chart + */ position: Position; + /** + * Flag whether the legend should be shown even with just a single series + */ + showSingleSeries?: boolean; } type LegendConfigResult = LegendConfig & { type: 'lens_xy_legendConfig' }; @@ -50,6 +60,12 @@ export const legendConfig: ExpressionFunctionDefinition< defaultMessage: 'Specifies the legend position.', }), }, + showSingleSeries: { + types: ['boolean'], + help: i18n.translate('xpack.lens.xyChart.showSingleSeries.help', { + defaultMessage: 'Specifies whether a legend with just a single entry should be shown', + }), + }, }, fn: function fn(input: unknown, args: LegendConfig) { return { diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx index d22b3ec0a44a6..59c4b393df467 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx @@ -7,6 +7,7 @@ import './xy_config_panel.scss'; import React, { useState } from 'react'; import { i18n } from '@kbn/i18n'; +import { Position } from '@elastic/charts'; import { debounce } from 'lodash'; import { EuiButtonGroup, @@ -16,12 +17,14 @@ import { EuiFormRow, EuiPopover, EuiText, + EuiSelect, htmlIdGenerator, EuiForm, EuiColorPicker, EuiColorPickerProps, EuiToolTip, EuiIcon, + EuiHorizontalRule, } from '@elastic/eui'; import { VisualizationLayerWidgetProps, @@ -46,6 +49,30 @@ function updateLayer(state: State, layer: UnwrapArray, index: n }; } +const legendOptions: Array<{ id: string; value: 'auto' | 'show' | 'hide'; label: string }> = [ + { + id: `xy_legend_auto`, + value: 'auto', + label: i18n.translate('xpack.lens.xyChart.legendVisibility.auto', { + defaultMessage: 'auto', + }), + }, + { + id: `xy_legend_show`, + value: 'show', + label: i18n.translate('xpack.lens.xyChart.legendVisibility.show', { + defaultMessage: 'show', + }), + }, + { + id: `xy_legend_hide`, + value: 'hide', + label: i18n.translate('xpack.lens.xyChart.legendVisibility.hide', { + defaultMessage: 'hide', + }), + }, +]; + export function LayerContextMenu(props: VisualizationLayerWidgetProps) { const { state, layerId } = props; const horizontalOnly = isHorizontalChart(state.layers); @@ -95,6 +122,12 @@ export function XyToolbar(props: VisualizationToolbarProps) { const hasNonBarSeries = props.state?.layers.some( (layer) => layer.seriesType === 'line' || layer.seriesType === 'area' ); + const legendMode = + props.state?.legend.isVisible && !props.state?.legend.showSingleSeries + ? 'auto' + : !props.state?.legend.isVisible + ? 'hide' + : 'show'; return ( @@ -157,6 +190,67 @@ export function XyToolbar(props: VisualizationToolbarProps) { /> + + + value === legendMode)!.id} + onChange={(optionId) => { + const newMode = legendOptions.find(({ id }) => id === optionId)!.value; + if (newMode === 'auto') { + props.setState({ + ...props.state, + legend: { ...props.state.legend, isVisible: true, showSingleSeries: false }, + }); + } else if (newMode === 'show') { + props.setState({ + ...props.state, + legend: { ...props.state.legend, isVisible: true, showSingleSeries: true }, + }); + } else if (newMode === 'hide') { + props.setState({ + ...props.state, + legend: { ...props.state.legend, isVisible: false, showSingleSeries: false }, + }); + } + }} + /> + + + { + props.setState({ + ...props.state, + legend: { ...props.state.legend, position: e.target.value as Position }, + }); + }} + /> + diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_expression.test.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_expression.test.tsx index b7a50b3af640c..c880cbb641e5d 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_expression.test.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_expression.test.tsx @@ -1556,6 +1556,73 @@ describe('xy_expression', () => { expect(component.find(Settings).prop('showLegend')).toEqual(true); }); + test('it should always show legend if showSingleSeries is set', () => { + const { data, args } = sampleArgs(); + + const component = shallow( + + ); + + expect(component.find(Settings).prop('showLegend')).toEqual(true); + }); + + test('it not show legend if isVisible is set to false', () => { + const { data, args } = sampleArgs(); + + const component = shallow( + + ); + + expect(component.find(Settings).prop('showLegend')).toEqual(false); + }); + + test('it should show legend on right side', () => { + const { data, args } = sampleArgs(); + + const component = shallow( + + ); + + expect(component.find(Settings).prop('legendPosition')).toEqual('top'); + }); + test('it should apply the fitting function to all non-bar series', () => { const data: LensMultiTable = { type: 'lens_multitable', diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_expression.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_expression.tsx index 3ab12aa0879b0..871b626d62560 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_expression.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_expression.tsx @@ -282,7 +282,11 @@ export function XYChart({ return ( { expect(suggestion.hide).toBeTruthy(); }); + test('keeps existing seriesType for initial tables', () => { + const currentState: XYState = { + legend: { isVisible: true, position: 'bottom' }, + fittingFunction: 'None', + preferredSeriesType: 'line', + layers: [ + { + accessors: [], + layerId: 'first', + seriesType: 'line', + splitAccessor: undefined, + xAccessor: '', + }, + ], + }; + const suggestions = getSuggestions({ + table: { + isMultiRow: true, + columns: [numCol('price'), dateCol('date')], + layerId: 'first', + changeType: 'initial', + }, + state: currentState, + keptLayerIds: ['first'], + }); + + expect(suggestions).toHaveLength(1); + + expect(suggestions[0].hide).toEqual(false); + expect(suggestions[0].state.preferredSeriesType).toEqual('line'); + expect(suggestions[0].state.layers[0].seriesType).toEqual('line'); + }); + test('makes a visible seriesType suggestion for unchanged table without split', () => { const currentState: XYState = { legend: { isVisible: true, position: 'bottom' }, diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts b/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts index d7348f00bf8b8..1be8d566a8b64 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts +++ b/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts @@ -318,11 +318,7 @@ function getSeriesType( return closestSeriesType.startsWith('bar') ? closestSeriesType : defaultType; } - if (changeType === 'initial') { - return defaultType; - } - - return closestSeriesType !== defaultType ? closestSeriesType : defaultType; + return closestSeriesType; } function getSuggestionTitle( diff --git a/x-pack/plugins/lists/common/constants.mock.ts b/x-pack/plugins/lists/common/constants.mock.ts index 4f01d43f47ecd..b7609b5a3602a 100644 --- a/x-pack/plugins/lists/common/constants.mock.ts +++ b/x-pack/plugins/lists/common/constants.mock.ts @@ -3,9 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { EntriesArray } from './schemas/types'; +import moment from 'moment'; +import { EntriesArray } from './schemas/types'; export const DATE_NOW = '2020-04-20T15:25:31.830Z'; +export const OLD_DATE_RELATIVE_TO_DATE_NOW = '2020-04-19T15:25:31.830Z'; export const USER = 'some user'; export const LIST_INDEX = '.lists'; export const LIST_ITEM_INDEX = '.items'; @@ -41,7 +43,7 @@ export const OPERATOR = 'included'; export const ENTRY_VALUE = 'some host name'; export const MATCH = 'match'; export const MATCH_ANY = 'match_any'; -export const MAX_IMPORT_PAYLOAD_BYTES = 40000000; +export const MAX_IMPORT_PAYLOAD_BYTES = 9000000; export const IMPORT_BUFFER_SIZE = 1000; export const LIST = 'list'; export const EXISTS = 'exists'; @@ -63,3 +65,4 @@ export const CURSOR = 'c29tZXN0cmluZ2ZvcnlvdQ=='; export const _VERSION = 'WzI5NywxXQ=='; export const VERSION = 1; export const IMMUTABLE = false; +export const IMPORT_TIMEOUT = moment.duration(5, 'minutes'); diff --git a/x-pack/plugins/lists/common/constants.ts b/x-pack/plugins/lists/common/constants.ts index 7bb83cddd4331..6c73dc1656302 100644 --- a/x-pack/plugins/lists/common/constants.ts +++ b/x-pack/plugins/lists/common/constants.ts @@ -44,7 +44,9 @@ export const ENDPOINT_LIST_ITEM_URL = '/api/endpoint_list/items'; export const ENDPOINT_LIST_ID = 'endpoint_list'; /** The name of the single global space agnostic endpoint list */ -export const ENDPOINT_LIST_NAME = 'Elastic Endpoint Exception List'; +export const ENDPOINT_LIST_NAME = 'Elastic Endpoint Security Exception List'; /** The description of the single global space agnostic endpoint list */ -export const ENDPOINT_LIST_DESCRIPTION = 'Elastic Endpoint Exception List'; +export const ENDPOINT_LIST_DESCRIPTION = 'Elastic Endpoint Security Exception List'; + +export const MAX_EXCEPTION_LIST_SIZE = 10000; diff --git a/x-pack/plugins/lists/common/schemas/request/create_endpoint_list_item_schema.test.ts b/x-pack/plugins/lists/common/schemas/request/create_endpoint_list_item_schema.test.ts index 5de9fbb0d5b50..75e0410be610a 100644 --- a/x-pack/plugins/lists/common/schemas/request/create_endpoint_list_item_schema.test.ts +++ b/x-pack/plugins/lists/common/schemas/request/create_endpoint_list_item_schema.test.ts @@ -8,8 +8,8 @@ import { left } from 'fp-ts/lib/Either'; import { pipe } from 'fp-ts/lib/pipeable'; import { exactCheck, foldLeftRight, getPaths } from '../../siem_common_deps'; -import { getCreateCommentsArrayMock } from '../types/create_comments.mock'; -import { getCommentsMock } from '../types/comments.mock'; +import { getCreateCommentsArrayMock } from '../types/create_comment.mock'; +import { getCommentsMock } from '../types/comment.mock'; import { CommentsArray } from '../types'; import { @@ -19,7 +19,7 @@ import { import { getCreateEndpointListItemSchemaMock } from './create_endpoint_list_item_schema.mock'; describe('create_endpoint_list_item_schema', () => { - test('it should validate a typical list item request not counting the auto generated uuid', () => { + test('it should pass validation when supplied a typical list item request not counting the auto generated uuid', () => { const payload = getCreateEndpointListItemSchemaMock(); const decoded = createEndpointListItemSchema.decode(payload); const checked = exactCheck(payload, decoded); @@ -29,7 +29,7 @@ describe('create_endpoint_list_item_schema', () => { expect(message.schema).toEqual(payload); }); - test('it should not validate an undefined for "description"', () => { + test('it should fail validation when supplied an undefined for "description"', () => { const payload = getCreateEndpointListItemSchemaMock(); delete payload.description; const decoded = createEndpointListItemSchema.decode(payload); @@ -41,7 +41,7 @@ describe('create_endpoint_list_item_schema', () => { expect(message.schema).toEqual({}); }); - test('it should not validate an undefined for "name"', () => { + test('it should fail validation when supplied an undefined for "name"', () => { const payload = getCreateEndpointListItemSchemaMock(); delete payload.name; const decoded = createEndpointListItemSchema.decode(payload); @@ -53,7 +53,7 @@ describe('create_endpoint_list_item_schema', () => { expect(message.schema).toEqual({}); }); - test('it should not validate an undefined for "type"', () => { + test('it should fail validation when supplied an undefined for "type"', () => { const payload = getCreateEndpointListItemSchemaMock(); delete payload.type; const decoded = createEndpointListItemSchema.decode(payload); @@ -65,7 +65,7 @@ describe('create_endpoint_list_item_schema', () => { expect(message.schema).toEqual({}); }); - test('it should not validate a "list_id" since it does not required one', () => { + test('it should fail validation when supplied a "list_id" since it does not required one', () => { const inputPayload: CreateEndpointListItemSchema & { list_id: string } = { ...getCreateEndpointListItemSchemaMock(), list_id: 'list-123', @@ -77,7 +77,7 @@ describe('create_endpoint_list_item_schema', () => { expect(message.schema).toEqual({}); }); - test('it should not validate a "namespace_type" since it does not required one', () => { + test('it should fail validation when supplied a "namespace_type" since it does not required one', () => { const inputPayload: CreateEndpointListItemSchema & { namespace_type: string } = { ...getCreateEndpointListItemSchemaMock(), namespace_type: 'single', @@ -89,7 +89,7 @@ describe('create_endpoint_list_item_schema', () => { expect(message.schema).toEqual({}); }); - test('it should validate an undefined for "meta" but strip it out and generate a correct body not counting the auto generated uuid', () => { + test('it should pass validation when supplied an undefined for "meta" but strip it out and generate a correct body not counting the auto generated uuid', () => { const payload = getCreateEndpointListItemSchemaMock(); const outputPayload = getCreateEndpointListItemSchemaMock(); delete payload.meta; @@ -102,7 +102,7 @@ describe('create_endpoint_list_item_schema', () => { expect(message.schema).toEqual(outputPayload); }); - test('it should validate an undefined for "comments" but return an array and generate a correct body not counting the auto generated uuid', () => { + test('it should pass validation when supplied an undefined for "comments" but return an array and generate a correct body not counting the auto generated uuid', () => { const inputPayload = getCreateEndpointListItemSchemaMock(); const outputPayload = getCreateEndpointListItemSchemaMock(); delete inputPayload.comments; @@ -115,7 +115,7 @@ describe('create_endpoint_list_item_schema', () => { expect(message.schema).toEqual(outputPayload); }); - test('it should validate "comments" array', () => { + test('it should pass validation when supplied "comments" array', () => { const inputPayload = { ...getCreateEndpointListItemSchemaMock(), comments: getCreateCommentsArrayMock(), @@ -128,7 +128,7 @@ describe('create_endpoint_list_item_schema', () => { expect(message.schema).toEqual(inputPayload); }); - test('it should NOT validate "comments" with "created_at" or "created_by" values', () => { + test('it should fail validation when supplied "comments" with "created_at", "created_by", or "id" values', () => { const inputPayload: Omit & { comments?: CommentsArray; } = { @@ -138,11 +138,11 @@ describe('create_endpoint_list_item_schema', () => { const decoded = createEndpointListItemSchema.decode(inputPayload); const checked = exactCheck(inputPayload, decoded); const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "created_at,created_by"']); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "created_at,created_by,id"']); expect(message.schema).toEqual({}); }); - test('it should NOT validate an undefined for "entries"', () => { + test('it should fail validation when supplied an undefined for "entries"', () => { const inputPayload = getCreateEndpointListItemSchemaMock(); const outputPayload = getCreateEndpointListItemSchemaMock(); delete inputPayload.entries; @@ -157,7 +157,7 @@ describe('create_endpoint_list_item_schema', () => { expect(message.schema).toEqual({}); }); - test('it should validate an undefined for "tags" but return an array and generate a correct body not counting the auto generated uuid', () => { + test('it should pass validation when supplied an undefined for "tags" but return an array and generate a correct body not counting the auto generated uuid', () => { const inputPayload = getCreateEndpointListItemSchemaMock(); const outputPayload = getCreateEndpointListItemSchemaMock(); delete inputPayload.tags; @@ -170,7 +170,7 @@ describe('create_endpoint_list_item_schema', () => { expect(message.schema).toEqual(outputPayload); }); - test('it should validate an undefined for "_tags" but return an array and generate a correct body not counting the auto generated uuid', () => { + test('it should pass validation when supplied an undefined for "_tags" but return an array and generate a correct body not counting the auto generated uuid', () => { const inputPayload = getCreateEndpointListItemSchemaMock(); const outputPayload = getCreateEndpointListItemSchemaMock(); delete inputPayload._tags; @@ -183,7 +183,7 @@ describe('create_endpoint_list_item_schema', () => { expect(message.schema).toEqual(outputPayload); }); - test('it should validate an undefined for "item_id" and auto generate a uuid', () => { + test('it should pass validation when supplied an undefined for "item_id" and auto generate a uuid', () => { const inputPayload = getCreateEndpointListItemSchemaMock(); delete inputPayload.item_id; const decoded = createEndpointListItemSchema.decode(inputPayload); @@ -195,7 +195,7 @@ describe('create_endpoint_list_item_schema', () => { ); }); - test('it should validate an undefined for "item_id" and generate a correct body not counting the uuid', () => { + test('it should pass validation when supplied an undefined for "item_id" and generate a correct body not counting the uuid', () => { const inputPayload = getCreateEndpointListItemSchemaMock(); delete inputPayload.item_id; const decoded = createEndpointListItemSchema.decode(inputPayload); diff --git a/x-pack/plugins/lists/common/schemas/request/create_exception_list_item_schema.test.ts b/x-pack/plugins/lists/common/schemas/request/create_exception_list_item_schema.test.ts index 08f3966af08d9..cf4c1fea0306f 100644 --- a/x-pack/plugins/lists/common/schemas/request/create_exception_list_item_schema.test.ts +++ b/x-pack/plugins/lists/common/schemas/request/create_exception_list_item_schema.test.ts @@ -8,8 +8,8 @@ import { left } from 'fp-ts/lib/Either'; import { pipe } from 'fp-ts/lib/pipeable'; import { exactCheck, foldLeftRight, getPaths } from '../../siem_common_deps'; -import { getCreateCommentsArrayMock } from '../types/create_comments.mock'; -import { getCommentsMock } from '../types/comments.mock'; +import { getCreateCommentsArrayMock } from '../types/create_comment.mock'; +import { getCommentsMock } from '../types/comment.mock'; import { CommentsArray } from '../types'; import { @@ -19,7 +19,7 @@ import { import { getCreateExceptionListItemSchemaMock } from './create_exception_list_item_schema.mock'; describe('create_exception_list_item_schema', () => { - test('it should validate a typical exception list item request not counting the auto generated uuid', () => { + test('it should pass validation when supplied a typical exception list item request not counting the auto generated uuid', () => { const payload = getCreateExceptionListItemSchemaMock(); const decoded = createExceptionListItemSchema.decode(payload); const checked = exactCheck(payload, decoded); @@ -29,7 +29,7 @@ describe('create_exception_list_item_schema', () => { expect(message.schema).toEqual(payload); }); - test('it should not validate an undefined for "description"', () => { + test('it should fail validation when supplied an undefined for "description"', () => { const payload = getCreateExceptionListItemSchemaMock(); delete payload.description; const decoded = createExceptionListItemSchema.decode(payload); @@ -41,7 +41,7 @@ describe('create_exception_list_item_schema', () => { expect(message.schema).toEqual({}); }); - test('it should not validate an undefined for "name"', () => { + test('it should fail validation when supplied an undefined for "name"', () => { const payload = getCreateExceptionListItemSchemaMock(); delete payload.name; const decoded = createExceptionListItemSchema.decode(payload); @@ -53,7 +53,7 @@ describe('create_exception_list_item_schema', () => { expect(message.schema).toEqual({}); }); - test('it should not validate an undefined for "type"', () => { + test('it should fail validation when supplied an undefined for "type"', () => { const payload = getCreateExceptionListItemSchemaMock(); delete payload.type; const decoded = createExceptionListItemSchema.decode(payload); @@ -65,7 +65,7 @@ describe('create_exception_list_item_schema', () => { expect(message.schema).toEqual({}); }); - test('it should not validate an undefined for "list_id"', () => { + test('it should fail validation when supplied an undefined for "list_id"', () => { const inputPayload = getCreateExceptionListItemSchemaMock(); delete inputPayload.list_id; const decoded = createExceptionListItemSchema.decode(inputPayload); @@ -77,7 +77,7 @@ describe('create_exception_list_item_schema', () => { expect(message.schema).toEqual({}); }); - test('it should validate an undefined for "meta" but strip it out and generate a correct body not counting the auto generated uuid', () => { + test('it should pass validation when supplied an undefined for "meta" but strip it out and generate a correct body not counting the auto generated uuid', () => { const payload = getCreateExceptionListItemSchemaMock(); const outputPayload = getCreateExceptionListItemSchemaMock(); delete payload.meta; @@ -90,7 +90,7 @@ describe('create_exception_list_item_schema', () => { expect(message.schema).toEqual(outputPayload); }); - test('it should validate an undefined for "comments" but return an array and generate a correct body not counting the auto generated uuid', () => { + test('it should pass validation when supplied an undefined for "comments" but return an array and generate a correct body not counting the auto generated uuid', () => { const inputPayload = getCreateExceptionListItemSchemaMock(); const outputPayload = getCreateExceptionListItemSchemaMock(); delete inputPayload.comments; @@ -103,7 +103,7 @@ describe('create_exception_list_item_schema', () => { expect(message.schema).toEqual(outputPayload); }); - test('it should validate "comments" array', () => { + test('it should pass validation when supplied "comments" array', () => { const inputPayload = { ...getCreateExceptionListItemSchemaMock(), comments: getCreateCommentsArrayMock(), @@ -116,7 +116,7 @@ describe('create_exception_list_item_schema', () => { expect(message.schema).toEqual(inputPayload); }); - test('it should NOT validate "comments" with "created_at" or "created_by" values', () => { + test('it should fail validation when supplied "comments" with "created_at" or "created_by" values', () => { const inputPayload: Omit & { comments?: CommentsArray; } = { @@ -126,11 +126,11 @@ describe('create_exception_list_item_schema', () => { const decoded = createExceptionListItemSchema.decode(inputPayload); const checked = exactCheck(inputPayload, decoded); const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "created_at,created_by"']); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "created_at,created_by,id"']); expect(message.schema).toEqual({}); }); - test('it should NOT validate an undefined for "entries"', () => { + test('it should fail validation when supplied an undefined for "entries"', () => { const inputPayload = getCreateExceptionListItemSchemaMock(); const outputPayload = getCreateExceptionListItemSchemaMock(); delete inputPayload.entries; @@ -145,7 +145,7 @@ describe('create_exception_list_item_schema', () => { expect(message.schema).toEqual({}); }); - test('it should validate an undefined for "namespace_type" but return enum "single" and generate a correct body not counting the auto generated uuid', () => { + test('it should pass validation when supplied an undefined for "namespace_type" but return enum "single" and generate a correct body not counting the auto generated uuid', () => { const inputPayload = getCreateExceptionListItemSchemaMock(); const outputPayload = getCreateExceptionListItemSchemaMock(); delete inputPayload.namespace_type; @@ -158,7 +158,7 @@ describe('create_exception_list_item_schema', () => { expect(message.schema).toEqual(outputPayload); }); - test('it should validate an undefined for "tags" but return an array and generate a correct body not counting the auto generated uuid', () => { + test('it should pass validation when supplied an undefined for "tags" but return an array and generate a correct body not counting the auto generated uuid', () => { const inputPayload = getCreateExceptionListItemSchemaMock(); const outputPayload = getCreateExceptionListItemSchemaMock(); delete inputPayload.tags; @@ -171,7 +171,7 @@ describe('create_exception_list_item_schema', () => { expect(message.schema).toEqual(outputPayload); }); - test('it should validate an undefined for "_tags" but return an array and generate a correct body not counting the auto generated uuid', () => { + test('it should pass validation when supplied an undefined for "_tags" but return an array and generate a correct body not counting the auto generated uuid', () => { const inputPayload = getCreateExceptionListItemSchemaMock(); const outputPayload = getCreateExceptionListItemSchemaMock(); delete inputPayload._tags; @@ -184,7 +184,7 @@ describe('create_exception_list_item_schema', () => { expect(message.schema).toEqual(outputPayload); }); - test('it should validate an undefined for "item_id" and auto generate a uuid', () => { + test('it should pass validation when supplied an undefined for "item_id" and auto generate a uuid', () => { const inputPayload = getCreateExceptionListItemSchemaMock(); delete inputPayload.item_id; const decoded = createExceptionListItemSchema.decode(inputPayload); @@ -196,7 +196,7 @@ describe('create_exception_list_item_schema', () => { ); }); - test('it should validate an undefined for "item_id" and generate a correct body not counting the uuid', () => { + test('it should pass validation when supplied an undefined for "item_id" and generate a correct body not counting the uuid', () => { const inputPayload = getCreateExceptionListItemSchemaMock(); delete inputPayload.item_id; const decoded = createExceptionListItemSchema.decode(inputPayload); diff --git a/x-pack/plugins/lists/common/schemas/request/update_exception_list_item_validation.test.ts b/x-pack/plugins/lists/common/schemas/request/update_exception_list_item_validation.test.ts new file mode 100644 index 0000000000000..3358582786cc7 --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/request/update_exception_list_item_validation.test.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { getUpdateExceptionListItemSchemaMock } from './update_exception_list_item_schema.mock'; +import { validateComments } from './update_exception_list_item_validation'; + +describe('update_exception_list_item_validation', () => { + describe('#validateComments', () => { + test('it returns no errors if comments is undefined', () => { + const payload = getUpdateExceptionListItemSchemaMock(); + delete payload.comments; + const output = validateComments(payload); + + expect(output).toEqual([]); + }); + + test('it returns no errors if new comments are append only', () => { + const payload = getUpdateExceptionListItemSchemaMock(); + payload.comments = [ + { comment: 'Im an old comment', id: '1' }, + { comment: 'Im a new comment' }, + ]; + const output = validateComments(payload); + + expect(output).toEqual([]); + }); + + test('it returns error if comments are not append only', () => { + const payload = getUpdateExceptionListItemSchemaMock(); + payload.comments = [ + { comment: 'Im an old comment', id: '1' }, + { comment: 'Im a new comment modifying the order of existing comments' }, + { comment: 'Im an old comment', id: '2' }, + ]; + const output = validateComments(payload); + + expect(output).toEqual(['item "comments" are append only']); + }); + }); +}); diff --git a/x-pack/plugins/lists/common/schemas/request/update_exception_list_item_validation.ts b/x-pack/plugins/lists/common/schemas/request/update_exception_list_item_validation.ts new file mode 100644 index 0000000000000..5e44c4e9f73e7 --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/request/update_exception_list_item_validation.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { UpdateExceptionListItemSchema } from './update_exception_list_item_schema'; + +export const validateComments = (item: UpdateExceptionListItemSchema): string[] => { + if (item.comments == null) { + return []; + } + + const [appendOnly] = item.comments.reduce( + (acc, comment) => { + const [, hasNewComments] = acc; + if (comment.id == null) { + return [true, true]; + } + + if (hasNewComments && comment.id != null) { + return [false, true]; + } + + return acc; + }, + [true, false] + ); + if (!appendOnly) { + return ['item "comments" are append only']; + } else { + return []; + } +}; + +export const updateExceptionListItemValidate = ( + schema: UpdateExceptionListItemSchema +): string[] => { + return [...validateComments(schema)]; +}; diff --git a/x-pack/plugins/lists/common/schemas/types/comments.mock.ts b/x-pack/plugins/lists/common/schemas/types/comment.mock.ts similarity index 71% rename from x-pack/plugins/lists/common/schemas/types/comments.mock.ts rename to x-pack/plugins/lists/common/schemas/types/comment.mock.ts index 9e56ac292f8b5..213259b3cce29 100644 --- a/x-pack/plugins/lists/common/schemas/types/comments.mock.ts +++ b/x-pack/plugins/lists/common/schemas/types/comment.mock.ts @@ -4,14 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { DATE_NOW, USER } from '../../constants.mock'; +import { DATE_NOW, ID, USER } from '../../constants.mock'; -import { Comments, CommentsArray } from './comments'; +import { Comment, CommentsArray } from './comment'; -export const getCommentsMock = (): Comments => ({ +export const getCommentsMock = (): Comment => ({ comment: 'some old comment', created_at: DATE_NOW, created_by: USER, + id: ID, }); export const getCommentsArrayMock = (): CommentsArray => [getCommentsMock(), getCommentsMock()]; diff --git a/x-pack/plugins/lists/common/schemas/types/comments.test.ts b/x-pack/plugins/lists/common/schemas/types/comment.test.ts similarity index 56% rename from x-pack/plugins/lists/common/schemas/types/comments.test.ts rename to x-pack/plugins/lists/common/schemas/types/comment.test.ts index 29bfde03abcc8..c7c945277f756 100644 --- a/x-pack/plugins/lists/common/schemas/types/comments.test.ts +++ b/x-pack/plugins/lists/common/schemas/types/comment.test.ts @@ -10,56 +10,79 @@ import { left } from 'fp-ts/lib/Either'; import { DATE_NOW } from '../../constants.mock'; import { foldLeftRight, getPaths } from '../../siem_common_deps'; -import { getCommentsArrayMock, getCommentsMock } from './comments.mock'; +import { getCommentsArrayMock, getCommentsMock } from './comment.mock'; import { - Comments, + Comment, CommentsArray, CommentsArrayOrUndefined, - comments, + comment, commentsArray, commentsArrayOrUndefined, -} from './comments'; +} from './comment'; -describe('Comments', () => { - describe('comments', () => { - test('it should validate a comments', () => { +describe('Comment', () => { + describe('comment', () => { + test('it fails validation when "id" is undefined', () => { + const payload = { ...getCommentsMock(), id: undefined }; + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it passes validation with a typical comment', () => { const payload = getCommentsMock(); - const decoded = comments.decode(payload); + const decoded = comment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([]); expect(message.schema).toEqual(payload); }); - test('it should validate with "updated_at" and "updated_by"', () => { + test('it passes validation with "updated_at" and "updated_by" fields included', () => { const payload = getCommentsMock(); payload.updated_at = DATE_NOW; payload.updated_by = 'someone'; - const decoded = comments.decode(payload); + const decoded = comment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([]); expect(message.schema).toEqual(payload); }); - test('it should not validate when undefined', () => { + test('it fails validation when undefined', () => { const payload = undefined; - const decoded = comments.decode(payload); + const decoded = comment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>)"', - 'Invalid value "undefined" supplied to "({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>)"', + 'Invalid value "undefined" supplied to "({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)"', + 'Invalid value "undefined" supplied to "({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)"', ]); expect(message.schema).toEqual({}); }); - test('it should not validate when "comment" is not a string', () => { - const payload: Omit & { comment: string[] } = { + test('it fails validation when "comment" is an empty string', () => { + const payload: Omit & { comment: string } = { + ...getCommentsMock(), + comment: '', + }; + const decoded = comment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "comment"']); + expect(message.schema).toEqual({}); + }); + + test('it fails validation when "comment" is not a string', () => { + const payload: Omit & { comment: string[] } = { ...getCommentsMock(), comment: ['some value'], }; - const decoded = comments.decode(payload); + const decoded = comment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ @@ -68,12 +91,12 @@ describe('Comments', () => { expect(message.schema).toEqual({}); }); - test('it should not validate when "created_at" is not a string', () => { - const payload: Omit & { created_at: number } = { + test('it fails validation when "created_at" is not a string', () => { + const payload: Omit & { created_at: number } = { ...getCommentsMock(), created_at: 1, }; - const decoded = comments.decode(payload); + const decoded = comment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ @@ -82,12 +105,12 @@ describe('Comments', () => { expect(message.schema).toEqual({}); }); - test('it should not validate when "created_by" is not a string', () => { - const payload: Omit & { created_by: number } = { + test('it fails validation when "created_by" is not a string', () => { + const payload: Omit & { created_by: number } = { ...getCommentsMock(), created_by: 1, }; - const decoded = comments.decode(payload); + const decoded = comment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ @@ -96,12 +119,12 @@ describe('Comments', () => { expect(message.schema).toEqual({}); }); - test('it should not validate when "updated_at" is not a string', () => { - const payload: Omit & { updated_at: number } = { + test('it fails validation when "updated_at" is not a string', () => { + const payload: Omit & { updated_at: number } = { ...getCommentsMock(), updated_at: 1, }; - const decoded = comments.decode(payload); + const decoded = comment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ @@ -110,12 +133,12 @@ describe('Comments', () => { expect(message.schema).toEqual({}); }); - test('it should not validate when "updated_by" is not a string', () => { - const payload: Omit & { updated_by: number } = { + test('it fails validation when "updated_by" is not a string', () => { + const payload: Omit & { updated_by: number } = { ...getCommentsMock(), updated_by: 1, }; - const decoded = comments.decode(payload); + const decoded = comment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ @@ -125,11 +148,11 @@ describe('Comments', () => { }); test('it should strip out extra keys', () => { - const payload: Comments & { + const payload: Comment & { extraKey?: string; } = getCommentsMock(); payload.extraKey = 'some value'; - const decoded = comments.decode(payload); + const decoded = comment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([]); @@ -138,7 +161,7 @@ describe('Comments', () => { }); describe('commentsArray', () => { - test('it should validate an array of comments', () => { + test('it passes validation an array of Comment', () => { const payload = getCommentsArrayMock(); const decoded = commentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -147,7 +170,7 @@ describe('Comments', () => { expect(message.schema).toEqual(payload); }); - test('it should validate when a comments includes "updated_at" and "updated_by"', () => { + test('it passes validation when a Comment includes "updated_at" and "updated_by"', () => { const commentsPayload = getCommentsMock(); commentsPayload.updated_at = DATE_NOW; commentsPayload.updated_by = 'someone'; @@ -159,32 +182,32 @@ describe('Comments', () => { expect(message.schema).toEqual(payload); }); - test('it should not validate when undefined', () => { + test('it fails validation when undefined', () => { const payload = undefined; const decoded = commentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "Array<({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + 'Invalid value "undefined" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', ]); expect(message.schema).toEqual({}); }); - test('it should not validate when array includes non comments types', () => { + test('it fails validation when array includes non Comment types', () => { const payload = ([1] as unknown) as CommentsArray; const decoded = commentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>)>"', - 'Invalid value "1" supplied to "Array<({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', ]); expect(message.schema).toEqual({}); }); }); describe('commentsArrayOrUndefined', () => { - test('it should validate an array of comments', () => { + test('it passes validation an array of Comment', () => { const payload = getCommentsArrayMock(); const decoded = commentsArrayOrUndefined.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -193,7 +216,7 @@ describe('Comments', () => { expect(message.schema).toEqual(payload); }); - test('it should validate when undefined', () => { + test('it passes validation when undefined', () => { const payload = undefined; const decoded = commentsArrayOrUndefined.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -202,14 +225,14 @@ describe('Comments', () => { expect(message.schema).toEqual(payload); }); - test('it should not validate when array includes non comments types', () => { + test('it fails validation when array includes non Comment types', () => { const payload = ([1] as unknown) as CommentsArrayOrUndefined; const decoded = commentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>)>"', - 'Invalid value "1" supplied to "Array<({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', ]); expect(message.schema).toEqual({}); }); diff --git a/x-pack/plugins/lists/common/schemas/types/comments.ts b/x-pack/plugins/lists/common/schemas/types/comment.ts similarity index 56% rename from x-pack/plugins/lists/common/schemas/types/comments.ts rename to x-pack/plugins/lists/common/schemas/types/comment.ts index 0ee3b05c8102f..6b0b0166b9ee1 100644 --- a/x-pack/plugins/lists/common/schemas/types/comments.ts +++ b/x-pack/plugins/lists/common/schemas/types/comment.ts @@ -3,26 +3,33 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ + +/* eslint-disable @typescript-eslint/camelcase */ + import * as t from 'io-ts'; -export const comments = t.intersection([ +import { NonEmptyString } from '../../siem_common_deps'; +import { created_at, created_by, id, updated_at, updated_by } from '../common/schemas'; + +export const comment = t.intersection([ t.exact( t.type({ - comment: t.string, - created_at: t.string, // TODO: Make this into an ISO Date string check, - created_by: t.string, + comment: NonEmptyString, + created_at, + created_by, + id, }) ), t.exact( t.partial({ - updated_at: t.string, - updated_by: t.string, + updated_at, + updated_by, }) ), ]); -export const commentsArray = t.array(comments); +export const commentsArray = t.array(comment); export type CommentsArray = t.TypeOf; -export type Comments = t.TypeOf; +export type Comment = t.TypeOf; export const commentsArrayOrUndefined = t.union([commentsArray, t.undefined]); export type CommentsArrayOrUndefined = t.TypeOf; diff --git a/x-pack/plugins/lists/common/schemas/types/create_comments.mock.ts b/x-pack/plugins/lists/common/schemas/types/create_comment.mock.ts similarity index 73% rename from x-pack/plugins/lists/common/schemas/types/create_comments.mock.ts rename to x-pack/plugins/lists/common/schemas/types/create_comment.mock.ts index 60a59432275ca..689d4ccdc2c2e 100644 --- a/x-pack/plugins/lists/common/schemas/types/create_comments.mock.ts +++ b/x-pack/plugins/lists/common/schemas/types/create_comment.mock.ts @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { CreateComments, CreateCommentsArray } from './create_comments'; +import { CreateComment, CreateCommentsArray } from './create_comment'; -export const getCreateCommentsMock = (): CreateComments => ({ +export const getCreateCommentsMock = (): CreateComment => ({ comment: 'some comments', }); diff --git a/x-pack/plugins/lists/common/schemas/types/create_comments.test.ts b/x-pack/plugins/lists/common/schemas/types/create_comment.test.ts similarity index 72% rename from x-pack/plugins/lists/common/schemas/types/create_comments.test.ts rename to x-pack/plugins/lists/common/schemas/types/create_comment.test.ts index d2680750e05e4..366bf84d48bbf 100644 --- a/x-pack/plugins/lists/common/schemas/types/create_comments.test.ts +++ b/x-pack/plugins/lists/common/schemas/types/create_comment.test.ts @@ -9,44 +9,44 @@ import { left } from 'fp-ts/lib/Either'; import { foldLeftRight, getPaths } from '../../siem_common_deps'; -import { getCreateCommentsArrayMock, getCreateCommentsMock } from './create_comments.mock'; +import { getCreateCommentsArrayMock, getCreateCommentsMock } from './create_comment.mock'; import { - CreateComments, + CreateComment, CreateCommentsArray, CreateCommentsArrayOrUndefined, - createComments, + createComment, createCommentsArray, createCommentsArrayOrUndefined, -} from './create_comments'; +} from './create_comment'; -describe('CreateComments', () => { - describe('createComments', () => { - test('it should validate a comments', () => { +describe('CreateComment', () => { + describe('createComment', () => { + test('it passes validation with a default comment', () => { const payload = getCreateCommentsMock(); - const decoded = createComments.decode(payload); + const decoded = createComment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([]); expect(message.schema).toEqual(payload); }); - test('it should not validate when undefined', () => { + test('it fails validation when undefined', () => { const payload = undefined; - const decoded = createComments.decode(payload); + const decoded = createComment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "{| comment: string |}"', + 'Invalid value "undefined" supplied to "{| comment: NonEmptyString |}"', ]); expect(message.schema).toEqual({}); }); - test('it should not validate when "comment" is not a string', () => { - const payload: Omit & { comment: string[] } = { + test('it fails validation when "comment" is not a string', () => { + const payload: Omit & { comment: string[] } = { ...getCreateCommentsMock(), comment: ['some value'], }; - const decoded = createComments.decode(payload); + const decoded = createComment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ @@ -56,11 +56,11 @@ describe('CreateComments', () => { }); test('it should strip out extra keys', () => { - const payload: CreateComments & { + const payload: CreateComment & { extraKey?: string; } = getCreateCommentsMock(); payload.extraKey = 'some value'; - const decoded = createComments.decode(payload); + const decoded = createComment.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([]); @@ -69,7 +69,7 @@ describe('CreateComments', () => { }); describe('createCommentsArray', () => { - test('it should validate an array of comments', () => { + test('it passes validation an array of comments', () => { const payload = getCreateCommentsArrayMock(); const decoded = createCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -78,31 +78,31 @@ describe('CreateComments', () => { expect(message.schema).toEqual(payload); }); - test('it should not validate when undefined', () => { + test('it fails validation when undefined', () => { const payload = undefined; const decoded = createCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "Array<{| comment: string |}>"', + 'Invalid value "undefined" supplied to "Array<{| comment: NonEmptyString |}>"', ]); expect(message.schema).toEqual({}); }); - test('it should not validate when array includes non comments types', () => { + test('it fails validation when array includes non comments types', () => { const payload = ([1] as unknown) as CreateCommentsArray; const decoded = createCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<{| comment: string |}>"', + 'Invalid value "1" supplied to "Array<{| comment: NonEmptyString |}>"', ]); expect(message.schema).toEqual({}); }); }); describe('createCommentsArrayOrUndefined', () => { - test('it should validate an array of comments', () => { + test('it passes validation an array of comments', () => { const payload = getCreateCommentsArrayMock(); const decoded = createCommentsArrayOrUndefined.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -111,7 +111,7 @@ describe('CreateComments', () => { expect(message.schema).toEqual(payload); }); - test('it should validate when undefined', () => { + test('it passes validation when undefined', () => { const payload = undefined; const decoded = createCommentsArrayOrUndefined.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -120,13 +120,13 @@ describe('CreateComments', () => { expect(message.schema).toEqual(payload); }); - test('it should not validate when array includes non comments types', () => { + test('it fails validation when array includes non comments types', () => { const payload = ([1] as unknown) as CreateCommentsArrayOrUndefined; const decoded = createCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<{| comment: string |}>"', + 'Invalid value "1" supplied to "Array<{| comment: NonEmptyString |}>"', ]); expect(message.schema).toEqual({}); }); diff --git a/x-pack/plugins/lists/common/schemas/types/create_comments.ts b/x-pack/plugins/lists/common/schemas/types/create_comment.ts similarity index 64% rename from x-pack/plugins/lists/common/schemas/types/create_comments.ts rename to x-pack/plugins/lists/common/schemas/types/create_comment.ts index c34419298ef93..fd33313430ce6 100644 --- a/x-pack/plugins/lists/common/schemas/types/create_comments.ts +++ b/x-pack/plugins/lists/common/schemas/types/create_comment.ts @@ -5,14 +5,17 @@ */ import * as t from 'io-ts'; -export const createComments = t.exact( +import { NonEmptyString } from '../../siem_common_deps'; + +export const createComment = t.exact( t.type({ - comment: t.string, + comment: NonEmptyString, }) ); -export const createCommentsArray = t.array(createComments); +export type CreateComment = t.TypeOf; +export const createCommentsArray = t.array(createComment); export type CreateCommentsArray = t.TypeOf; -export type CreateComments = t.TypeOf; +export type CreateComments = t.TypeOf; export const createCommentsArrayOrUndefined = t.union([createCommentsArray, t.undefined]); export type CreateCommentsArrayOrUndefined = t.TypeOf; diff --git a/x-pack/plugins/lists/common/schemas/types/default_comments_array.test.ts b/x-pack/plugins/lists/common/schemas/types/default_comments_array.test.ts index 3a4241aaec82d..541b8ab1c799c 100644 --- a/x-pack/plugins/lists/common/schemas/types/default_comments_array.test.ts +++ b/x-pack/plugins/lists/common/schemas/types/default_comments_array.test.ts @@ -10,11 +10,11 @@ import { left } from 'fp-ts/lib/Either'; import { foldLeftRight, getPaths } from '../../siem_common_deps'; import { DefaultCommentsArray } from './default_comments_array'; -import { CommentsArray } from './comments'; -import { getCommentsArrayMock } from './comments.mock'; +import { CommentsArray } from './comment'; +import { getCommentsArrayMock } from './comment.mock'; describe('default_comments_array', () => { - test('it should validate an empty array', () => { + test('it should pass validation when supplied an empty array', () => { const payload: CommentsArray = []; const decoded = DefaultCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -23,7 +23,7 @@ describe('default_comments_array', () => { expect(message.schema).toEqual(payload); }); - test('it should validate an array of comments', () => { + test('it should pass validation when supplied an array of comments', () => { const payload: CommentsArray = getCommentsArrayMock(); const decoded = DefaultCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -32,27 +32,26 @@ describe('default_comments_array', () => { expect(message.schema).toEqual(payload); }); - test('it should NOT validate an array of numbers', () => { + test('it should fail validation when supplied an array of numbers', () => { const payload = [1]; const decoded = DefaultCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); - // TODO: Known weird error formatting that is on our list to address expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>)>"', - 'Invalid value "1" supplied to "Array<({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', ]); expect(message.schema).toEqual({}); }); - test('it should NOT validate an array of strings', () => { + test('it should fail validation when supplied an array of strings', () => { const payload = ['some string']; const decoded = DefaultCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some string" supplied to "Array<({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>)>"', - 'Invalid value "some string" supplied to "Array<({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + 'Invalid value "some string" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', + 'Invalid value "some string" supplied to "Array<({| comment: NonEmptyString, created_at: string, created_by: string, id: NonEmptyString |} & Partial<{| updated_at: string, updated_by: string |}>)>"', ]); expect(message.schema).toEqual({}); }); diff --git a/x-pack/plugins/lists/common/schemas/types/default_comments_array.ts b/x-pack/plugins/lists/common/schemas/types/default_comments_array.ts index 342cf8b0d7091..0d7e28e69cf71 100644 --- a/x-pack/plugins/lists/common/schemas/types/default_comments_array.ts +++ b/x-pack/plugins/lists/common/schemas/types/default_comments_array.ts @@ -7,7 +7,7 @@ import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; -import { CommentsArray, comments } from './comments'; +import { CommentsArray, comment } from './comment'; /** * Types the DefaultCommentsArray as: @@ -15,8 +15,8 @@ import { CommentsArray, comments } from './comments'; */ export const DefaultCommentsArray = new t.Type( 'DefaultCommentsArray', - t.array(comments).is, + t.array(comment).is, (input): Either => - input == null ? t.success([]) : t.array(comments).decode(input), + input == null ? t.success([]) : t.array(comment).decode(input), t.identity ); diff --git a/x-pack/plugins/lists/common/schemas/types/default_create_comments_array.test.ts b/x-pack/plugins/lists/common/schemas/types/default_create_comments_array.test.ts index f5ef7d0ad96bd..eb960b5411904 100644 --- a/x-pack/plugins/lists/common/schemas/types/default_create_comments_array.test.ts +++ b/x-pack/plugins/lists/common/schemas/types/default_create_comments_array.test.ts @@ -10,11 +10,12 @@ import { left } from 'fp-ts/lib/Either'; import { foldLeftRight, getPaths } from '../../siem_common_deps'; import { DefaultCreateCommentsArray } from './default_create_comments_array'; -import { CreateCommentsArray } from './create_comments'; -import { getCreateCommentsArrayMock } from './create_comments.mock'; +import { CreateCommentsArray } from './create_comment'; +import { getCreateCommentsArrayMock } from './create_comment.mock'; +import { getCommentsArrayMock } from './comment.mock'; describe('default_create_comments_array', () => { - test('it should validate an empty array', () => { + test('it should pass validation when an empty array', () => { const payload: CreateCommentsArray = []; const decoded = DefaultCreateCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -23,7 +24,7 @@ describe('default_create_comments_array', () => { expect(message.schema).toEqual(payload); }); - test('it should validate an array of comments', () => { + test('it should pass validation when an array of comments', () => { const payload: CreateCommentsArray = getCreateCommentsArrayMock(); const decoded = DefaultCreateCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -32,25 +33,38 @@ describe('default_create_comments_array', () => { expect(message.schema).toEqual(payload); }); - test('it should NOT validate an array of numbers', () => { + test('it should strip out "created_at" and "created_by" if they are passed in', () => { + const payload = getCommentsArrayMock(); + const decoded = DefaultCreateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + // TODO: Known weird error formatting that is on our list to address + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([ + { comment: 'some old comment' }, + { comment: 'some old comment' }, + ]); + }); + + test('it should not pass validation when an array of numbers', () => { const payload = [1]; const decoded = DefaultCreateCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); // TODO: Known weird error formatting that is on our list to address expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<{| comment: string |}>"', + 'Invalid value "1" supplied to "Array<{| comment: NonEmptyString |}>"', ]); expect(message.schema).toEqual({}); }); - test('it should NOT validate an array of strings', () => { + test('it should not pass validation when an array of strings', () => { const payload = ['some string']; const decoded = DefaultCreateCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some string" supplied to "Array<{| comment: string |}>"', + 'Invalid value "some string" supplied to "Array<{| comment: NonEmptyString |}>"', ]); expect(message.schema).toEqual({}); }); diff --git a/x-pack/plugins/lists/common/schemas/types/default_create_comments_array.ts b/x-pack/plugins/lists/common/schemas/types/default_create_comments_array.ts index 7fd79782836e3..4df888ba728fb 100644 --- a/x-pack/plugins/lists/common/schemas/types/default_create_comments_array.ts +++ b/x-pack/plugins/lists/common/schemas/types/default_create_comments_array.ts @@ -7,7 +7,7 @@ import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; -import { CreateCommentsArray, createComments } from './create_comments'; +import { CreateCommentsArray, createComment } from './create_comment'; /** * Types the DefaultCreateComments as: @@ -19,8 +19,8 @@ export const DefaultCreateCommentsArray = new t.Type< unknown >( 'DefaultCreateComments', - t.array(createComments).is, + t.array(createComment).is, (input): Either => - input == null ? t.success([]) : t.array(createComments).decode(input), + input == null ? t.success([]) : t.array(createComment).decode(input), t.identity ); diff --git a/x-pack/plugins/lists/common/schemas/types/default_update_comments_array.test.ts b/x-pack/plugins/lists/common/schemas/types/default_update_comments_array.test.ts index b023e73cb9328..612148dc4ccab 100644 --- a/x-pack/plugins/lists/common/schemas/types/default_update_comments_array.test.ts +++ b/x-pack/plugins/lists/common/schemas/types/default_update_comments_array.test.ts @@ -10,11 +10,11 @@ import { left } from 'fp-ts/lib/Either'; import { foldLeftRight, getPaths } from '../../siem_common_deps'; import { DefaultUpdateCommentsArray } from './default_update_comments_array'; -import { UpdateCommentsArray } from './update_comments'; -import { getUpdateCommentsArrayMock } from './update_comments.mock'; +import { UpdateCommentsArray } from './update_comment'; +import { getUpdateCommentsArrayMock } from './update_comment.mock'; describe('default_update_comments_array', () => { - test('it should validate an empty array', () => { + test('it should pass validation when supplied an empty array', () => { const payload: UpdateCommentsArray = []; const decoded = DefaultUpdateCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -23,7 +23,7 @@ describe('default_update_comments_array', () => { expect(message.schema).toEqual(payload); }); - test('it should validate an array of comments', () => { + test('it should pass validation when supplied an array of comments', () => { const payload: UpdateCommentsArray = getUpdateCommentsArrayMock(); const decoded = DefaultUpdateCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -32,29 +32,26 @@ describe('default_update_comments_array', () => { expect(message.schema).toEqual(payload); }); - test('it should NOT validate an array of numbers', () => { + test('it should fail validation when supplied an array of numbers', () => { const payload = [1]; const decoded = DefaultUpdateCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); - // TODO: Known weird error formatting that is on our list to address expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', - 'Invalid value "1" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', - 'Invalid value "1" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', ]); expect(message.schema).toEqual({}); }); - test('it should NOT validate an array of strings', () => { + test('it should fail validation when supplied an array of strings', () => { const payload = ['some string']; const decoded = DefaultUpdateCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some string" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', - 'Invalid value "some string" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', - 'Invalid value "some string" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', + 'Invalid value "some string" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', + 'Invalid value "some string" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', ]); expect(message.schema).toEqual({}); }); diff --git a/x-pack/plugins/lists/common/schemas/types/default_update_comments_array.ts b/x-pack/plugins/lists/common/schemas/types/default_update_comments_array.ts index 854b7cf7ada7e..35338dae64387 100644 --- a/x-pack/plugins/lists/common/schemas/types/default_update_comments_array.ts +++ b/x-pack/plugins/lists/common/schemas/types/default_update_comments_array.ts @@ -7,7 +7,7 @@ import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; -import { UpdateCommentsArray, updateCommentsArray } from './update_comments'; +import { UpdateCommentsArray, updateCommentsArray } from './update_comment'; /** * Types the DefaultCommentsUpdate as: diff --git a/x-pack/plugins/lists/common/schemas/types/entries.mock.ts b/x-pack/plugins/lists/common/schemas/types/entries.mock.ts index 3ed3f4e7ff88f..16794415138b2 100644 --- a/x-pack/plugins/lists/common/schemas/types/entries.mock.ts +++ b/x-pack/plugins/lists/common/schemas/types/entries.mock.ts @@ -11,10 +11,22 @@ import { getEntryListMock } from './entry_list.mock'; import { getEntryExistsMock } from './entry_exists.mock'; import { getEntryNestedMock } from './entry_nested.mock'; -export const getEntriesArrayMock = (): EntriesArray => [ +export const getListAndNonListEntriesArrayMock = (): EntriesArray => [ { ...getEntryMatchMock() }, { ...getEntryMatchAnyMock() }, { ...getEntryListMock() }, { ...getEntryExistsMock() }, { ...getEntryNestedMock() }, ]; + +export const getListEntriesArrayMock = (): EntriesArray => [ + { ...getEntryListMock() }, + { ...getEntryListMock() }, +]; + +export const getEntriesArrayMock = (): EntriesArray => [ + { ...getEntryMatchMock() }, + { ...getEntryMatchAnyMock() }, + { ...getEntryExistsMock() }, + { ...getEntryNestedMock() }, +]; diff --git a/x-pack/plugins/lists/common/schemas/types/index.ts b/x-pack/plugins/lists/common/schemas/types/index.ts index 463f7cfe51ce3..6b7e9fd17a1af 100644 --- a/x-pack/plugins/lists/common/schemas/types/index.ts +++ b/x-pack/plugins/lists/common/schemas/types/index.ts @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -export * from './comments'; -export * from './create_comments'; -export * from './update_comments'; +export * from './comment'; +export * from './create_comment'; +export * from './update_comment'; export * from './default_comments_array'; export * from './default_create_comments_array'; export * from './default_update_comments_array'; diff --git a/x-pack/plugins/lists/common/schemas/types/non_empty_entries_array.test.ts b/x-pack/plugins/lists/common/schemas/types/non_empty_entries_array.test.ts index ab7002982cf28..a2697286aa038 100644 --- a/x-pack/plugins/lists/common/schemas/types/non_empty_entries_array.test.ts +++ b/x-pack/plugins/lists/common/schemas/types/non_empty_entries_array.test.ts @@ -11,10 +11,13 @@ import { foldLeftRight, getPaths } from '../../siem_common_deps'; import { getEntryMatchMock } from './entry_match.mock'; import { getEntryMatchAnyMock } from './entry_match_any.mock'; -import { getEntryListMock } from './entry_list.mock'; import { getEntryExistsMock } from './entry_exists.mock'; import { getEntryNestedMock } from './entry_nested.mock'; -import { getEntriesArrayMock } from './entries.mock'; +import { + getEntriesArrayMock, + getListAndNonListEntriesArrayMock, + getListEntriesArrayMock, +} from './entries.mock'; import { nonEmptyEntriesArray } from './non_empty_entries_array'; import { EntriesArray } from './entries'; @@ -80,7 +83,7 @@ describe('non_empty_entries_array', () => { }); test('it should validate an array of "list" entries', () => { - const payload: EntriesArray = [{ ...getEntryListMock() }, { ...getEntryListMock() }]; + const payload: EntriesArray = [...getListEntriesArrayMock()]; const decoded = nonEmptyEntriesArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -106,6 +109,15 @@ describe('non_empty_entries_array', () => { expect(message.schema).toEqual(payload); }); + test('it should NOT validate an array of entries of value list and non-value list entries', () => { + const payload: EntriesArray = [...getListAndNonListEntriesArrayMock()]; + const decoded = nonEmptyEntriesArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Cannot have entry of type list and other']); + expect(message.schema).toEqual({}); + }); + test('it should NOT validate an array of non entries', () => { const payload = [1]; const decoded = nonEmptyEntriesArray.decode(payload); diff --git a/x-pack/plugins/lists/common/schemas/types/non_empty_entries_array.ts b/x-pack/plugins/lists/common/schemas/types/non_empty_entries_array.ts index 1370fe022c258..3683ca97dedb8 100644 --- a/x-pack/plugins/lists/common/schemas/types/non_empty_entries_array.ts +++ b/x-pack/plugins/lists/common/schemas/types/non_empty_entries_array.ts @@ -8,6 +8,7 @@ import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; import { EntriesArray, entriesArray } from './entries'; +import { entriesList } from './entry_list'; /** * Types the nonEmptyEntriesArray as: @@ -21,6 +22,14 @@ export const nonEmptyEntriesArray = new t.Type entriesList.is(entry)) && + input.some((entry) => !entriesList.is(entry)) + ) { + // fail when an exception item contains both a value list entry and a non-value list entry + return t.failure(input, context, 'Cannot have entry of type list and other'); + } return entriesArray.validate(input, context); } }, diff --git a/x-pack/plugins/lists/common/schemas/types/update_comments.mock.ts b/x-pack/plugins/lists/common/schemas/types/update_comment.mock.ts similarity index 54% rename from x-pack/plugins/lists/common/schemas/types/update_comments.mock.ts rename to x-pack/plugins/lists/common/schemas/types/update_comment.mock.ts index 3e963c2607dc5..9b85a24abe40b 100644 --- a/x-pack/plugins/lists/common/schemas/types/update_comments.mock.ts +++ b/x-pack/plugins/lists/common/schemas/types/update_comment.mock.ts @@ -4,11 +4,16 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getCommentsMock } from './comments.mock'; -import { getCreateCommentsMock } from './create_comments.mock'; -import { UpdateCommentsArray } from './update_comments'; +import { ID } from '../../constants.mock'; + +import { UpdateComment, UpdateCommentsArray } from './update_comment'; + +export const getUpdateCommentMock = (): UpdateComment => ({ + comment: 'some comment', + id: ID, +}); export const getUpdateCommentsArrayMock = (): UpdateCommentsArray => [ - getCommentsMock(), - getCreateCommentsMock(), + getUpdateCommentMock(), + getUpdateCommentMock(), ]; diff --git a/x-pack/plugins/lists/common/schemas/types/update_comment.test.ts b/x-pack/plugins/lists/common/schemas/types/update_comment.test.ts new file mode 100644 index 0000000000000..ac7716af40966 --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/types/update_comment.test.ts @@ -0,0 +1,150 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; + +import { foldLeftRight, getPaths } from '../../siem_common_deps'; + +import { getUpdateCommentMock, getUpdateCommentsArrayMock } from './update_comment.mock'; +import { + UpdateComment, + UpdateCommentsArray, + UpdateCommentsArrayOrUndefined, + updateComment, + updateCommentsArray, + updateCommentsArrayOrUndefined, +} from './update_comment'; + +describe('CommentsUpdate', () => { + describe('updateComment', () => { + test('it should pass validation when supplied typical comment update', () => { + const payload = getUpdateCommentMock(); + const decoded = updateComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when supplied an undefined for "comment"', () => { + const payload = getUpdateCommentMock(); + delete payload.comment; + const decoded = updateComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "comment"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when supplied an empty string for "comment"', () => { + const payload = { ...getUpdateCommentMock(), comment: '' }; + const decoded = updateComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "comment"']); + expect(message.schema).toEqual({}); + }); + + test('it should pass validation when supplied an undefined for "id"', () => { + const payload = getUpdateCommentMock(); + delete payload.id; + const decoded = updateComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when supplied an empty string for "id"', () => { + const payload = { ...getUpdateCommentMock(), id: '' }; + const decoded = updateComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('it should strip out extra key passed in', () => { + const payload: UpdateComment & { + extraKey?: string; + } = { ...getUpdateCommentMock(), extraKey: 'some new value' }; + const decoded = updateComment.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getUpdateCommentMock()); + }); + }); + + describe('updateCommentsArray', () => { + test('it should pass validation when supplied an array of comments', () => { + const payload = getUpdateCommentsArrayMock(); + const decoded = updateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when undefined', () => { + const payload = undefined; + const decoded = updateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should fail validation when array includes non comments types', () => { + const payload = ([1] as unknown) as UpdateCommentsArray; + const decoded = updateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + }); + + describe('updateCommentsArrayOrUndefined', () => { + test('it should pass validation when supplied an array of comments', () => { + const payload = getUpdateCommentsArrayMock(); + const decoded = updateCommentsArrayOrUndefined.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should pass validation when supplied when undefined', () => { + const payload = undefined; + const decoded = updateCommentsArrayOrUndefined.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should fail validation when array includes non comments types', () => { + const payload = ([1] as unknown) as UpdateCommentsArrayOrUndefined; + const decoded = updateCommentsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', + 'Invalid value "1" supplied to "Array<({| comment: NonEmptyString |} & Partial<{| id: NonEmptyString |}>)>"', + ]); + expect(message.schema).toEqual({}); + }); + }); +}); diff --git a/x-pack/plugins/lists/common/schemas/types/update_comments.ts b/x-pack/plugins/lists/common/schemas/types/update_comment.ts similarity index 58% rename from x-pack/plugins/lists/common/schemas/types/update_comments.ts rename to x-pack/plugins/lists/common/schemas/types/update_comment.ts index 4a21bfa363d45..b95812cb35bf9 100644 --- a/x-pack/plugins/lists/common/schemas/types/update_comments.ts +++ b/x-pack/plugins/lists/common/schemas/types/update_comment.ts @@ -5,10 +5,24 @@ */ import * as t from 'io-ts'; -import { comments } from './comments'; -import { createComments } from './create_comments'; +import { NonEmptyString } from '../../siem_common_deps'; +import { id } from '../common/schemas'; -export const updateCommentsArray = t.array(t.union([comments, createComments])); +export const updateComment = t.intersection([ + t.exact( + t.type({ + comment: NonEmptyString, + }) + ), + t.exact( + t.partial({ + id, + }) + ), +]); + +export type UpdateComment = t.TypeOf; +export const updateCommentsArray = t.array(updateComment); export type UpdateCommentsArray = t.TypeOf; export const updateCommentsArrayOrUndefined = t.union([updateCommentsArray, t.undefined]); export type UpdateCommentsArrayOrUndefined = t.TypeOf; diff --git a/x-pack/plugins/lists/common/schemas/types/update_comments.test.ts b/x-pack/plugins/lists/common/schemas/types/update_comments.test.ts deleted file mode 100644 index 7668504b031b5..0000000000000 --- a/x-pack/plugins/lists/common/schemas/types/update_comments.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; - -import { foldLeftRight, getPaths } from '../../siem_common_deps'; - -import { getUpdateCommentsArrayMock } from './update_comments.mock'; -import { - UpdateCommentsArray, - UpdateCommentsArrayOrUndefined, - updateCommentsArray, - updateCommentsArrayOrUndefined, -} from './update_comments'; -import { getCommentsMock } from './comments.mock'; -import { getCreateCommentsMock } from './create_comments.mock'; - -describe('CommentsUpdate', () => { - describe('updateCommentsArray', () => { - test('it should validate an array of comments', () => { - const payload = getUpdateCommentsArrayMock(); - const decoded = updateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate an array of existing comments', () => { - const payload = [getCommentsMock()]; - const decoded = updateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate an array of new comments', () => { - const payload = [getCreateCommentsMock()]; - const decoded = updateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate when undefined', () => { - const payload = undefined; - const decoded = updateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate when array includes non comments types', () => { - const payload = ([1] as unknown) as UpdateCommentsArray; - const decoded = updateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', - 'Invalid value "1" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', - 'Invalid value "1" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', - ]); - expect(message.schema).toEqual({}); - }); - }); - - describe('updateCommentsArrayOrUndefined', () => { - test('it should validate an array of comments', () => { - const payload = getUpdateCommentsArrayMock(); - const decoded = updateCommentsArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate when undefined', () => { - const payload = undefined; - const decoded = updateCommentsArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate when array includes non comments types', () => { - const payload = ([1] as unknown) as UpdateCommentsArrayOrUndefined; - const decoded = updateCommentsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', - 'Invalid value "1" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', - 'Invalid value "1" supplied to "Array<(({| comment: string, created_at: string, created_by: string |} & Partial<{| updated_at: string, updated_by: string |}>) | {| comment: string |})>"', - ]); - expect(message.schema).toEqual({}); - }); - }); -}); diff --git a/x-pack/plugins/lists/common/shared_exports.ts b/x-pack/plugins/lists/common/shared_exports.ts index dc0a9aa5926ef..1f6c65919b063 100644 --- a/x-pack/plugins/lists/common/shared_exports.ts +++ b/x-pack/plugins/lists/common/shared_exports.ts @@ -8,8 +8,8 @@ export { ListSchema, CommentsArray, CreateCommentsArray, - Comments, - CreateComments, + Comment, + CreateComment, ExceptionListSchema, ExceptionListItemSchema, CreateExceptionListSchema, @@ -28,6 +28,7 @@ export { OperatorType, OperatorTypeEnum, ExceptionListTypeEnum, + comment, exceptionListItemSchema, exceptionListType, createExceptionListItemSchema, diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.ts b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.ts index 918397d01ce2c..f678ed4faeeda 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.ts +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.ts @@ -41,7 +41,9 @@ describe('useExceptionList', () => { useExceptionList({ filterOptions: { filter: '', tags: [] }, http: mockKibanaHttpService, - lists: [{ id: 'myListId', namespaceType: 'single', type: 'detection' }], + lists: [ + { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, + ], onError: onErrorMock, pagination: { page: 1, @@ -76,7 +78,9 @@ describe('useExceptionList', () => { useExceptionList({ filterOptions: { filter: '', tags: [] }, http: mockKibanaHttpService, - lists: [{ id: 'myListId', namespaceType: 'single', type: 'detection' }], + lists: [ + { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, + ], onError: onErrorMock, onSuccess: onSuccessMock, pagination: { @@ -131,7 +135,9 @@ describe('useExceptionList', () => { initialProps: { filterOptions: { filter: '', tags: [] }, http: mockKibanaHttpService, - lists: [{ id: 'myListId', namespaceType: 'single', type: 'detection' }], + lists: [ + { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, + ], onError: onErrorMock, onSuccess: onSuccessMock, pagination: { @@ -146,7 +152,9 @@ describe('useExceptionList', () => { rerender({ filterOptions: { filter: '', tags: [] }, http: mockKibanaHttpService, - lists: [{ id: 'newListId', namespaceType: 'single', type: 'detection' }], + lists: [ + { id: 'newListId', listId: 'new_list_id', namespaceType: 'single', type: 'detection' }, + ], onError: onErrorMock, onSuccess: onSuccessMock, pagination: { @@ -173,7 +181,9 @@ describe('useExceptionList', () => { useExceptionList({ filterOptions: { filter: '', tags: [] }, http: mockKibanaHttpService, - lists: [{ id: 'myListId', namespaceType: 'single', type: 'detection' }], + lists: [ + { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, + ], onError: onErrorMock, pagination: { page: 1, @@ -210,7 +220,9 @@ describe('useExceptionList', () => { useExceptionList({ filterOptions: { filter: '', tags: [] }, http: mockKibanaHttpService, - lists: [{ id: 'myListId', namespaceType: 'single', type: 'detection' }], + lists: [ + { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, + ], onError: onErrorMock, pagination: { page: 1, @@ -238,7 +250,9 @@ describe('useExceptionList', () => { useExceptionList({ filterOptions: { filter: '', tags: [] }, http: mockKibanaHttpService, - lists: [{ id: 'myListId', namespaceType: 'single', type: 'detection' }], + lists: [ + { id: 'myListId', listId: 'list_id', namespaceType: 'single', type: 'detection' }, + ], onError: onErrorMock, pagination: { page: 1, diff --git a/x-pack/plugins/lists/public/exceptions/types.ts b/x-pack/plugins/lists/public/exceptions/types.ts index f99323b384781..c0ec72e1c19eb 100644 --- a/x-pack/plugins/lists/public/exceptions/types.ts +++ b/x-pack/plugins/lists/public/exceptions/types.ts @@ -60,6 +60,7 @@ export interface UseExceptionListProps { export interface ExceptionIdentifiers { id: string; + listId: string; namespaceType: NamespaceType; type: ExceptionListType; } diff --git a/x-pack/plugins/lists/public/shared_exports.ts b/x-pack/plugins/lists/public/shared_exports.ts index 56341035f839f..16026a436f154 100644 --- a/x-pack/plugins/lists/public/shared_exports.ts +++ b/x-pack/plugins/lists/public/shared_exports.ts @@ -5,7 +5,9 @@ */ // Exports to be shared with plugins +export { withOptionalSignal } from './common/with_optional_signal'; export { useIsMounted } from './common/hooks/use_is_mounted'; +export { useAsync } from './common/hooks/use_async'; export { useApi } from './exceptions/hooks/use_api'; export { usePersistExceptionItem } from './exceptions/hooks/persist_exception_item'; export { usePersistExceptionList } from './exceptions/hooks/persist_exception_list'; diff --git a/x-pack/plugins/lists/server/config.mock.ts b/x-pack/plugins/lists/server/config.mock.ts index 3cf5040c73675..b272f18c4e809 100644 --- a/x-pack/plugins/lists/server/config.mock.ts +++ b/x-pack/plugins/lists/server/config.mock.ts @@ -6,6 +6,7 @@ import { IMPORT_BUFFER_SIZE, + IMPORT_TIMEOUT, LIST_INDEX, LIST_ITEM_INDEX, MAX_IMPORT_PAYLOAD_BYTES, @@ -21,6 +22,7 @@ export const getConfigMock = (): Partial => ({ export const getConfigMockDecoded = (): ConfigType => ({ enabled: true, importBufferSize: IMPORT_BUFFER_SIZE, + importTimeout: IMPORT_TIMEOUT, listIndex: LIST_INDEX, listItemIndex: LIST_ITEM_INDEX, maxImportPayloadBytes: MAX_IMPORT_PAYLOAD_BYTES, diff --git a/x-pack/plugins/lists/server/config.test.ts b/x-pack/plugins/lists/server/config.test.ts index 60501322dcfa2..40b04edd4c007 100644 --- a/x-pack/plugins/lists/server/config.test.ts +++ b/x-pack/plugins/lists/server/config.test.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +import moment from 'moment'; + import { ConfigSchema, ConfigType } from './config'; import { getConfigMock, getConfigMockDecoded } from './config.mock'; @@ -61,4 +63,24 @@ describe('config_schema', () => { '[importBufferSize]: Value must be equal to or greater than [1].' ); }); + + test('it throws if the "importTimeout" value is less than 2 minutes', () => { + const mock: ConfigType = { + ...getConfigMockDecoded(), + importTimeout: moment.duration(2, 'minutes').subtract(1, 'second'), + }; + expect(() => ConfigSchema.validate(mock)).toThrow( + '[importTimeout]: duration cannot be less than 2 minutes' + ); + }); + + test('it throws if the "importTimeout" value is greater than 1 hour', () => { + const mock: ConfigType = { + ...getConfigMockDecoded(), + importTimeout: moment.duration(1, 'hour').add(1, 'second'), + }; + expect(() => ConfigSchema.validate(mock)).toThrow( + '[importTimeout]: duration cannot be greater than 30 minutes' + ); + }); }); diff --git a/x-pack/plugins/lists/server/config.ts b/x-pack/plugins/lists/server/config.ts index 0fcc68419f8fe..6e36d135abfcc 100644 --- a/x-pack/plugins/lists/server/config.ts +++ b/x-pack/plugins/lists/server/config.ts @@ -9,9 +9,19 @@ import { TypeOf, schema } from '@kbn/config-schema'; export const ConfigSchema = schema.object({ enabled: schema.boolean({ defaultValue: true }), importBufferSize: schema.number({ defaultValue: 1000, min: 1 }), + importTimeout: schema.duration({ + defaultValue: '5m', + validate: (value) => { + if (value.asMinutes() < 2) { + throw new Error('duration cannot be less than 2 minutes'); + } else if (value.asMinutes() > 30) { + throw new Error('duration cannot be greater than 30 minutes'); + } + }, + }), listIndex: schema.string({ defaultValue: '.lists' }), listItemIndex: schema.string({ defaultValue: '.items' }), - maxImportPayloadBytes: schema.number({ defaultValue: 40000000, min: 1 }), + maxImportPayloadBytes: schema.number({ defaultValue: 9000000, min: 1 }), }); export type ConfigType = TypeOf; diff --git a/x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts b/x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts index 5ff2a9d9df9f4..22aa1fb59858b 100644 --- a/x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts @@ -6,7 +6,7 @@ import { IRouter } from 'kibana/server'; -import { ENDPOINT_LIST_ITEM_URL } from '../../common/constants'; +import { ENDPOINT_LIST_ID, ENDPOINT_LIST_ITEM_URL } from '../../common/constants'; import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; import { validate } from '../../common/siem_common_deps'; import { @@ -16,6 +16,7 @@ import { } from '../../common/schemas'; import { getExceptionListClient } from './utils/get_exception_list_client'; +import { validateExceptionListSize } from './validate'; export const createEndpointListItemRoute = (router: IRouter): void => { router.post( @@ -71,6 +72,18 @@ export const createEndpointListItemRoute = (router: IRouter): void => { if (errors != null) { return siemResponse.error({ body: errors, statusCode: 500 }); } else { + const listSizeError = await validateExceptionListSize( + exceptionLists, + ENDPOINT_LIST_ID, + 'agnostic' + ); + if (listSizeError != null) { + await exceptionLists.deleteExceptionListItemById({ + id: createdList.id, + namespaceType: 'agnostic', + }); + return siemResponse.error(listSizeError); + } return response.ok({ body: validated ?? {} }); } } diff --git a/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts b/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts index e4885c7393bd4..ed58621dae973 100644 --- a/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts @@ -17,6 +17,7 @@ import { import { getExceptionListClient } from './utils/get_exception_list_client'; import { endpointDisallowedFields } from './endpoint_disallowed_fields'; +import { validateExceptionListSize } from './validate'; export const createExceptionListItemRoute = (router: IRouter): void => { router.post( @@ -104,6 +105,18 @@ export const createExceptionListItemRoute = (router: IRouter): void => { if (errors != null) { return siemResponse.error({ body: errors, statusCode: 500 }); } else { + const listSizeError = await validateExceptionListSize( + exceptionLists, + listId, + namespaceType + ); + if (listSizeError != null) { + await exceptionLists.deleteExceptionListItemById({ + id: createdList.id, + namespaceType, + }); + return siemResponse.error(listSizeError); + } return response.ok({ body: validated ?? {} }); } } diff --git a/x-pack/plugins/lists/server/routes/import_list_item_route.ts b/x-pack/plugins/lists/server/routes/import_list_item_route.ts index 1003a0c52a794..e162e7829e456 100644 --- a/x-pack/plugins/lists/server/routes/import_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/import_list_item_route.ts @@ -27,6 +27,7 @@ export const importListItemRoute = (router: IRouter, config: ConfigType): void = parse: false, }, tags: ['access:lists-all'], + timeout: config.importTimeout.asMilliseconds(), }, path: `${LIST_ITEM_URL}/_import`, validate: { diff --git a/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts b/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts index 293435b3f6202..f5e0e7ae75700 100644 --- a/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts @@ -14,6 +14,7 @@ import { exceptionListItemSchema, updateExceptionListItemSchema, } from '../../common/schemas'; +import { updateExceptionListItemValidate } from '../../common/schemas/request/update_exception_list_item_validation'; import { getExceptionListClient } from '.'; @@ -33,6 +34,11 @@ export const updateExceptionListItemRoute = (router: IRouter): void => { }, async (context, request, response) => { const siemResponse = buildSiemResponse(response); + const validationErrors = updateExceptionListItemValidate(request.body); + if (validationErrors.length) { + return siemResponse.error({ body: validationErrors, statusCode: 400 }); + } + try { const { description, diff --git a/x-pack/plugins/lists/server/routes/validate.ts b/x-pack/plugins/lists/server/routes/validate.ts new file mode 100644 index 0000000000000..bbd4b0eaf0e33 --- /dev/null +++ b/x-pack/plugins/lists/server/routes/validate.ts @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ExceptionListClient } from '../services/exception_lists/exception_list_client'; +import { MAX_EXCEPTION_LIST_SIZE } from '../../common/constants'; +import { foundExceptionListItemSchema } from '../../common/schemas'; +import { NamespaceType } from '../../common/schemas/types'; +import { validate } from '../../common/siem_common_deps'; + +export const validateExceptionListSize = async ( + exceptionLists: ExceptionListClient, + listId: string, + namespaceType: NamespaceType +): Promise<{ body: string; statusCode: number } | null> => { + const exceptionListItems = await exceptionLists.findExceptionListItem({ + filter: undefined, + listId, + namespaceType, + page: undefined, + perPage: undefined, + sortField: undefined, + sortOrder: undefined, + }); + if (exceptionListItems == null) { + // If exceptionListItems is null then we couldn't find the list so it may have been deleted + return { + body: `Unable to find list id: ${listId} to verify max exception list size`, + statusCode: 500, + }; + } + const [validatedItems, err] = validate(exceptionListItems, foundExceptionListItemSchema); + if (err != null) { + return { + body: err, + statusCode: 500, + }; + } + // Unnecessary since validatedItems comes from exceptionListItems which is already + // checked for null, but typescript fails to detect that + if (validatedItems == null) { + return { + body: `Unable to find list id: ${listId} to verify max exception list size`, + statusCode: 500, + }; + } + if (validatedItems.total > MAX_EXCEPTION_LIST_SIZE) { + return { + body: `Failed to add exception item, exception list would exceed max size of ${MAX_EXCEPTION_LIST_SIZE}`, + statusCode: 400, + }; + } + return null; +}; diff --git a/x-pack/plugins/lists/server/saved_objects/exception_list.ts b/x-pack/plugins/lists/server/saved_objects/exception_list.ts index 3bde3545837cf..f9e408833e069 100644 --- a/x-pack/plugins/lists/server/saved_objects/exception_list.ts +++ b/x-pack/plugins/lists/server/saved_objects/exception_list.ts @@ -83,6 +83,9 @@ export const exceptionListItemMapping: SavedObjectsType['mappings'] = { created_by: { type: 'keyword', }, + id: { + type: 'keyword', + }, updated_at: { type: 'keyword', }, diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item.json b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item.json index 5fbfcc10bcc3c..eede855aab199 100644 --- a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item.json +++ b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item.json @@ -8,7 +8,7 @@ "name": "Sample Endpoint Exception List", "entries": [ { - "field": "host.ip", + "field": "actingProcess.file.signer", "operator": "excluded", "type": "exists" }, diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_bad_ip_list.json b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_bad_ip_list.json new file mode 100644 index 0000000000000..bab435487ec25 --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_bad_ip_list.json @@ -0,0 +1,24 @@ +{ + "list_id": "endpoint_list", + "item_id": "endpoint_list_item_good_rock01", + "_tags": ["endpoint", "process", "malware", "os:windows"], + "tags": ["user added string for a tag", "malware"], + "type": "simple", + "description": "Don't signal when agent.name is rock01 and source.ip is in the goodguys.txt list", + "name": "Filter out good guys ip and agent.name rock01", + "comments": [], + "entries": [ + { + "field": "agent.name", + "operator": "excluded", + "type": "match", + "value": ["rock01"] + }, + { + "field": "source.ip", + "operator": "excluded", + "type": "list", + "list": { "id": "goodguys.txt", "type": "ip" } + } + ] +} diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update_item.json b/x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update_item.json index da345fb930c04..81db909277595 100644 --- a/x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update_item.json +++ b/x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update_item.json @@ -1,17 +1,18 @@ { - "item_id": "simple_list_item", - "_tags": ["endpoint", "process", "malware", "os:windows"], - "tags": ["user added string for a tag", "malware"], - "type": "simple", - "description": "This is a sample change here this list", - "name": "Sample Endpoint Exception List update change", - "comments": [{ "comment": "this is a newly added comment" }], + "_tags": ["detection"], + "comments": [], + "description": "Test comments - exception list item", "entries": [ { - "field": "event.category", - "operator": "included", - "type": "match_any", - "value": ["process", "malware"] + "field": "host.name", + "type": "match", + "value": "rock01", + "operator": "included" } - ] + ], + "item_id": "993f43f7-325d-4df3-9338-964e77c37053", + "name": "Test comments - exception list item", + "namespace_type": "single", + "tags": [], + "type": "simple" } diff --git a/x-pack/plugins/lists/server/scripts/lists/new/list_ip_item.json b/x-pack/plugins/lists/server/scripts/lists/new/list_ip_item.json new file mode 100644 index 0000000000000..e932892b517a4 --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/lists/new/list_ip_item.json @@ -0,0 +1,4 @@ +{ + "id": "hand_inserted_item_id", + "value": "127.0.0.1" +} diff --git a/x-pack/plugins/lists/server/scripts/lists/new/list_keyword_item.json b/x-pack/plugins/lists/server/scripts/lists/new/list_keyword_item.json new file mode 100644 index 0000000000000..ed798a1dc0792 --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/lists/new/list_keyword_item.json @@ -0,0 +1,4 @@ +{ + "list_id": "keyword_list", + "value": "sh" +} diff --git a/x-pack/plugins/lists/server/scripts/quick_start.sh b/x-pack/plugins/lists/server/scripts/quick_start.sh new file mode 100755 index 0000000000000..d09370bd46a52 --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/quick_start.sh @@ -0,0 +1,5 @@ +./hard_reset.sh && \ +./post_list.sh lists/new/lists/keyword.json && \ +./post_list_item.sh lists/new/list_keyword_item.json && \ +./post_exception_list.sh && \ +./post_exception_list_item.sh ./exception_lists/new/exception_list_item_with_list.json diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts b/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts index b596b831f2d68..2e9bb1325632e 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts @@ -60,7 +60,7 @@ export const createEndpointList = async ({ ); return transformSavedObjectToExceptionList({ savedObject }); } catch (err) { - if (err.status === 409) { + if (savedObjectsClient.errors.isConflictError(err)) { return null; } else { throw err; diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_exception_list_item.ts b/x-pack/plugins/lists/server/services/exception_lists/create_exception_list_item.ts index a90ec61aef4af..47c21735b45f4 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/create_exception_list_item.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/create_exception_list_item.ts @@ -64,7 +64,10 @@ export const createExceptionListItem = async ({ }: CreateExceptionListItemOptions): Promise => { const savedObjectType = getSavedObjectType({ namespaceType }); const dateNow = new Date().toISOString(); - const transformedComments = transformCreateCommentsToComments({ comments, user }); + const transformedComments = transformCreateCommentsToComments({ + incomingComments: comments, + user, + }); const savedObject = await savedObjectsClient.create(savedObjectType, { _tags, comments: transformedComments, diff --git a/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_item.ts b/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_item.ts index 8dce1f1f79e35..ee85cf36a48b5 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_item.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_item.ts @@ -8,6 +8,7 @@ import { SavedObjectsClientContract } from 'kibana/server'; import { ExceptionListItemSchema, + Id, IdOrUndefined, ItemIdOrUndefined, NamespaceType, @@ -23,6 +24,12 @@ interface DeleteExceptionListItemOptions { savedObjectsClient: SavedObjectsClientContract; } +interface DeleteExceptionListItemByIdOptions { + id: Id; + namespaceType: NamespaceType; + savedObjectsClient: SavedObjectsClientContract; +} + export const deleteExceptionListItem = async ({ itemId, id, @@ -43,3 +50,12 @@ export const deleteExceptionListItem = async ({ return exceptionListItem; } }; + +export const deleteExceptionListItemById = async ({ + id, + namespaceType, + savedObjectsClient, +}: DeleteExceptionListItemByIdOptions): Promise => { + const savedObjectType = getSavedObjectType({ namespaceType }); + await savedObjectsClient.delete(savedObjectType, id); +}; diff --git a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts index 11302e64b3538..83b44ababf9de 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts @@ -20,6 +20,7 @@ import { CreateExceptionListItemOptions, CreateExceptionListOptions, DeleteEndpointListItemOptions, + DeleteExceptionListItemByIdOptions, DeleteExceptionListItemOptions, DeleteExceptionListOptions, FindEndpointListItemOptions, @@ -40,7 +41,7 @@ import { createExceptionListItem } from './create_exception_list_item'; import { updateExceptionList } from './update_exception_list'; import { updateExceptionListItem } from './update_exception_list_item'; import { deleteExceptionList } from './delete_exception_list'; -import { deleteExceptionListItem } from './delete_exception_list_item'; +import { deleteExceptionListItem, deleteExceptionListItemById } from './delete_exception_list_item'; import { findExceptionListItem } from './find_exception_list_item'; import { findExceptionList } from './find_exception_list'; import { findExceptionListsItem } from './find_exception_list_items'; @@ -326,6 +327,18 @@ export class ExceptionListClient { }); }; + public deleteExceptionListItemById = async ({ + id, + namespaceType, + }: DeleteExceptionListItemByIdOptions): Promise => { + const { savedObjectsClient } = this; + return deleteExceptionListItemById({ + id, + namespaceType, + savedObjectsClient, + }); + }; + /** * This is the same as "deleteExceptionListItem" except it applies specifically to the endpoint list. */ diff --git a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts index 555b9c5e95a77..963716b55ea77 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts @@ -19,6 +19,7 @@ import { ExceptionListType, ExceptionListTypeOrUndefined, FilterOrUndefined, + Id, IdOrUndefined, Immutable, ItemId, @@ -93,6 +94,11 @@ export interface DeleteExceptionListItemOptions { namespaceType: NamespaceType; } +export interface DeleteExceptionListItemByIdOptions { + id: Id; + namespaceType: NamespaceType; +} + export interface DeleteEndpointListItemOptions { id: IdOrUndefined; itemId: ItemIdOrUndefined; diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils.test.ts b/x-pack/plugins/lists/server/services/exception_lists/utils.test.ts index 6f0c5195f2025..e3d96a9c3f6d0 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/utils.test.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/utils.test.ts @@ -5,15 +5,11 @@ */ import sinon from 'sinon'; import moment from 'moment'; +import uuid from 'uuid'; -import { USER } from '../../../common/constants.mock'; +import { transformCreateCommentsToComments, transformUpdateCommentsToComments } from './utils'; -import { - isCommentEqual, - transformCreateCommentsToComments, - transformUpdateComments, - transformUpdateCommentsToComments, -} from './utils'; +jest.mock('uuid/v4'); describe('utils', () => { const oldDate = '2020-03-17T20:34:51.337Z'; @@ -22,59 +18,43 @@ describe('utils', () => { let clock: sinon.SinonFakeTimers; beforeEach(() => { + ((uuid.v4 as unknown) as jest.Mock) + .mockImplementationOnce(() => '123') + .mockImplementationOnce(() => '456'); + clock = sinon.useFakeTimers(unix); }); afterEach(() => { clock.restore(); + jest.clearAllMocks(); + jest.restoreAllMocks(); + jest.resetAllMocks(); }); describe('#transformUpdateCommentsToComments', () => { - test('it returns empty array if "comments" is undefined and no comments exist', () => { + test('it formats new comments', () => { const comments = transformUpdateCommentsToComments({ - comments: undefined, + comments: [{ comment: 'Im a new comment' }], existingComments: [], user: 'lily', }); - expect(comments).toEqual([]); - }); - - test('it formats newly added comments', () => { - const comments = transformUpdateCommentsToComments({ - comments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'bane' }, - { comment: 'Im a new comment' }, - ], - existingComments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'bane' }, - ], - user: 'lily', - }); - expect(comments).toEqual([ - { - comment: 'Im an old comment', - created_at: oldDate, - created_by: 'bane', - }, { comment: 'Im a new comment', created_at: dateNow, created_by: 'lily', + id: '123', }, ]); }); - test('it formats multiple newly added comments', () => { + test('it formats new comments and preserves existing comments', () => { const comments = transformUpdateCommentsToComments({ - comments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, - { comment: 'Im a new comment' }, - { comment: 'Im another new comment' }, - ], + comments: [{ comment: 'Im an old comment', id: '1' }, { comment: 'Im a new comment' }], existingComments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, + { comment: 'Im an old comment', created_at: oldDate, created_by: 'bane', id: '1' }, ], user: 'lily', }); @@ -83,26 +63,23 @@ describe('utils', () => { { comment: 'Im an old comment', created_at: oldDate, - created_by: 'lily', + created_by: 'bane', + id: '1', }, { comment: 'Im a new comment', created_at: dateNow, created_by: 'lily', - }, - { - comment: 'Im another new comment', - created_at: dateNow, - created_by: 'lily', + id: '123', }, ]); }); - test('it should not throw if comments match existing comments', () => { + test('it returns existing comments if empty array passed for "comments"', () => { const comments = transformUpdateCommentsToComments({ - comments: [{ comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }], + comments: [], existingComments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, + { comment: 'Im an old comment', created_at: oldDate, created_by: 'bane', id: '1' }, ], user: 'lily', }); @@ -111,170 +88,42 @@ describe('utils', () => { { comment: 'Im an old comment', created_at: oldDate, - created_by: 'lily', + created_by: 'bane', + id: '1', }, ]); }); - test('it does not throw if user tries to update one of their own existing comments', () => { + test('it acts as append only, only modifying new comments', () => { const comments = transformUpdateCommentsToComments({ - comments: [ - { - comment: 'Im an old comment that is trying to be updated', - created_at: oldDate, - created_by: 'lily', - }, - ], + comments: [{ comment: 'Im a new comment' }], existingComments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, + { comment: 'Im an old comment', created_at: oldDate, created_by: 'bane', id: '1' }, ], user: 'lily', }); expect(comments).toEqual([ { - comment: 'Im an old comment that is trying to be updated', + comment: 'Im an old comment', created_at: oldDate, + created_by: 'bane', + id: '1', + }, + { + comment: 'Im a new comment', + created_at: dateNow, created_by: 'lily', - updated_at: dateNow, - updated_by: 'lily', + id: '123', }, ]); }); - - test('it throws an error if user tries to update their comment, without passing in the "created_at" and "created_by" properties', () => { - expect(() => - transformUpdateCommentsToComments({ - comments: [ - { - comment: 'Im an old comment that is trying to be updated', - }, - ], - existingComments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, - ], - user: 'lily', - }) - ).toThrowErrorMatchingInlineSnapshot( - `"When trying to update a comment, \\"created_at\\" and \\"created_by\\" must be present"` - ); - }); - - test('it throws an error if user tries to delete comments', () => { - expect(() => - transformUpdateCommentsToComments({ - comments: [], - existingComments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, - ], - user: 'lily', - }) - ).toThrowErrorMatchingInlineSnapshot( - `"Comments cannot be deleted, only new comments may be added"` - ); - }); - - test('it throws if user tries to update existing comment timestamp', () => { - expect(() => - transformUpdateCommentsToComments({ - comments: [{ comment: 'Im an old comment', created_at: dateNow, created_by: 'lily' }], - existingComments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, - ], - user: 'bane', - }) - ).toThrowErrorMatchingInlineSnapshot(`"Not authorized to edit others comments"`); - }); - - test('it throws if user tries to update existing comment author', () => { - expect(() => - transformUpdateCommentsToComments({ - comments: [{ comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }], - existingComments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'me!' }, - ], - user: 'bane', - }) - ).toThrowErrorMatchingInlineSnapshot(`"Not authorized to edit others comments"`); - }); - - test('it throws if user tries to update an existing comment that is not their own', () => { - expect(() => - transformUpdateCommentsToComments({ - comments: [ - { - comment: 'Im an old comment that is trying to be updated', - created_at: oldDate, - created_by: 'lily', - }, - ], - existingComments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, - ], - user: 'bane', - }) - ).toThrowErrorMatchingInlineSnapshot(`"Not authorized to edit others comments"`); - }); - - test('it throws if user tries to update order of comments', () => { - expect(() => - transformUpdateCommentsToComments({ - comments: [ - { comment: 'Im a new comment' }, - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, - ], - existingComments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, - ], - user: 'lily', - }) - ).toThrowErrorMatchingInlineSnapshot( - `"When trying to update a comment, \\"created_at\\" and \\"created_by\\" must be present"` - ); - }); - - test('it throws an error if user tries to add comment formatted as existing comment when none yet exist', () => { - expect(() => - transformUpdateCommentsToComments({ - comments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, - { comment: 'Im a new comment' }, - ], - existingComments: [], - user: 'lily', - }) - ).toThrowErrorMatchingInlineSnapshot(`"Only new comments may be added"`); - }); - - test('it throws if empty comment exists', () => { - expect(() => - transformUpdateCommentsToComments({ - comments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, - { comment: ' ' }, - ], - existingComments: [ - { comment: 'Im an old comment', created_at: oldDate, created_by: 'lily' }, - ], - user: 'lily', - }) - ).toThrowErrorMatchingInlineSnapshot(`"Empty comments not allowed"`); - }); }); describe('#transformCreateCommentsToComments', () => { - test('it returns "undefined" if "comments" is "undefined"', () => { - const comments = transformCreateCommentsToComments({ - comments: undefined, - user: 'lily', - }); - - expect(comments).toBeUndefined(); - }); - test('it formats newly added comments', () => { const comments = transformCreateCommentsToComments({ - comments: [{ comment: 'Im a new comment' }, { comment: 'Im another new comment' }], + incomingComments: [{ comment: 'Im a new comment' }, { comment: 'Im another new comment' }], user: 'lily', }); @@ -283,178 +132,15 @@ describe('utils', () => { comment: 'Im a new comment', created_at: dateNow, created_by: 'lily', + id: '123', }, { comment: 'Im another new comment', created_at: dateNow, created_by: 'lily', + id: '456', }, ]); }); - - test('it throws an error if user tries to add an empty comment', () => { - expect(() => - transformCreateCommentsToComments({ - comments: [{ comment: ' ' }], - user: 'lily', - }) - ).toThrowErrorMatchingInlineSnapshot(`"Empty comments not allowed"`); - }); - }); - - describe('#transformUpdateComments', () => { - test('it updates comment and adds "updated_at" and "updated_by" if content differs', () => { - const comments = transformUpdateComments({ - comment: { - comment: 'Im an old comment that is trying to be updated', - created_at: oldDate, - created_by: 'lily', - }, - existingComment: { - comment: 'Im an old comment', - created_at: oldDate, - created_by: 'lily', - }, - user: 'lily', - }); - - expect(comments).toEqual({ - comment: 'Im an old comment that is trying to be updated', - created_at: oldDate, - created_by: 'lily', - updated_at: dateNow, - updated_by: 'lily', - }); - }); - - test('it does not update comment and add "updated_at" and "updated_by" if content is the same', () => { - const comments = transformUpdateComments({ - comment: { - comment: 'Im an old comment ', - created_at: oldDate, - created_by: 'lily', - }, - existingComment: { - comment: 'Im an old comment', - created_at: oldDate, - created_by: 'lily', - }, - user: 'lily', - }); - - expect(comments).toEqual({ - comment: 'Im an old comment', - created_at: oldDate, - created_by: 'lily', - }); - }); - - test('it throws if user tries to update an existing comment that is not their own', () => { - expect(() => - transformUpdateComments({ - comment: { - comment: 'Im an old comment that is trying to be updated', - created_at: oldDate, - created_by: 'lily', - }, - existingComment: { - comment: 'Im an old comment', - created_at: oldDate, - created_by: 'lily', - }, - user: 'bane', - }) - ).toThrowErrorMatchingInlineSnapshot(`"Not authorized to edit others comments"`); - }); - - test('it throws if user tries to update an existing comments timestamp', () => { - expect(() => - transformUpdateComments({ - comment: { - comment: 'Im an old comment', - created_at: dateNow, - created_by: 'lily', - }, - existingComment: { - comment: 'Im an old comment', - created_at: oldDate, - created_by: 'lily', - }, - user: 'lily', - }) - ).toThrowErrorMatchingInlineSnapshot(`"Unable to update comment"`); - }); - }); - - describe('#isCommentEqual', () => { - test('it returns false if "comment" values differ', () => { - const result = isCommentEqual( - { - comment: 'some old comment', - created_at: oldDate, - created_by: USER, - }, - { - comment: 'some older comment', - created_at: oldDate, - created_by: USER, - } - ); - - expect(result).toBeFalsy(); - }); - - test('it returns false if "created_at" values differ', () => { - const result = isCommentEqual( - { - comment: 'some old comment', - created_at: oldDate, - created_by: USER, - }, - { - comment: 'some old comment', - created_at: dateNow, - created_by: USER, - } - ); - - expect(result).toBeFalsy(); - }); - - test('it returns false if "created_by" values differ', () => { - const result = isCommentEqual( - { - comment: 'some old comment', - created_at: oldDate, - created_by: USER, - }, - { - comment: 'some old comment', - created_at: oldDate, - created_by: 'lily', - } - ); - - expect(result).toBeFalsy(); - }); - - test('it returns true if comment values are equivalent', () => { - const result = isCommentEqual( - { - comment: 'some old comment', - created_at: oldDate, - created_by: USER, - }, - { - created_at: oldDate, - created_by: USER, - // Disabling to assure that order doesn't matter - // eslint-disable-next-line sort-keys - comment: 'some old comment', - } - ); - - expect(result).toBeTruthy(); - }); }); }); diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils.ts b/x-pack/plugins/lists/server/services/exception_lists/utils.ts index b168fae741822..836f642899086 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/utils.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/utils.ts @@ -3,17 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - +import uuid from 'uuid'; import { SavedObject, SavedObjectsFindResponse, SavedObjectsUpdateResponse } from 'kibana/server'; import { NamespaceTypeArray } from '../../../common/schemas/types/default_namespace_array'; -import { ErrorWithStatusCode } from '../../error_with_status_code'; import { - Comments, CommentsArray, - CommentsArrayOrUndefined, - CreateComments, - CreateCommentsArrayOrUndefined, + CreateComment, + CreateCommentsArray, ExceptionListItemSchema, ExceptionListSchema, ExceptionListSoSchema, @@ -21,7 +18,6 @@ import { FoundExceptionListSchema, NamespaceType, UpdateCommentsArrayOrUndefined, - comments as commentsSchema, exceptionListItemType, exceptionListType, } from '../../../common/schemas'; @@ -296,17 +292,6 @@ export const transformSavedObjectsToFoundExceptionList = ({ }; }; -/* - * Determines whether two comments are equal, this is a very - * naive implementation, not meant to be used for deep equality of complex objects - */ -export const isCommentEqual = (commentA: Comments, commentB: Comments): boolean => { - const a = Object.values(commentA).sort().join(); - const b = Object.values(commentB).sort().join(); - - return a === b; -}; - export const transformUpdateCommentsToComments = ({ comments, existingComments, @@ -316,90 +301,28 @@ export const transformUpdateCommentsToComments = ({ existingComments: CommentsArray; user: string; }): CommentsArray => { - const newComments = comments ?? []; + const incomingComments = comments ?? []; + const newComments = incomingComments.filter((comment) => comment.id == null); + const newCommentsFormatted = transformCreateCommentsToComments({ + incomingComments: newComments, + user, + }); - if (newComments.length < existingComments.length) { - throw new ErrorWithStatusCode( - 'Comments cannot be deleted, only new comments may be added', - 403 - ); - } else { - return newComments.flatMap((c, index) => { - const existingComment = existingComments[index]; - - if (commentsSchema.is(existingComment) && !commentsSchema.is(c)) { - throw new ErrorWithStatusCode( - 'When trying to update a comment, "created_at" and "created_by" must be present', - 403 - ); - } else if (existingComment == null && commentsSchema.is(c)) { - throw new ErrorWithStatusCode('Only new comments may be added', 403); - } else if ( - commentsSchema.is(c) && - existingComment != null && - isCommentEqual(c, existingComment) - ) { - return existingComment; - } else if (commentsSchema.is(c) && existingComment != null) { - return transformUpdateComments({ comment: c, existingComment, user }); - } else { - return transformCreateCommentsToComments({ comments: [c], user }) ?? []; - } - }); - } -}; - -export const transformUpdateComments = ({ - comment, - existingComment, - user, -}: { - comment: Comments; - existingComment: Comments; - user: string; -}): Comments => { - if (comment.created_by !== user) { - // existing comment is being edited, can only be edited by author - throw new ErrorWithStatusCode('Not authorized to edit others comments', 401); - } else if (existingComment.created_at !== comment.created_at) { - throw new ErrorWithStatusCode('Unable to update comment', 403); - } else if (comment.comment.trim().length === 0) { - throw new ErrorWithStatusCode('Empty comments not allowed', 403); - } else if (comment.comment.trim() !== existingComment.comment) { - const dateNow = new Date().toISOString(); - - return { - ...existingComment, - comment: comment.comment, - updated_at: dateNow, - updated_by: user, - }; - } else { - return existingComment; - } + return [...existingComments, ...newCommentsFormatted]; }; export const transformCreateCommentsToComments = ({ - comments, + incomingComments, user, }: { - comments: CreateCommentsArrayOrUndefined; + incomingComments: CreateCommentsArray; user: string; -}): CommentsArrayOrUndefined => { +}): CommentsArray => { const dateNow = new Date().toISOString(); - if (comments != null) { - return comments.map((c: CreateComments) => { - if (c.comment.trim().length === 0) { - throw new ErrorWithStatusCode('Empty comments not allowed', 403); - } else { - return { - comment: c.comment, - created_at: dateNow, - created_by: user, - }; - } - }); - } else { - return comments; - } + return incomingComments.map((comment: CreateComment) => ({ + comment: comment.comment, + created_at: dateNow, + created_by: user, + id: uuid.v4(), + })); }; diff --git a/x-pack/plugins/lists/server/services/lists/list_client.mock.ts b/x-pack/plugins/lists/server/services/lists/list_client.mock.ts index e5036d561ddc6..a2959a024f292 100644 --- a/x-pack/plugins/lists/server/services/lists/list_client.mock.ts +++ b/x-pack/plugins/lists/server/services/lists/list_client.mock.ts @@ -11,6 +11,7 @@ import { getListResponseMock } from '../../../common/schemas/response/list_schem import { getCallClusterMock } from '../../../common/get_call_cluster.mock'; import { IMPORT_BUFFER_SIZE, + IMPORT_TIMEOUT, LIST_INDEX, LIST_ITEM_INDEX, MAX_IMPORT_PAYLOAD_BYTES, @@ -65,6 +66,7 @@ export const getListClientMock = (): ListClient => { config: { enabled: true, importBufferSize: IMPORT_BUFFER_SIZE, + importTimeout: IMPORT_TIMEOUT, listIndex: LIST_INDEX, listItemIndex: LIST_ITEM_INDEX, maxImportPayloadBytes: MAX_IMPORT_PAYLOAD_BYTES, diff --git a/x-pack/plugins/maps/common/descriptor_types/sources.ts b/x-pack/plugins/maps/common/descriptor_types/sources.ts index 7eda37bf53351..6e8884d942e19 100644 --- a/x-pack/plugins/maps/common/descriptor_types/sources.ts +++ b/x-pack/plugins/maps/common/descriptor_types/sources.ts @@ -168,6 +168,7 @@ export type LayerDescriptor = { __trackedLayerDescriptor?: LayerDescriptor; alpha?: number; id: string; + joins?: JoinDescriptor[]; label?: string | null; areLabelsOnTop?: boolean; minZoom?: number; @@ -180,7 +181,6 @@ export type LayerDescriptor = { }; export type VectorLayerDescriptor = LayerDescriptor & { - joins?: JoinDescriptor[]; style?: VectorStyleDescriptor; }; diff --git a/x-pack/plugins/maps/public/_mapbox_hacks.scss b/x-pack/plugins/maps/public/_mapbox_hacks.scss index a6436585847cb..9b2d93986e426 100644 --- a/x-pack/plugins/maps/public/_mapbox_hacks.scss +++ b/x-pack/plugins/maps/public/_mapbox_hacks.scss @@ -25,16 +25,18 @@ // Custom SVG as background for zoom controls based off of EUI glyphs plusInCircleFilled and minusInCircleFilled // Also fixes dark mode -.mapboxgl-ctrl-icon.mapboxgl-ctrl-zoom-in { - background-repeat: no-repeat; +.mapboxgl-ctrl-zoom-in .mapboxgl-ctrl-icon { + // sass-lint:disable-block no-important + background-repeat: no-repeat !important; // sass-lint:disable-block quotes - background-image: url("data:image/svg+xml,%0A%3Csvg width='15px' height='15px' viewBox='0 0 15 15' version='1.1' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='#{hexToRGB($euiTextColor)}' d='M8,7 L8,3.5 C8,3.22385763 7.77614237,3 7.5,3 C7.22385763,3 7,3.22385763 7,3.5 L7,7 L3.5,7 C3.22385763,7 3,7.22385763 3,7.5 C3,7.77614237 3.22385763,8 3.5,8 L7,8 L7,11.5 C7,11.7761424 7.22385763,12 7.5,12 C7.77614237,12 8,11.7761424 8,11.5 L8,8 L11.5,8 C11.7761424,8 12,7.77614237 12,7.5 C12,7.22385763 11.7761424,7 11.5,7 L8,7 Z M7.5,15 C3.35786438,15 0,11.6421356 0,7.5 C0,3.35786438 3.35786438,0 7.5,0 C11.6421356,0 15,3.35786438 15,7.5 C15,11.6421356 11.6421356,15 7.5,15 Z' /%3E%3C/svg%3E"); - background-position: center; + background-image: url("data:image/svg+xml,%0A%3Csvg width='15px' height='15px' viewBox='0 0 15 15' version='1.1' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='#{hexToRGB($euiTextColor)}' d='M8,7 L8,3.5 C8,3.22385763 7.77614237,3 7.5,3 C7.22385763,3 7,3.22385763 7,3.5 L7,7 L3.5,7 C3.22385763,7 3,7.22385763 3,7.5 C3,7.77614237 3.22385763,8 3.5,8 L7,8 L7,11.5 C7,11.7761424 7.22385763,12 7.5,12 C7.77614237,12 8,11.7761424 8,11.5 L8,8 L11.5,8 C11.7761424,8 12,7.77614237 12,7.5 C12,7.22385763 11.7761424,7 11.5,7 L8,7 Z M7.5,15 C3.35786438,15 0,11.6421356 0,7.5 C0,3.35786438 3.35786438,0 7.5,0 C11.6421356,0 15,3.35786438 15,7.5 C15,11.6421356 11.6421356,15 7.5,15 Z' /%3E%3C/svg%3E") !important; + background-position: center !important; } -.mapboxgl-ctrl-icon.mapboxgl-ctrl-zoom-out { - background-repeat: no-repeat; +.mapboxgl-ctrl-zoom-out .mapboxgl-ctrl-icon { + // sass-lint:disable-block no-important + background-repeat: no-repeat !important; // sass-lint:disable-block quotes - background-image: url("data:image/svg+xml,%0A%3Csvg width='15px' height='15px' viewBox='0 0 15 15' version='1.1' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='#{hexToRGB($euiTextColor)}' d='M7.5,0 C11.6355882,0 15,3.36441176 15,7.5 C15,11.6355882 11.6355882,15 7.5,15 C3.36441176,15 0,11.6355882 0,7.5 C0,3.36441176 3.36441176,0 7.5,0 Z M3.5,7 C3.22385763,7 3,7.22385763 3,7.5 C3,7.77614237 3.22385763,8 3.5,8 L11.5,8 C11.7761424,8 12,7.77614237 12,7.5 C12,7.22385763 11.7761424,7 11.5,7 L3.5,7 Z' /%3E%3C/svg%3E"); - background-position: center; + background-image: url("data:image/svg+xml,%0A%3Csvg width='15px' height='15px' viewBox='0 0 15 15' version='1.1' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='#{hexToRGB($euiTextColor)}' d='M7.5,0 C11.6355882,0 15,3.36441176 15,7.5 C15,11.6355882 11.6355882,15 7.5,15 C3.36441176,15 0,11.6355882 0,7.5 C0,3.36441176 3.36441176,0 7.5,0 Z M3.5,7 C3.22385763,7 3,7.22385763 3,7.5 C3,7.77614237 3.22385763,8 3.5,8 L11.5,8 C11.7761424,8 12,7.77614237 12,7.5 C12,7.22385763 11.7761424,7 11.5,7 L3.5,7 Z' /%3E%3C/svg%3E") !important; + background-position: center !important; } diff --git a/x-pack/plugins/maps/public/actions/layer_actions.ts b/x-pack/plugins/maps/public/actions/layer_actions.ts index a0d2152e8866c..208f6dc6c6f85 100644 --- a/x-pack/plugins/maps/public/actions/layer_actions.ts +++ b/x-pack/plugins/maps/public/actions/layer_actions.ts @@ -35,12 +35,7 @@ import { UPDATE_LAYER_STYLE, UPDATE_SOURCE_PROP, } from './map_action_constants'; -import { - clearDataRequests, - syncDataForLayerId, - syncDataForLayer, - updateStyleMeta, -} from './data_request_actions'; +import { clearDataRequests, syncDataForLayerId, updateStyleMeta } from './data_request_actions'; import { cleanTooltipStateForLayer } from './tooltip_actions'; import { JoinDescriptor, LayerDescriptor, StyleDescriptor } from '../../common/descriptor_types'; import { ILayer } from '../classes/layers/layer'; @@ -175,7 +170,7 @@ export function promotePreviewLayers() { } export function setLayerVisibility(layerId: string, makeVisible: boolean) { - return async (dispatch: Dispatch, getState: () => MapStoreState) => { + return (dispatch: Dispatch, getState: () => MapStoreState) => { // if the current-state is invisible, we also want to sync data // e.g. if a layer was invisible at start-up, it won't have any data loaded const layer = getLayerById(layerId, getState()); @@ -189,19 +184,19 @@ export function setLayerVisibility(layerId: string, makeVisible: boolean) { dispatch(cleanTooltipStateForLayer(layerId)); } - await dispatch({ + dispatch({ type: SET_LAYER_VISIBILITY, layerId, visibility: makeVisible, }); if (makeVisible) { - dispatch(syncDataForLayer(layer)); + dispatch(syncDataForLayerId(layerId)); } }; } export function toggleLayerVisible(layerId: string) { - return async (dispatch: Dispatch, getState: () => MapStoreState) => { + return (dispatch: Dispatch, getState: () => MapStoreState) => { const layer = getLayerById(layerId, getState()); if (!layer) { return; diff --git a/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.test.tsx b/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.test.tsx new file mode 100644 index 0000000000000..5d234f5be44af --- /dev/null +++ b/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.test.tsx @@ -0,0 +1,150 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { SCALING_TYPES, SOURCE_TYPES } from '../../../../common/constants'; +import { BlendedVectorLayer } from './blended_vector_layer'; +// @ts-expect-error +import { ESSearchSource } from '../../sources/es_search_source'; +import { ESGeoGridSourceDescriptor } from '../../../../common/descriptor_types'; + +jest.mock('../../../kibana_services', () => { + return { + getIsDarkMode() { + return false; + }, + }; +}); + +const mapColors: string[] = []; + +const notClusteredDataRequest = { + data: { isSyncClustered: false }, + dataId: 'ACTIVE_COUNT_DATA_ID', +}; + +const clusteredDataRequest = { + data: { isSyncClustered: true }, + dataId: 'ACTIVE_COUNT_DATA_ID', +}; + +const documentSourceDescriptor = ESSearchSource.createDescriptor({ + geoField: 'myGeoField', + indexPatternId: 'myIndexPattern', + scalingType: SCALING_TYPES.CLUSTERS, +}); + +describe('getSource', () => { + describe('isClustered: true', () => { + test('should return cluster source', async () => { + const blendedVectorLayer = new BlendedVectorLayer({ + source: new ESSearchSource(documentSourceDescriptor), + layerDescriptor: BlendedVectorLayer.createDescriptor( + { + sourceDescriptor: documentSourceDescriptor, + __dataRequests: [clusteredDataRequest], + }, + mapColors + ), + }); + + const source = blendedVectorLayer.getSource(); + expect(source.cloneDescriptor().type).toBe(SOURCE_TYPES.ES_GEO_GRID); + }); + + test('cluster source applyGlobalQuery should be true when document source applyGlobalQuery is true', async () => { + const blendedVectorLayer = new BlendedVectorLayer({ + source: new ESSearchSource(documentSourceDescriptor), + layerDescriptor: BlendedVectorLayer.createDescriptor( + { + sourceDescriptor: documentSourceDescriptor, + __dataRequests: [clusteredDataRequest], + }, + mapColors + ), + }); + + const source = blendedVectorLayer.getSource(); + expect((source.cloneDescriptor() as ESGeoGridSourceDescriptor).applyGlobalQuery).toBe(true); + }); + + test('cluster source applyGlobalQuery should be false when document source applyGlobalQuery is false', async () => { + const blendedVectorLayer = new BlendedVectorLayer({ + source: new ESSearchSource({ + ...documentSourceDescriptor, + applyGlobalQuery: false, + }), + layerDescriptor: BlendedVectorLayer.createDescriptor( + { + sourceDescriptor: documentSourceDescriptor, + __dataRequests: [clusteredDataRequest], + }, + mapColors + ), + }); + + const source = blendedVectorLayer.getSource(); + expect((source.cloneDescriptor() as ESGeoGridSourceDescriptor).applyGlobalQuery).toBe(false); + }); + }); + + describe('isClustered: false', () => { + test('should return document source', async () => { + const blendedVectorLayer = new BlendedVectorLayer({ + source: new ESSearchSource(documentSourceDescriptor), + layerDescriptor: BlendedVectorLayer.createDescriptor( + { + sourceDescriptor: documentSourceDescriptor, + __dataRequests: [notClusteredDataRequest], + }, + mapColors + ), + }); + + const source = blendedVectorLayer.getSource(); + expect(source.cloneDescriptor().type).toBe(SOURCE_TYPES.ES_SEARCH); + }); + }); +}); + +describe('cloneDescriptor', () => { + describe('isClustered: true', () => { + test('Cloned layer descriptor sourceDescriptor should be document source', async () => { + const blendedVectorLayer = new BlendedVectorLayer({ + source: new ESSearchSource(documentSourceDescriptor), + layerDescriptor: BlendedVectorLayer.createDescriptor( + { + sourceDescriptor: documentSourceDescriptor, + __dataRequests: [clusteredDataRequest], + }, + mapColors + ), + }); + + const clonedLayerDescriptor = await blendedVectorLayer.cloneDescriptor(); + expect(clonedLayerDescriptor.sourceDescriptor!.type).toBe(SOURCE_TYPES.ES_SEARCH); + expect(clonedLayerDescriptor.label).toBe('Clone of myIndexPattern'); + }); + }); + + describe('isClustered: false', () => { + test('Cloned layer descriptor sourceDescriptor should be document source', async () => { + const blendedVectorLayer = new BlendedVectorLayer({ + source: new ESSearchSource(documentSourceDescriptor), + layerDescriptor: BlendedVectorLayer.createDescriptor( + { + sourceDescriptor: documentSourceDescriptor, + __dataRequests: [notClusteredDataRequest], + }, + mapColors + ), + }); + + const clonedLayerDescriptor = await blendedVectorLayer.cloneDescriptor(); + expect(clonedLayerDescriptor.sourceDescriptor!.type).toBe(SOURCE_TYPES.ES_SEARCH); + expect(clonedLayerDescriptor.label).toBe('Clone of myIndexPattern'); + }); + }); +}); diff --git a/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.ts b/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.ts index c0b9c4553d01e..950d9890a3c65 100644 --- a/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.ts +++ b/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.ts @@ -34,6 +34,7 @@ import { SizeDynamicOptions, DynamicStylePropertyOptions, StylePropertyOptions, + LayerDescriptor, VectorLayerDescriptor, } from '../../../../common/descriptor_types'; import { IStyle } from '../../styles/style'; @@ -55,6 +56,7 @@ function getClusterSource(documentSource: IESSource, documentStyle: IVectorStyle geoField: documentSource.getGeoFieldName(), requestType: RENDER_AS.POINT, }); + clusterSourceDescriptor.applyGlobalQuery = documentSource.getApplyGlobalQuery(); clusterSourceDescriptor.metrics = [ { type: AGG_TYPE.COUNT, @@ -215,7 +217,7 @@ export class BlendedVectorLayer extends VectorLayer implements IVectorLayer { } } - async getDisplayName(source: ISource) { + async getDisplayName(source?: ISource) { const displayName = await super.getDisplayName(source); return this._isClustered ? i18n.translate('xpack.maps.blendedVectorLayer.clusteredLayerName', { @@ -241,6 +243,19 @@ export class BlendedVectorLayer extends VectorLayer implements IVectorLayer { return false; } + async cloneDescriptor(): Promise { + const clonedDescriptor = await super.cloneDescriptor(); + + // Use super getDisplayName instead of instance getDisplayName to avoid getting 'Clustered Clone of Clustered' + const displayName = await super.getDisplayName(); + clonedDescriptor.label = `Clone of ${displayName}`; + + // sourceDescriptor must be document source descriptor + clonedDescriptor.sourceDescriptor = this._documentSource.cloneDescriptor(); + + return clonedDescriptor; + } + getSource() { return this._isClustered ? this._clusterSource : this._documentSource; } diff --git a/x-pack/plugins/maps/public/classes/layers/layer.test.ts b/x-pack/plugins/maps/public/classes/layers/layer.test.ts new file mode 100644 index 0000000000000..f25ecd7106457 --- /dev/null +++ b/x-pack/plugins/maps/public/classes/layers/layer.test.ts @@ -0,0 +1,128 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +/* eslint-disable max-classes-per-file */ + +import { AbstractLayer } from './layer'; +import { ISource } from '../sources/source'; +import { IStyle } from '../styles/style'; +import { AGG_TYPE, FIELD_ORIGIN, LAYER_STYLE_TYPE, VECTOR_STYLES } from '../../../common/constants'; +import { ESTermSourceDescriptor, VectorStyleDescriptor } from '../../../common/descriptor_types'; +import { getDefaultDynamicProperties } from '../styles/vector/vector_style_defaults'; + +jest.mock('uuid/v4', () => { + return function () { + return '12345'; + }; +}); + +class MockLayer extends AbstractLayer {} + +class MockSource { + cloneDescriptor() { + return {}; + } + + getDisplayName() { + return 'mySource'; + } +} + +class MockStyle {} + +describe('cloneDescriptor', () => { + describe('with joins', () => { + const styleDescriptor = { + type: LAYER_STYLE_TYPE.VECTOR, + properties: { + ...getDefaultDynamicProperties(), + }, + } as VectorStyleDescriptor; + // @ts-expect-error + styleDescriptor.properties[VECTOR_STYLES.FILL_COLOR].options.field = { + name: '__kbnjoin__count__557d0f15', + origin: FIELD_ORIGIN.JOIN, + }; + // @ts-expect-error + styleDescriptor.properties[VECTOR_STYLES.LINE_COLOR].options.field = { + name: 'bytes', + origin: FIELD_ORIGIN.SOURCE, + }; + // @ts-expect-error + styleDescriptor.properties[VECTOR_STYLES.LABEL_BORDER_COLOR].options.field = { + name: '__kbnjoin__count__6666666666', + origin: FIELD_ORIGIN.JOIN, + }; + + test('Should update data driven styling properties using join fields', async () => { + const layerDescriptor = AbstractLayer.createDescriptor({ + style: styleDescriptor, + joins: [ + { + leftField: 'iso2', + right: { + id: '557d0f15', + indexPatternId: 'myIndexPattern', + indexPatternTitle: 'logs-*', + metrics: [{ type: AGG_TYPE.COUNT }], + term: 'myTermField', + type: 'joinSource', + }, + }, + ], + }); + const layer = new MockLayer({ + layerDescriptor, + source: (new MockSource() as unknown) as ISource, + style: (new MockStyle() as unknown) as IStyle, + }); + const clonedDescriptor = await layer.cloneDescriptor(); + const clonedStyleProps = (clonedDescriptor.style as VectorStyleDescriptor).properties; + // Should update style field belonging to join + // @ts-expect-error + expect(clonedStyleProps[VECTOR_STYLES.FILL_COLOR].options.field.name).toEqual( + '__kbnjoin__count__12345' + ); + // Should not update style field belonging to source + // @ts-expect-error + expect(clonedStyleProps[VECTOR_STYLES.LINE_COLOR].options.field.name).toEqual('bytes'); + // Should not update style feild belonging to different join + // @ts-expect-error + expect(clonedStyleProps[VECTOR_STYLES.LABEL_BORDER_COLOR].options.field.name).toEqual( + '__kbnjoin__count__6666666666' + ); + }); + + test('Should update data driven styling properties using join fields when metrics are not provided', async () => { + const layerDescriptor = AbstractLayer.createDescriptor({ + style: styleDescriptor, + joins: [ + { + leftField: 'iso2', + right: ({ + id: '557d0f15', + indexPatternId: 'myIndexPattern', + indexPatternTitle: 'logs-*', + term: 'myTermField', + type: 'joinSource', + } as unknown) as ESTermSourceDescriptor, + }, + ], + }); + const layer = new MockLayer({ + layerDescriptor, + source: (new MockSource() as unknown) as ISource, + style: (new MockStyle() as unknown) as IStyle, + }); + const clonedDescriptor = await layer.cloneDescriptor(); + const clonedStyleProps = (clonedDescriptor.style as VectorStyleDescriptor).properties; + // Should update style field belonging to join + // @ts-expect-error + expect(clonedStyleProps[VECTOR_STYLES.FILL_COLOR].options.field.name).toEqual( + '__kbnjoin__count__12345' + ); + }); + }); +}); diff --git a/x-pack/plugins/maps/public/classes/layers/layer.tsx b/x-pack/plugins/maps/public/classes/layers/layer.tsx index d8def155a9185..424100c5a7e3a 100644 --- a/x-pack/plugins/maps/public/classes/layers/layer.tsx +++ b/x-pack/plugins/maps/public/classes/layers/layer.tsx @@ -14,16 +14,26 @@ import { i18n } from '@kbn/i18n'; import { FeatureCollection } from 'geojson'; import { DataRequest } from '../util/data_request'; import { + AGG_TYPE, + FIELD_ORIGIN, MAX_ZOOM, MB_SOURCE_ID_LAYER_ID_PREFIX_DELIMITER, MIN_ZOOM, SOURCE_DATA_REQUEST_ID, + STYLE_TYPE, } from '../../../common/constants'; import { copyPersistentState } from '../../reducers/util'; -import { LayerDescriptor, MapExtent, StyleDescriptor } from '../../../common/descriptor_types'; +import { + AggDescriptor, + JoinDescriptor, + LayerDescriptor, + MapExtent, + StyleDescriptor, +} from '../../../common/descriptor_types'; import { Attribution, ImmutableSourceProperty, ISource, SourceEditorArgs } from '../sources/source'; import { DataRequestContext } from '../../actions'; import { IStyle } from '../styles/style'; +import { getJoinAggKey } from '../../../common/get_agg_key'; export interface ILayer { getBounds(dataRequestContext: DataRequestContext): Promise; @@ -157,10 +167,43 @@ export class AbstractLayer implements ILayer { clonedDescriptor.sourceDescriptor = this.getSource().cloneDescriptor(); if (clonedDescriptor.joins) { - // @ts-expect-error - clonedDescriptor.joins.forEach((joinDescriptor) => { + clonedDescriptor.joins.forEach((joinDescriptor: JoinDescriptor) => { + const originalJoinId = joinDescriptor.right.id!; + // right.id is uuid used to track requests in inspector joinDescriptor.right.id = uuid(); + + // Update all data driven styling properties using join fields + if (clonedDescriptor.style && 'properties' in clonedDescriptor.style) { + const metrics = + joinDescriptor.right.metrics && joinDescriptor.right.metrics.length + ? joinDescriptor.right.metrics + : [{ type: AGG_TYPE.COUNT }]; + metrics.forEach((metricsDescriptor: AggDescriptor) => { + const originalJoinKey = getJoinAggKey({ + aggType: metricsDescriptor.type, + aggFieldName: metricsDescriptor.field ? metricsDescriptor.field : '', + rightSourceId: originalJoinId, + }); + const newJoinKey = getJoinAggKey({ + aggType: metricsDescriptor.type, + aggFieldName: metricsDescriptor.field ? metricsDescriptor.field : '', + rightSourceId: joinDescriptor.right.id!, + }); + + Object.keys(clonedDescriptor.style.properties).forEach((key) => { + const styleProp = clonedDescriptor.style.properties[key]; + if ( + styleProp.type === STYLE_TYPE.DYNAMIC && + styleProp.options.field && + styleProp.options.field.origin === FIELD_ORIGIN.JOIN && + styleProp.options.field.name === originalJoinKey + ) { + styleProp.options.field.name = newJoinKey; + } + }); + }); + } }); } return clonedDescriptor; diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js index 92f6c258af597..a4dba71307b71 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js @@ -161,7 +161,6 @@ export class ESGeoGridSource extends AbstractESAggSource { bounds: makeESBbox(bufferedExtent), field: this._descriptor.geoField, precision, - size: DEFAULT_MAX_BUCKETS_LIMIT, }, }, }, diff --git a/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/__snapshots__/xyz_tms_editor.test.tsx.snap b/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/__snapshots__/xyz_tms_editor.test.tsx.snap new file mode 100644 index 0000000000000..b8ed4a727fad0 --- /dev/null +++ b/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/__snapshots__/xyz_tms_editor.test.tsx.snap @@ -0,0 +1,237 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`attribution validation should provide no validation errors when attribution text and attribution url are provided 1`] = ` + + + + + + + + + + + +`; + +exports[`attribution validation should provide validation error when attribution text is provided without attribution url 1`] = ` + + + + + + + + + + + +`; + +exports[`attribution validation should provide validation error when attribution url is provided without attribution text 1`] = ` + + + + + + + + + + + +`; + +exports[`should render 1`] = ` + + + + + + + + + + + +`; diff --git a/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/layer_wizard.tsx b/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/layer_wizard.tsx index 48c526855d3a4..b0344a3e0e318 100644 --- a/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/layer_wizard.tsx +++ b/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/layer_wizard.tsx @@ -19,7 +19,12 @@ export const tmsLayerWizardConfig: LayerWizard = { }), icon: 'grid', renderWizard: ({ previewLayers }: RenderWizardArguments) => { - const onSourceConfigChange = (sourceConfig: XYZTMSSourceConfig) => { + const onSourceConfigChange = (sourceConfig: XYZTMSSourceConfig | null) => { + if (!sourceConfig) { + previewLayers([]); + return; + } + const layerDescriptor = TileLayer.createDescriptor({ sourceDescriptor: XYZTMSSource.createDescriptor(sourceConfig), }); diff --git a/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.test.tsx b/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.test.tsx new file mode 100644 index 0000000000000..71f78c3e15152 --- /dev/null +++ b/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.test.tsx @@ -0,0 +1,37 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { shallow } from 'enzyme'; +import { XYZTMSEditor } from './xyz_tms_editor'; + +const onSourceConfigChange = () => {}; + +test('should render', () => { + const component = shallow(); + expect(component).toMatchSnapshot(); +}); + +describe('attribution validation', () => { + test('should provide validation error when attribution text is provided without attribution url', () => { + const component = shallow(); + component.setState({ attributionText: 'myAttribtionLabel' }); + expect(component).toMatchSnapshot(); + }); + + test('should provide validation error when attribution url is provided without attribution text', () => { + const component = shallow(); + component.setState({ attributionUrl: 'http://mySource' }); + expect(component).toMatchSnapshot(); + }); + + test('should provide no validation errors when attribution text and attribution url are provided', () => { + const component = shallow(); + component.setState({ attributionText: 'myAttribtionLabel' }); + component.setState({ attributionUrl: 'http://mySource' }); + expect(component).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.tsx b/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.tsx index bf5f2c3dfe04d..5583f637b4471 100644 --- a/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.tsx +++ b/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.tsx @@ -9,70 +9,56 @@ import React, { Component, ChangeEvent } from 'react'; import _ from 'lodash'; import { EuiFormRow, EuiFieldText, EuiPanel } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { AttributionDescriptor } from '../../../../common/descriptor_types'; -export type XYZTMSSourceConfig = AttributionDescriptor & { +export type XYZTMSSourceConfig = { urlTemplate: string; + attributionText: string; + attributionUrl: string; }; -export interface Props { - onSourceConfigChange: (sourceConfig: XYZTMSSourceConfig) => void; +interface Props { + onSourceConfigChange: (sourceConfig: XYZTMSSourceConfig | null) => void; } interface State { - tmsInput: string; - tmsCanPreview: boolean; + url: string; attributionText: string; attributionUrl: string; } export class XYZTMSEditor extends Component { state = { - tmsInput: '', - tmsCanPreview: false, + url: '', attributionText: '', attributionUrl: '', }; - _sourceConfigChange = _.debounce((updatedSourceConfig: XYZTMSSourceConfig) => { - if (this.state.tmsCanPreview) { - this.props.onSourceConfigChange(updatedSourceConfig); - } - }, 2000); - - _handleTMSInputChange(e: ChangeEvent) { - const url = e.target.value; + _previewLayer = _.debounce(() => { + const { url, attributionText, attributionUrl } = this.state; - const canPreview = + const isUrlValid = url.indexOf('{x}') >= 0 && url.indexOf('{y}') >= 0 && url.indexOf('{z}') >= 0; - this.setState( - { - tmsInput: url, - tmsCanPreview: canPreview, - }, - () => this._sourceConfigChange({ urlTemplate: url }) - ); - } + const sourceConfig = isUrlValid + ? { + urlTemplate: url, + attributionText, + attributionUrl, + } + : null; + this.props.onSourceConfigChange(sourceConfig); + }, 500); - _handleTMSAttributionChange(attributionUpdate: AttributionDescriptor) { - this.setState( - { - attributionUrl: attributionUpdate.attributionUrl || '', - attributionText: attributionUpdate.attributionText || '', - }, - () => { - const { attributionText, attributionUrl, tmsInput } = this.state; + _onUrlChange = (event: ChangeEvent) => { + this.setState({ url: event.target.value }, this._previewLayer); + }; - if (tmsInput && attributionText && attributionUrl) { - this._sourceConfigChange({ - urlTemplate: tmsInput, - attributionText, - attributionUrl, - }); - } - } - ); - } + _onAttributionTextChange = (event: ChangeEvent) => { + this.setState({ attributionText: event.target.value }, this._previewLayer); + }; + + _onAttributionUrlChange = (event: ChangeEvent) => { + this.setState({ attributionUrl: event.target.value }, this._previewLayer); + }; render() { const { attributionText, attributionUrl } = this.state; @@ -81,11 +67,13 @@ export class XYZTMSEditor extends Component { this._handleTMSInputChange(e)} + onChange={this._onUrlChange} /> { }), ]} > - ) => - this._handleTMSAttributionChange({ attributionText: target.value }) - } - /> + { }), ]} > - ) => - this._handleTMSAttributionChange({ attributionUrl: target.value }) - } - /> + ); diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/filter_editor/filter_editor.js b/x-pack/plugins/maps/public/connected_components/layer_panel/filter_editor/filter_editor.js index 45c7507160e98..d2652fac5bd2c 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/filter_editor/filter_editor.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/filter_editor/filter_editor.js @@ -20,8 +20,7 @@ import { import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; -import { UI_SETTINGS } from '../../../../../../../src/plugins/data/public'; -import { getIndexPatternService, getUiSettings, getData } from '../../../kibana_services'; +import { getIndexPatternService, getData } from '../../../kibana_services'; import { GlobalFilterCheckbox } from '../../../components/global_filter_checkbox'; export class FilterEditor extends Component { @@ -82,7 +81,6 @@ export class FilterEditor extends Component { _renderQueryPopover() { const layerQuery = this.props.layer.getQuery(); - const uiSettings = getUiSettings(); const { SearchBar } = getData().ui; return ( @@ -99,11 +97,7 @@ export class FilterEditor extends Component { showFilterBar={false} showDatePicker={false} showQueryInput={true} - query={ - layerQuery - ? layerQuery - : { language: uiSettings.get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE), query: '' } - } + query={layerQuery ? layerQuery : getData().query.queryString.getDefaultQuery()} onQuerySubmit={this._onQueryChange} indexPatterns={this.state.indexPatterns} customSubmitButton={ diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/where_expression.js b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/where_expression.js index 8fdb71de2dfed..60151219a994f 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/where_expression.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/where_expression.js @@ -8,8 +8,7 @@ import React, { Component } from 'react'; import { i18n } from '@kbn/i18n'; import { EuiButton, EuiPopover, EuiExpression, EuiFormHelpText } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { UI_SETTINGS } from '../../../../../../../../src/plugins/data/public'; -import { getUiSettings, getData } from '../../../../kibana_services'; +import { getData } from '../../../../kibana_services'; export class WhereExpression extends Component { state = { @@ -77,11 +76,7 @@ export class WhereExpression extends Component { showFilterBar={false} showDatePicker={false} showQueryInput={true} - query={ - whereQuery - ? whereQuery - : { language: getUiSettings().get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE), query: '' } - } + query={whereQuery ? whereQuery : getData().query.queryString.getDefaultQuery()} onQuerySubmit={this._onQueryChange} indexPatterns={[indexPattern]} customSubmitButton={ diff --git a/x-pack/plugins/maps/public/routing/bootstrap/get_initial_query.js b/x-pack/plugins/maps/public/routing/bootstrap/get_initial_query.js index dfc3a1c9de96a..1f2cf27077623 100644 --- a/x-pack/plugins/maps/public/routing/bootstrap/get_initial_query.js +++ b/x-pack/plugins/maps/public/routing/bootstrap/get_initial_query.js @@ -4,12 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getUiSettings } from '../../kibana_services'; -import { UI_SETTINGS } from '../../../../../../src/plugins/data/public'; - -export function getInitialQuery({ mapStateJSON, appState = {}, userQueryLanguage }) { - const settings = getUiSettings(); +import { getData } from '../../kibana_services'; +export function getInitialQuery({ mapStateJSON, appState = {} }) { if (appState.query) { return appState.query; } @@ -21,8 +18,5 @@ export function getInitialQuery({ mapStateJSON, appState = {}, userQueryLanguage } } - return { - query: '', - language: userQueryLanguage || settings.get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE), - }; + return getData().query.queryString.getDefaultQuery(); } diff --git a/x-pack/plugins/maps/public/routing/page_elements/top_nav_menu/top_nav_menu.js b/x-pack/plugins/maps/public/routing/page_elements/top_nav_menu/top_nav_menu.js index ac2dec0db59cc..2340e3716547b 100644 --- a/x-pack/plugins/maps/public/routing/page_elements/top_nav_menu/top_nav_menu.js +++ b/x-pack/plugins/maps/public/routing/page_elements/top_nav_menu/top_nav_menu.js @@ -14,7 +14,6 @@ import { getToasts, getCoreI18n, getData, - getUiSettings, } from '../../../kibana_services'; import { SavedObjectSaveModal, @@ -46,16 +45,13 @@ export function MapsTopNavMenu({ isOpenSettingsDisabled, }) { const { TopNavMenu } = getNavigation().ui; - const { filterManager } = getData().query; + const { filterManager, queryString } = getData().query; const showSaveQuery = getMapsCapabilities().saveQuery; const onClearSavedQuery = () => { onQuerySaved(undefined); onQueryChange({ filters: filterManager.getGlobalFilters(), - query: { - query: '', - language: getUiSettings().get('search:queryLanguage'), - }, + query: queryString.getDefaultQuery(), }); }; diff --git a/x-pack/plugins/maps/public/routing/routes/maps_app/maps_app_view.js b/x-pack/plugins/maps/public/routing/routes/maps_app/maps_app_view.js index aa7f24155ab43..bccfdbf2467d6 100644 --- a/x-pack/plugins/maps/public/routing/routes/maps_app/maps_app_view.js +++ b/x-pack/plugins/maps/public/routing/routes/maps_app/maps_app_view.js @@ -13,7 +13,6 @@ import { getIndexPatternService, getToasts, getData, - getUiSettings, getCoreChrome, } from '../../../kibana_services'; import { copyPersistentState } from '../../../reducers/util'; @@ -274,6 +273,7 @@ export class MapsAppView extends React.Component { _initQueryTimeRefresh() { const { setRefreshConfig, savedMap } = this.props; + const { queryString } = getData().query; // TODO: Handle null when converting to TS const globalState = getGlobalState(); const mapStateJSON = savedMap ? savedMap.mapStateJSON : undefined; @@ -281,7 +281,6 @@ export class MapsAppView extends React.Component { query: getInitialQuery({ mapStateJSON, appState: this._appStateManager.getAppState(), - userQueryLanguage: getUiSettings().get('search:queryLanguage'), }), time: getInitialTimeFilters({ mapStateJSON, @@ -292,6 +291,8 @@ export class MapsAppView extends React.Component { globalState, }), }; + + if (newState.query) queryString.setQuery(newState.query); this.setState({ query: newState.query, time: newState.time }); updateGlobalState( { diff --git a/x-pack/plugins/maps/public/routing/state_syncing/app_sync.js b/x-pack/plugins/maps/public/routing/state_syncing/app_sync.js index 36b20174f2436..69d6dbbe0c4d3 100644 --- a/x-pack/plugins/maps/public/routing/state_syncing/app_sync.js +++ b/x-pack/plugins/maps/public/routing/state_syncing/app_sync.js @@ -31,6 +31,7 @@ export function useAppStateSyncing(appStateManager) { }; const stopSyncingQueryAppStateWithStateContainer = connectToQueryState(query, stateContainer, { filters: esFilters.FilterStateStore.APP_STATE, + query: true, }); // sets up syncing app state container with url diff --git a/x-pack/plugins/ml/common/types/capabilities.ts b/x-pack/plugins/ml/common/types/capabilities.ts index f2177b0a3572f..58a2043502d27 100644 --- a/x-pack/plugins/ml/common/types/capabilities.ts +++ b/x-pack/plugins/ml/common/types/capabilities.ts @@ -7,6 +7,10 @@ import { KibanaRequest } from 'kibana/server'; import { PLUGIN_ID } from '../constants/app'; +export const apmUserMlCapabilities = { + canGetJobs: false, +}; + export const userMlCapabilities = { canAccessML: false, // Anomaly Detection @@ -68,10 +72,12 @@ export function getDefaultCapabilities(): MlCapabilities { } export function getPluginPrivileges() { + const apmUserMlCapabilitiesKeys = Object.keys(apmUserMlCapabilities); const userMlCapabilitiesKeys = Object.keys(userMlCapabilities); const adminMlCapabilitiesKeys = Object.keys(adminMlCapabilities); const allMlCapabilitiesKeys = [...adminMlCapabilitiesKeys, ...userMlCapabilitiesKeys]; // TODO: include ML in base privileges for the `8.0` release: https://github.com/elastic/kibana/issues/71422 + const savedObjects = ['index-pattern', 'dashboard', 'search', 'visualization']; const privilege = { app: [PLUGIN_ID, 'kibana'], excludeFromBasePrivileges: true, @@ -79,10 +85,6 @@ export function getPluginPrivileges() { insightsAndAlerting: ['jobsListLink'], }, catalogue: [PLUGIN_ID], - savedObject: { - all: [], - read: ['index-pattern', 'dashboard', 'search', 'visualization'], - }, }; return { @@ -90,11 +92,30 @@ export function getPluginPrivileges() { ...privilege, api: allMlCapabilitiesKeys.map((k) => `ml:${k}`), ui: allMlCapabilitiesKeys, + savedObject: { + all: savedObjects, + read: savedObjects, + }, }, user: { ...privilege, api: userMlCapabilitiesKeys.map((k) => `ml:${k}`), ui: userMlCapabilitiesKeys, + savedObject: { + all: [], + read: savedObjects, + }, + }, + apmUser: { + excludeFromBasePrivileges: true, + app: [], + catalogue: [], + savedObject: { + all: [], + read: [], + }, + api: apmUserMlCapabilitiesKeys.map((k) => `ml:${k}`), + ui: apmUserMlCapabilitiesKeys, }, }; } diff --git a/x-pack/plugins/ml/public/application/components/chart_tooltip/_chart_tooltip.scss b/x-pack/plugins/ml/public/application/components/chart_tooltip/_chart_tooltip.scss index 25bf3597c3466..46e5d91e1cc83 100644 --- a/x-pack/plugins/ml/public/application/components/chart_tooltip/_chart_tooltip.scss +++ b/x-pack/plugins/ml/public/application/components/chart_tooltip/_chart_tooltip.scss @@ -25,15 +25,10 @@ } &__label { - overflow-wrap: break-word; - word-wrap: break-word; min-width: 1px; - flex: 1 1 auto; } &__value { - overflow-wrap: break-word; - word-wrap: break-word; font-weight: $euiFontWeightBold; text-align: right; font-feature-settings: 'tnum'; diff --git a/x-pack/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx b/x-pack/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx index 7897ef5cad0df..3bd4ae1748311 100644 --- a/x-pack/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx +++ b/x-pack/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx @@ -7,6 +7,7 @@ import React, { FC, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import classNames from 'classnames'; import TooltipTrigger from 'react-popper-tooltip'; +import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { TooltipValueFormatter } from '@elastic/charts'; import './_index.scss'; @@ -79,8 +80,17 @@ const Tooltip: FC<{ service: ChartTooltipService }> = React.memo(({ service }) = borderLeftColor: color, }} > - {label} - {value} + + + {label} + + + {value} + +
); })} diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/details_step/details_step_form.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/details_step/details_step_form.tsx index 8442ca13910d1..0ac237bb33e76 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/details_step/details_step_form.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/details_step/details_step_form.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { FC, Fragment, useRef, useEffect } from 'react'; +import React, { FC, Fragment, useRef, useEffect, useState } from 'react'; import { debounce } from 'lodash'; import { EuiFieldText, @@ -25,6 +25,14 @@ import { ANALYTICS_STEPS } from '../../page'; import { ml } from '../../../../../services/ml_api_service'; import { extractErrorMessage } from '../../../../../../../common/util/errors'; +const indexNameExistsMessage = i18n.translate( + 'xpack.ml.dataframe.analytics.create.destinationIndexHelpText', + { + defaultMessage: + 'An index with this name already exists. Be aware that running this analytics job will modify this destination index.', + } +); + export const DetailsStepForm: FC = ({ actions, state, @@ -36,7 +44,7 @@ export const DetailsStepForm: FC = ({ const { ELASTIC_WEBSITE_URL, DOC_LINK_VERSION } = docLinks; const { setFormState } = actions; - const { form, isJobCreated } = state; + const { form, cloneJob, isJobCreated } = state; const { createIndexPattern, description, @@ -52,6 +60,9 @@ export const DetailsStepForm: FC = ({ jobIdValid, resultsField, } = form; + + const [destIndexSameAsId, setDestIndexSameAsId] = useState(cloneJob === undefined); + const forceInput = useRef(null); const isStepInvalid = @@ -88,6 +99,14 @@ export const DetailsStepForm: FC = ({ }; }, [destinationIndex]); + useEffect(() => { + if (destIndexSameAsId === true && !jobIdEmpty && jobIdValid) { + setFormState({ destinationIndex: jobId }); + } else if (destIndexSameAsId === false) { + setFormState({ destinationIndex: '' }); + } + }, [destIndexSameAsId, jobId]); + return ( = ({ - {i18n.translate('xpack.ml.dataframe.analytics.create.destinationIndexInvalidError', { - defaultMessage: 'Invalid destination index name.', - })} -
- - {i18n.translate( - 'xpack.ml.dataframe.stepDetailsForm.destinationIndexInvalidErrorLink', - { - defaultMessage: 'Learn more about index name limitations.', - } - )} - -
, - ] + destIndexSameAsId === true && destinationIndexNameExists && indexNameExistsMessage } > - setFormState({ destinationIndex: e.target.value })} - aria-label={i18n.translate( - 'xpack.ml.dataframe.analytics.create.destinationIndexInputAriaLabel', - { - defaultMessage: 'Choose a unique destination index name.', - } - )} - isInvalid={!destinationIndexNameEmpty && !destinationIndexNameValid} - data-test-subj="mlAnalyticsCreateJobFlyoutDestinationIndexInput" + name="mlDataFrameAnalyticsDestIndexSameAsId" + label={i18n.translate('xpack.ml.dataframe.analytics.create.DestIndexSameAsIdLabel', { + defaultMessage: 'Destination index same as job ID', + })} + checked={destIndexSameAsId === true} + onChange={() => setDestIndexSameAsId(!destIndexSameAsId)} + data-test-subj="mlAnalyticsCreateJobWizardDestIndexSameAsIdSwitch" /> + {destIndexSameAsId === false && ( + + {i18n.translate( + 'xpack.ml.dataframe.analytics.create.destinationIndexInvalidError', + { + defaultMessage: 'Invalid destination index name.', + } + )} +
+ + {i18n.translate( + 'xpack.ml.dataframe.stepDetailsForm.destinationIndexInvalidErrorLink', + { + defaultMessage: 'Learn more about index name limitations.', + } + )} + + , + ] + } + > + setFormState({ destinationIndex: e.target.value })} + aria-label={i18n.translate( + 'xpack.ml.dataframe.analytics.create.destinationIndexInputAriaLabel', + { + defaultMessage: 'Choose a unique destination index name.', + } + )} + isInvalid={!destinationIndexNameEmpty && !destinationIndexNameValid} + data-test-subj="mlAnalyticsCreateJobFlyoutDestinationIndexInput" + /> +
+ )} { ); if (ip !== undefined) { setIndexPatternExists(true); + } else { + setIndexPatternExists(false); } } catch (e) { const { toasts } = notifications; @@ -101,7 +103,7 @@ export const useDeleteAction = () => { // Check if an user has permission to delete the index & index pattern checkUserIndexPermission(); - }, []); + }, [isModalVisible]); const closeModal = () => setModalVisible(false); const deleteAndCloseModal = () => { diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/bottom_bar/bottom_bar.tsx b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/bottom_bar/bottom_bar.tsx index e28386093abe0..8b6c16a71651a 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/bottom_bar/bottom_bar.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/bottom_bar/bottom_bar.tsx @@ -39,7 +39,7 @@ export const BottomBar: FC = ({ mode, onChangeMode, onCancel, di disableImport ? ( ) : null } diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/import_view/import_view.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/import_view/import_view.js index 64d2e26f827f8..36b77a5a25e09 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/import_view/import_view.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/import_view/import_view.js @@ -18,6 +18,7 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; +import { debounce } from 'lodash'; import { importerFactory } from './importer'; import { ResultsLinks } from '../results_links'; import { FilebeatConfigFlyout } from '../filebeat_config_flyout'; @@ -66,6 +67,7 @@ const DEFAULT_STATE = { indexPatternNameError: '', timeFieldName: undefined, isFilebeatFlyoutVisible: false, + checkingValidIndex: false, }; export class ImportView extends Component { @@ -76,14 +78,12 @@ export class ImportView extends Component { } componentDidMount() { - this.loadIndexNames(); this.loadIndexPatternNames(); } clickReset = () => { const state = getDefaultState(this.state, this.props.results); this.setState(state, () => { - this.loadIndexNames(); this.loadIndexPatternNames(); }); }; @@ -326,21 +326,33 @@ export class ImportView extends Component { }; onIndexChange = (e) => { - const name = e.target.value; - const { indexNames, indexPattern, indexPatternNames } = this.state; - + const index = e.target.value; this.setState({ - index: name, - indexNameError: isIndexNameValid(name, indexNames), - // if index pattern has been altered, check that it still matches the inputted index - ...(indexPattern === '' - ? {} - : { - indexPatternNameError: isIndexPatternNameValid(indexPattern, indexPatternNames, name), - }), + index, + checkingValidIndex: true, }); + this.debounceIndexCheck(index); }; + debounceIndexCheck = debounce(async (index) => { + if (index === '') { + this.setState({ checkingValidIndex: false }); + return; + } + + const { exists } = await ml.checkIndexExists({ index }); + const indexNameError = exists ? ( + + ) : ( + isIndexNameValid(index) + ); + + this.setState({ checkingValidIndex: false, indexNameError }); + }, 500); + onIndexPatternChange = (e) => { const name = e.target.value; const { indexPatternNames, index } = this.state; @@ -396,12 +408,6 @@ export class ImportView extends Component { this.props.showBottomBar(); }; - async loadIndexNames() { - const indices = await ml.getIndices(); - const indexNames = indices.map((i) => i.name); - this.setState({ indexNames }); - } - async loadIndexPatternNames() { await loadIndexPatterns(this.props.indexPatterns); const indexPatternNames = getIndexPatternNames(); @@ -437,6 +443,7 @@ export class ImportView extends Component { indexPatternNameError, timeFieldName, isFilebeatFlyoutVisible, + checkingValidIndex, } = this.state; const createPipeline = pipelineString !== ''; @@ -459,7 +466,8 @@ export class ImportView extends Component { index === '' || indexNameError !== '' || (createIndexPattern === true && indexPatternNameError !== '') || - initialized === true; + initialized === true || + checkingValidIndex === true; return ( @@ -655,16 +663,7 @@ function getDefaultState(state, results) { }; } -function isIndexNameValid(name, indexNames) { - if (indexNames.find((i) => i === name)) { - return ( - - ); - } - +function isIndexNameValid(name) { const reg = new RegExp('[\\\\/*?"<>|\\s,#]+'); if ( name !== name.toLowerCase() || // name should be lowercase diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/results_links/results_links.tsx b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/results_links/results_links.tsx index 088c2a0cad7e2..efade08720cc2 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/results_links/results_links.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/results_links/results_links.tsx @@ -139,7 +139,7 @@ export const ResultsLinks: FC = ({ /> } description="" - href={`${basePath.get()}/app/management/data/index_management/indices/filter/${index}`} + href={`${basePath.get()}/app/management/data/index_management/indices`} /> diff --git a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/utils.js b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/utils.js index 0b33efa3f9ff1..87c2219f4d441 100644 --- a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/utils.js +++ b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/utils.js @@ -11,7 +11,6 @@ import url from 'url'; import { DASHBOARD_APP_URL_GENERATOR } from '../../../../../../../../src/plugins/dashboard/public'; -import { ML_RESULTS_INDEX_PATTERN } from '../../../../../common/constants/index_patterns'; import { getPartitioningFieldNames } from '../../../../../common/util/job_utils'; import { parseInterval } from '../../../../../common/util/parse_interval'; import { replaceTokensInUrlValue, isValidLabel } from '../../../util/custom_url_utils'; @@ -295,11 +294,11 @@ export function getTestUrl(job, customUrl) { }; return new Promise((resolve, reject) => { - ml.esSearch({ - index: ML_RESULTS_INDEX_PATTERN, - rest_total_hits_as_int: true, - body, - }) + ml.results + .anomalySearch({ + rest_total_hits_as_int: true, + body, + }) .then((resp) => { if (resp.hits.total > 0) { const record = resp.hits.hits[0]._source; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js index a3b6cb39815a3..e9f3cb0d7d70d 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js @@ -63,9 +63,14 @@ export class JobsListView extends Component { this.showDeleteJobModal = () => {}; this.showStartDatafeedModal = () => {}; this.showCreateWatchFlyout = () => {}; + // work around to keep track of whether the component is mounted + // used to block timeouts for results polling + // which can run after unmounting + this._isMounted = false; } componentDidMount() { + this._isMounted = true; this.refreshJobSummaryList(true); if (this.props.isManagementTable !== true) { @@ -87,6 +92,7 @@ export class JobsListView extends Component { if (this.props.isManagementTable === undefined) { deletingJobsRefreshTimeout = null; } + this._isMounted = false; } openAutoStartDatafeedModal() { @@ -232,7 +238,7 @@ export class JobsListView extends Component { }; async refreshJobSummaryList(forceRefresh = false) { - if (forceRefresh === true || this.props.blockRefresh !== true) { + if (this._isMounted && (forceRefresh === true || this.props.blockRefresh !== true)) { // Set loading to true for jobs_list table for initial job loading if (this.state.loading === null) { this.setState({ loading: true }); @@ -283,6 +289,10 @@ export class JobsListView extends Component { } async checkDeletingJobTasks(forceRefresh = false) { + if (this._isMounted === false) { + return; + } + const { jobIds: taskJobIds } = await ml.jobs.deletingJobTasks(); const taskListHasChanged = diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/searches.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/searches.ts index 724a6146854af..51c396518c851 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/searches.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/searches.ts @@ -6,7 +6,6 @@ import { get } from 'lodash'; -import { ML_RESULTS_INDEX_PATTERN } from '../../../../../../common/constants/index_patterns'; import { escapeForElasticsearchQuery } from '../../../../util/string_utils'; import { ml } from '../../../../services/ml_api_service'; @@ -53,69 +52,70 @@ export function getScoresByRecord( jobIdFilterStr += `"${String(firstSplitField.value).replace(/\\/g, '\\\\')}"`; } - ml.esSearch({ - index: ML_RESULTS_INDEX_PATTERN, - size: 0, - body: { - query: { - bool: { - filter: [ - { - query_string: { - query: 'result_type:record', + ml.results + .anomalySearch({ + size: 0, + body: { + query: { + bool: { + filter: [ + { + query_string: { + query: 'result_type:record', + }, }, - }, - { - bool: { - must: [ - { - range: { - timestamp: { - gte: earliestMs, - lte: latestMs, - format: 'epoch_millis', + { + bool: { + must: [ + { + range: { + timestamp: { + gte: earliestMs, + lte: latestMs, + format: 'epoch_millis', + }, }, }, - }, - { - query_string: { - query: jobIdFilterStr, + { + query_string: { + query: jobIdFilterStr, + }, }, - }, - ], + ], + }, }, - }, - ], - }, - }, - aggs: { - detector_index: { - terms: { - field: 'detector_index', - order: { - recordScore: 'desc', - }, + ], }, - aggs: { - recordScore: { - max: { - field: 'record_score', + }, + aggs: { + detector_index: { + terms: { + field: 'detector_index', + order: { + recordScore: 'desc', }, }, - byTime: { - date_histogram: { - field: 'timestamp', - interval, - min_doc_count: 1, - extended_bounds: { - min: earliestMs, - max: latestMs, + aggs: { + recordScore: { + max: { + field: 'record_score', }, }, - aggs: { - recordScore: { - max: { - field: 'record_score', + byTime: { + date_histogram: { + field: 'timestamp', + interval, + min_doc_count: 1, + extended_bounds: { + min: earliestMs, + max: latestMs, + }, + }, + aggs: { + recordScore: { + max: { + field: 'record_score', + }, }, }, }, @@ -123,8 +123,7 @@ export function getScoresByRecord( }, }, }, - }, - }) + }) .then((resp: any) => { const detectorsByIndex = get(resp, ['aggregations', 'detector_index', 'buckets'], []); detectorsByIndex.forEach((dtr: any) => { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_settings_form.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_settings_form.tsx index 63dec536ea487..e31c6bc7b59e0 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_settings_form.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_settings_form.tsx @@ -258,7 +258,7 @@ export const JobSettingsForm: FC = ({ fill type="submit" isLoading={saveState === SAVE_STATE.SAVING} - disabled={!validationResult.formValid} + disabled={!validationResult.formValid || saveState === SAVE_STATE.SAVING} onClick={() => { onSubmit(formState); }} @@ -266,19 +266,11 @@ export const JobSettingsForm: FC = ({ defaultMessage: 'Create job', })} > - {saveState === SAVE_STATE.NOT_SAVED && ( - - )} - {saveState === SAVE_STATE.SAVING && ( - - )} + diff --git a/x-pack/plugins/ml/public/application/services/forecast_service.js b/x-pack/plugins/ml/public/application/services/forecast_service.js index c3d593c3347df..ed5a29ff74a63 100644 --- a/x-pack/plugins/ml/public/application/services/forecast_service.js +++ b/x-pack/plugins/ml/public/application/services/forecast_service.js @@ -9,7 +9,6 @@ import _ from 'lodash'; import { map } from 'rxjs/operators'; -import { ML_RESULTS_INDEX_PATTERN } from '../../../common/constants/index_patterns'; import { ml } from './ml_api_service'; // Gets a basic summary of the most recently run forecasts for the specified @@ -48,19 +47,19 @@ function getForecastsSummary(job, query, earliestMs, maxResults) { filterCriteria.push(query); } - ml.esSearch({ - index: ML_RESULTS_INDEX_PATTERN, - size: maxResults, - rest_total_hits_as_int: true, - body: { - query: { - bool: { - filter: filterCriteria, + ml.results + .anomalySearch({ + size: maxResults, + rest_total_hits_as_int: true, + body: { + query: { + bool: { + filter: filterCriteria, + }, }, + sort: [{ forecast_create_timestamp: { order: 'desc' } }], }, - sort: [{ forecast_create_timestamp: { order: 'desc' } }], - }, - }) + }) .then((resp) => { if (resp.hits.total !== 0) { obj.forecasts = resp.hits.hits.map((hit) => hit._source); @@ -106,29 +105,29 @@ function getForecastDateRange(job, forecastId) { // TODO - add in criteria for detector index and entity fields (by, over, partition) // once forecasting with these parameters is supported. - ml.esSearch({ - index: ML_RESULTS_INDEX_PATTERN, - size: 0, - body: { - query: { - bool: { - filter: filterCriteria, - }, - }, - aggs: { - earliest: { - min: { - field: 'timestamp', + ml.results + .anomalySearch({ + size: 0, + body: { + query: { + bool: { + filter: filterCriteria, }, }, - latest: { - max: { - field: 'timestamp', + aggs: { + earliest: { + min: { + field: 'timestamp', + }, + }, + latest: { + max: { + field: 'timestamp', + }, }, }, }, - }, - }) + }) .then((resp) => { obj.earliest = _.get(resp, 'aggregations.earliest.value', null); obj.latest = _.get(resp, 'aggregations.latest.value', null); @@ -243,9 +242,8 @@ function getForecastData( min: aggType.min, }; - return ml - .esSearch$({ - index: ML_RESULTS_INDEX_PATTERN, + return ml.results + .anomalySearch$({ size: 0, body: { query: { @@ -343,18 +341,18 @@ function getForecastRequestStats(job, forecastId) { }, ]; - ml.esSearch({ - index: ML_RESULTS_INDEX_PATTERN, - size: 1, - rest_total_hits_as_int: true, - body: { - query: { - bool: { - filter: filterCriteria, + ml.results + .anomalySearch({ + size: 1, + rest_total_hits_as_int: true, + body: { + query: { + bool: { + filter: filterCriteria, + }, }, }, - }, - }) + }) .then((resp) => { if (resp.hits.total !== 0) { obj.stats = _.first(resp.hits.hits)._source; diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/results.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/results.ts index 521fd306847eb..08c3853ace6f8 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/results.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/results.ts @@ -96,4 +96,22 @@ export const resultsApiProvider = (httpService: HttpService) => ({ body, }); }, + + anomalySearch(obj: any) { + const body = JSON.stringify(obj); + return httpService.http({ + path: `${basePath()}/results/anomaly_search`, + method: 'POST', + body, + }); + }, + + anomalySearch$(obj: any) { + const body = JSON.stringify(obj); + return httpService.http$({ + path: `${basePath()}/results/anomaly_search`, + method: 'POST', + body, + }); + }, }); diff --git a/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts b/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts index 1bcbd8dbcdd63..d7f016b419377 100644 --- a/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts +++ b/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts @@ -262,8 +262,8 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { }, ]; - return mlApiServices - .esSearch$({ + return mlApiServices.results + .anomalySearch$({ index: ML_RESULTS_INDEX_PATTERN, size: 0, body: { @@ -399,8 +399,8 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { }); }); - return mlApiServices - .esSearch$({ + return mlApiServices.results + .anomalySearch$({ index: ML_RESULTS_INDEX_PATTERN, rest_total_hits_as_int: true, size: maxResults !== undefined ? maxResults : 100, @@ -484,8 +484,8 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { }); } - return mlApiServices - .esSearch$({ + return mlApiServices.results + .anomalySearch$({ index: ML_RESULTS_INDEX_PATTERN, size: 0, body: { diff --git a/x-pack/plugins/ml/public/application/services/results_service/results_service.js b/x-pack/plugins/ml/public/application/services/results_service/results_service.js index 55ddb1de3529e..50e2d0a5a2a0b 100644 --- a/x-pack/plugins/ml/public/application/services/results_service/results_service.js +++ b/x-pack/plugins/ml/public/application/services/results_service/results_service.js @@ -8,7 +8,6 @@ import _ from 'lodash'; import { ML_MEDIAN_PERCENTS } from '../../../../common/util/job_utils'; import { escapeForElasticsearchQuery } from '../../util/string_utils'; -import { ML_RESULTS_INDEX_PATTERN } from '../../../../common/constants/index_patterns'; import { ANOMALY_SWIM_LANE_HARD_LIMIT, SWIM_LANE_DEFAULT_PAGE_SIZE, @@ -66,9 +65,8 @@ export function resultsServiceProvider(mlApiServices) { }); } - mlApiServices - .esSearch({ - index: ML_RESULTS_INDEX_PATTERN, + mlApiServices.results + .anomalySearch({ size: 0, body: { query: { @@ -238,9 +236,8 @@ export function resultsServiceProvider(mlApiServices) { }); } - mlApiServices - .esSearch({ - index: ML_RESULTS_INDEX_PATTERN, + mlApiServices.results + .anomalySearch({ size: 0, body: { query: { @@ -378,9 +375,8 @@ export function resultsServiceProvider(mlApiServices) { }); } - mlApiServices - .esSearch({ - index: ML_RESULTS_INDEX_PATTERN, + mlApiServices.results + .anomalySearch({ size: 0, body: { query: { @@ -560,9 +556,8 @@ export function resultsServiceProvider(mlApiServices) { }); } - mlApiServices - .esSearch({ - index: ML_RESULTS_INDEX_PATTERN, + mlApiServices.results + .anomalySearch({ size: 0, body: { query: { @@ -721,9 +716,8 @@ export function resultsServiceProvider(mlApiServices) { }); } - mlApiServices - .esSearch({ - index: ML_RESULTS_INDEX_PATTERN, + mlApiServices.results + .anomalySearch({ size: maxResults !== undefined ? maxResults : 100, rest_total_hits_as_int: true, body: { @@ -854,9 +848,8 @@ export function resultsServiceProvider(mlApiServices) { }); } - mlApiServices - .esSearch({ - index: ML_RESULTS_INDEX_PATTERN, + mlApiServices.results + .anomalySearch({ size: maxResults !== undefined ? maxResults : 100, rest_total_hits_as_int: true, body: { @@ -980,9 +973,8 @@ export function resultsServiceProvider(mlApiServices) { } } - mlApiServices - .esSearch({ - index: ML_RESULTS_INDEX_PATTERN, + mlApiServices.results + .anomalySearch({ size: maxResults !== undefined ? maxResults : 100, rest_total_hits_as_int: true, body: { @@ -1307,9 +1299,8 @@ export function resultsServiceProvider(mlApiServices) { }); }); - mlApiServices - .esSearch({ - index: ML_RESULTS_INDEX_PATTERN, + mlApiServices.results + .anomalySearch({ size: 0, body: { query: { diff --git a/x-pack/plugins/ml/server/lib/check_annotations/index.ts b/x-pack/plugins/ml/server/lib/check_annotations/index.ts index fb37917c512cb..de19f0ead6791 100644 --- a/x-pack/plugins/ml/server/lib/check_annotations/index.ts +++ b/x-pack/plugins/ml/server/lib/check_annotations/index.ts @@ -18,17 +18,17 @@ import { // - ML_ANNOTATIONS_INDEX_ALIAS_READ alias is present // - ML_ANNOTATIONS_INDEX_ALIAS_WRITE alias is present export async function isAnnotationsFeatureAvailable({ - callAsCurrentUser, + callAsInternalUser, }: ILegacyScopedClusterClient) { try { const indexParams = { index: ML_ANNOTATIONS_INDEX_PATTERN }; - const annotationsIndexExists = await callAsCurrentUser('indices.exists', indexParams); + const annotationsIndexExists = await callAsInternalUser('indices.exists', indexParams); if (!annotationsIndexExists) { return false; } - const annotationsReadAliasExists = await callAsCurrentUser('indices.existsAlias', { + const annotationsReadAliasExists = await callAsInternalUser('indices.existsAlias', { index: ML_ANNOTATIONS_INDEX_ALIAS_READ, name: ML_ANNOTATIONS_INDEX_ALIAS_READ, }); @@ -37,7 +37,7 @@ export async function isAnnotationsFeatureAvailable({ return false; } - const annotationsWriteAliasExists = await callAsCurrentUser('indices.existsAlias', { + const annotationsWriteAliasExists = await callAsInternalUser('indices.existsAlias', { index: ML_ANNOTATIONS_INDEX_ALIAS_WRITE, name: ML_ANNOTATIONS_INDEX_ALIAS_WRITE, }); diff --git a/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts b/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts index 3bf9bd0232a5d..5be443266ffe1 100644 --- a/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts +++ b/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts @@ -52,8 +52,8 @@ describe('annotation_service', () => { const response = await deleteAnnotation(annotationMockId); - expect(mockFunct.callAsCurrentUser.mock.calls[0][0]).toBe('delete'); - expect(mockFunct.callAsCurrentUser.mock.calls[0][1]).toEqual(deleteParamsMock); + expect(mockFunct.callAsInternalUser.mock.calls[0][0]).toBe('delete'); + expect(mockFunct.callAsInternalUser.mock.calls[0][1]).toEqual(deleteParamsMock); expect(response).toBe(acknowledgedResponseMock); done(); }); @@ -73,8 +73,8 @@ describe('annotation_service', () => { const response: GetResponse = await getAnnotations(indexAnnotationArgsMock); - expect(mockFunct.callAsCurrentUser.mock.calls[0][0]).toBe('search'); - expect(mockFunct.callAsCurrentUser.mock.calls[0][1]).toEqual(getAnnotationsRequestMock); + expect(mockFunct.callAsInternalUser.mock.calls[0][0]).toBe('search'); + expect(mockFunct.callAsInternalUser.mock.calls[0][1]).toEqual(getAnnotationsRequestMock); expect(Object.keys(response.annotations)).toHaveLength(1); expect(response.annotations[jobIdMock]).toHaveLength(2); expect(isAnnotations(response.annotations[jobIdMock])).toBeTruthy(); @@ -89,7 +89,7 @@ describe('annotation_service', () => { }; const mlClusterClientSpyError: any = { - callAsCurrentUser: jest.fn(() => { + callAsInternalUser: jest.fn(() => { return Promise.resolve(mockEsError); }), }; @@ -124,10 +124,10 @@ describe('annotation_service', () => { const response = await indexAnnotation(annotationMock, usernameMock); - expect(mockFunct.callAsCurrentUser.mock.calls[0][0]).toBe('index'); + expect(mockFunct.callAsInternalUser.mock.calls[0][0]).toBe('index'); // test if the annotation has been correctly augmented - const indexParamsCheck = mockFunct.callAsCurrentUser.mock.calls[0][1]; + const indexParamsCheck = mockFunct.callAsInternalUser.mock.calls[0][1]; const annotation = indexParamsCheck.body; expect(annotation.create_username).toBe(usernameMock); expect(annotation.modified_username).toBe(usernameMock); @@ -154,10 +154,10 @@ describe('annotation_service', () => { const response = await indexAnnotation(annotationMock, usernameMock); - expect(mockFunct.callAsCurrentUser.mock.calls[0][0]).toBe('index'); + expect(mockFunct.callAsInternalUser.mock.calls[0][0]).toBe('index'); // test if the annotation has been correctly augmented - const indexParamsCheck = mockFunct.callAsCurrentUser.mock.calls[0][1]; + const indexParamsCheck = mockFunct.callAsInternalUser.mock.calls[0][1]; const annotation = indexParamsCheck.body; expect(annotation.create_username).toBe(usernameMock); expect(annotation.modified_username).toBe(usernameMock); @@ -196,9 +196,9 @@ describe('annotation_service', () => { await indexAnnotation(annotation, modifiedUsernameMock); - expect(mockFunct.callAsCurrentUser.mock.calls[1][0]).toBe('index'); + expect(mockFunct.callAsInternalUser.mock.calls[1][0]).toBe('index'); // test if the annotation has been correctly updated - const indexParamsCheck = mockFunct.callAsCurrentUser.mock.calls[1][1]; + const indexParamsCheck = mockFunct.callAsInternalUser.mock.calls[1][1]; const modifiedAnnotation = indexParamsCheck.body; expect(modifiedAnnotation.annotation).toBe(modifiedAnnotationText); expect(modifiedAnnotation.create_username).toBe(originalUsernameMock); diff --git a/x-pack/plugins/ml/server/models/annotation_service/annotation.ts b/x-pack/plugins/ml/server/models/annotation_service/annotation.ts index f7353034b7453..8094689abf3e5 100644 --- a/x-pack/plugins/ml/server/models/annotation_service/annotation.ts +++ b/x-pack/plugins/ml/server/models/annotation_service/annotation.ts @@ -76,7 +76,7 @@ export interface DeleteParams { id: string; } -export function annotationProvider({ callAsCurrentUser }: ILegacyScopedClusterClient) { +export function annotationProvider({ callAsInternalUser }: ILegacyScopedClusterClient) { async function indexAnnotation(annotation: Annotation, username: string) { if (isAnnotation(annotation) === false) { // No need to translate, this will not be exposed in the UI. @@ -103,7 +103,7 @@ export function annotationProvider({ callAsCurrentUser }: ILegacyScopedClusterCl delete params.body.key; } - return await callAsCurrentUser('index', params); + return await callAsInternalUser('index', params); } async function getAnnotations({ @@ -286,7 +286,7 @@ export function annotationProvider({ callAsCurrentUser }: ILegacyScopedClusterCl }; try { - const resp = await callAsCurrentUser('search', params); + const resp = await callAsInternalUser('search', params); if (resp.error !== undefined && resp.message !== undefined) { // No need to translate, this will not be exposed in the UI. @@ -335,7 +335,7 @@ export function annotationProvider({ callAsCurrentUser }: ILegacyScopedClusterCl refresh: 'wait_for', }; - return await callAsCurrentUser('delete', param); + return await callAsInternalUser('delete', param); } return { diff --git a/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_audit_messages.ts b/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_audit_messages.ts index c8471b5462205..1cb0656e88a0b 100644 --- a/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_audit_messages.ts +++ b/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_audit_messages.ts @@ -23,7 +23,7 @@ interface BoolQuery { bool: { [key: string]: any }; } -export function analyticsAuditMessagesProvider({ callAsCurrentUser }: ILegacyScopedClusterClient) { +export function analyticsAuditMessagesProvider({ callAsInternalUser }: ILegacyScopedClusterClient) { // search for audit messages, // analyticsId is optional. without it, all analytics will be listed. async function getAnalyticsAuditMessages(analyticsId: string) { @@ -69,7 +69,7 @@ export function analyticsAuditMessagesProvider({ callAsCurrentUser }: ILegacySco } try { - const resp = await callAsCurrentUser('search', { + const resp = await callAsInternalUser('search', { index: ML_NOTIFICATION_INDEX_PATTERN, ignore_unavailable: true, rest_total_hits_as_int: true, diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/low_request_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/low_request_rate_ecs.json index d6d3879e8300f..5950d088d49e2 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/low_request_rate_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/low_request_rate_ecs.json @@ -1,7 +1,7 @@ { "groups": ["apache"], "description": "HTTP Access Logs: Detect low request rates (ECS)", - "analysis_config" : { + "analysis_config": { "bucket_span": "15m", "summary_count_field_name": "doc_count", "detectors": [ @@ -27,7 +27,7 @@ "custom_urls": [ { "url_name": "Raw data", - "url_value": "discover#/ml_http_access_filebeat_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027apache.access\u0027),type:phrase,value:\u0027apache.access\u0027),query:(match:(event.dataset:(query:\u0027apache.access\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027apache.access\u0027),type:phrase,value:\u0027apache.access\u0027),query:(match:(event.dataset:(query:\u0027apache.access\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_request_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_request_rate_ecs.json index 876b89b03952f..f888e4d44c844 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_request_rate_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_request_rate_ecs.json @@ -1,18 +1,16 @@ { "groups": ["apache"], "description": "HTTP Access Logs: Detect unusual source IPs - high request rates (ECS)", - "analysis_config" : { + "analysis_config": { "bucket_span": "1h", "detectors": [ - { + { "detector_description": "Apache access source IP high count", "function": "high_count", "over_field_name": "source.address" } ], - "influencers": [ - "source.address" - ] + "influencers": ["source.address"] }, "data_description": { "time_field": "@timestamp", @@ -27,7 +25,7 @@ }, { "url_name": "Raw data", - "url_value": "discover#/ml_http_access_filebeat_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027apache.access\u0027),type:phrase,value:\u0027apache.access\u0027),query:(match:(event.dataset:(query:\u0027apache.access\u0027,type:phrase)))),(\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:source.address,negate:!f,params:(query:\u0027$source.address$\u0027),type:phrase,value:\u0027$source.address$\u0027),query:(match:(source.address:(query:\u0027$source.address$\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027apache.access\u0027),type:phrase,value:\u0027apache.access\u0027),query:(match:(event.dataset:(query:\u0027apache.access\u0027,type:phrase)))),(\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:source.address,negate:!f,params:(query:\u0027$source.address$\u0027),type:phrase,value:\u0027$source.address$\u0027),query:(match:(source.address:(query:\u0027$source.address$\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_url_count_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_url_count_ecs.json index 810c61073ecc6..e4886b531ba42 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_url_count_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_url_count_ecs.json @@ -1,19 +1,17 @@ { "groups": ["apache"], "description": "HTTP Access Logs: Detect unusual source IPs - high distinct count of URLs (ECS)", - "analysis_config" : { + "analysis_config": { "bucket_span": "1h", "detectors": [ - { + { "detector_description": "Apache access source IP high dc URL", "function": "high_distinct_count", "field_name": "url.original", "over_field_name": "source.address" } ], - "influencers": [ - "source.address" - ] + "influencers": ["source.address"] }, "data_description": { "time_field": "@timestamp", @@ -28,7 +26,7 @@ }, { "url_name": "Raw data", - "url_value": "discover#/ml_http_access_filebeat_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027apache.access\u0027),type:phrase,value:\u0027apache.access\u0027),query:(match:(event.dataset:(query:\u0027apache.access\u0027,type:phrase)))),(\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:source.address,negate:!f,params:(query:\u0027$source.address$\u0027),type:phrase,value:\u0027$source.address$\u0027),query:(match:(source.address:(query:\u0027$source.address$\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027apache.access\u0027),type:phrase,value:\u0027apache.access\u0027),query:(match:(event.dataset:(query:\u0027apache.access\u0027,type:phrase)))),(\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:source.address,negate:!f,params:(query:\u0027$source.address$\u0027),type:phrase,value:\u0027$source.address$\u0027),query:(match:(source.address:(query:\u0027$source.address$\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/status_code_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/status_code_rate_ecs.json index a9341e43723a6..ac5bd5e478c16 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/status_code_rate_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/status_code_rate_ecs.json @@ -1,19 +1,16 @@ { "groups": ["apache"], "description": "HTTP Access Logs: Detect unusual status code rates (ECS)", - "analysis_config" : { + "analysis_config": { "bucket_span": "15m", "detectors": [ - { + { "detector_description": "Apache access status code rate", "function": "count", "partition_field_name": "http.response.status_code" } ], - "influencers": [ - "http.response.status_code", - "source.address" - ] + "influencers": ["http.response.status_code", "source.address"] }, "analysis_limits": { "model_memory_limit": "100mb" @@ -34,7 +31,7 @@ }, { "url_name": "Raw data", - "url_value": "discover#/ml_http_access_filebeat_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027apache.access\u0027),type:phrase,value:\u0027apache.access\u0027),query:(match:(event.dataset:(query:\u0027apache.access\u0027,type:phrase)))),(\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:http.response.status_code,negate:!f,params:(query:\u0027$http.response.status_code$\u0027),type:phrase,value:\u0027$http.response.status_code$\u0027),query:(match:(http.response.status_code:(query:\u0027$http.response.status_code$\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027apache.access\u0027),type:phrase,value:\u0027apache.access\u0027),query:(match:(event.dataset:(query:\u0027apache.access\u0027,type:phrase)))),(\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:http.response.status_code,negate:!f,params:(query:\u0027$http.response.status_code$\u0027),type:phrase,value:\u0027$http.response.status_code$\u0027),query:(match:(http.response.status_code:(query:\u0027$http.response.status_code$\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/visitor_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/visitor_rate_ecs.json index 5bc641315bc3f..f513e53a964f3 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/visitor_rate_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/visitor_rate_ecs.json @@ -1,7 +1,7 @@ { "groups": ["apache"], "description": "HTTP Access Logs: Detect unusual visitor rates (ECS)", - "analysis_config" : { + "analysis_config": { "bucket_span": "15m", "summary_count_field_name": "dc_source_address", "detectors": [ @@ -27,7 +27,7 @@ "custom_urls": [ { "url_name": "Raw data", - "url_value": "discover#/ml_http_access_filebeat_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027apache.access\u0027),type:phrase,value:\u0027apache.access\u0027),query:(match:(event.dataset:(query:\u0027apache.access\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027apache.access\u0027),type:phrase,value:\u0027apache.access\u0027),query:(match:(event.dataset:(query:\u0027apache.access\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_high_count_process_events_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_high_count_process_events_ecs.json index 27949c76b3e13..046736b6f5559 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_high_count_process_events_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_high_count_process_events_ecs.json @@ -11,10 +11,7 @@ "partition_field_name": "container.name" } ], - "influencers": [ - "container.name", - "process.executable" - ] + "influencers": ["container.name", "process.executable"] }, "analysis_limits": { "model_memory_limit": "256mb", @@ -35,7 +32,7 @@ { "url_name": "Raw data", "time_range": "1h", - "url_value": "discover#/ml_auditbeat_docker_process_events_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(index:\u0027INDEX_PATTERN_ID\u0027,query:(language:kuery,query:\u0027container.name:\u0022$container.name$\u0022\u0027))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(index:\u0027INDEX_PATTERN_ID\u0027,query:(language:kuery,query:\u0027container.name:\u0022$container.name$\u0022\u0027))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_rare_process_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_rare_process_activity_ecs.json index 899518f30f7a3..ab405d47484d9 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_rare_process_activity_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_rare_process_activity_ecs.json @@ -12,10 +12,7 @@ "partition_field_name": "container.name" } ], - "influencers": [ - "container.name", - "process.executable" - ] + "influencers": ["container.name", "process.executable"] }, "analysis_limits": { "model_memory_limit": "256mb" @@ -35,7 +32,7 @@ { "url_name": "Raw data", "time_range": "1h", - "url_value": "discover#/ml_auditbeat_docker_process_events_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(index:\u0027INDEX_PATTERN_ID\u0027,query:(language:kuery,query:\u0027container.name:\u0022$container.name$\u0022 AND process.executable:\u0022$process.executable$\u0022\u0027))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(index:\u0027INDEX_PATTERN_ID\u0027,query:(language:kuery,query:\u0027container.name:\u0022$container.name$\u0022 AND process.executable:\u0022$process.executable$\u0022\u0027))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_high_count_process_events_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_high_count_process_events_ecs.json index 1664e19096ee3..192842309dd92 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_high_count_process_events_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_high_count_process_events_ecs.json @@ -11,10 +11,7 @@ "partition_field_name": "host.name" } ], - "influencers": [ - "host.name", - "process.executable" - ] + "influencers": ["host.name", "process.executable"] }, "analysis_limits": { "model_memory_limit": "256mb" @@ -34,7 +31,7 @@ { "url_name": "Raw data", "time_range": "1h", - "url_value": "discover#/ml_auditbeat_hosts_process_events_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(index:\u0027INDEX_PATTERN_ID\u0027,query:(language:kuery,query:\u0027host.name:\u0022$host.name$\u0022\u0027))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(index:\u0027INDEX_PATTERN_ID\u0027,query:(language:kuery,query:\u0027host.name:\u0022$host.name$\u0022\u0027))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_rare_process_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_rare_process_activity_ecs.json index d83f36db5a491..9448537b387c2 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_rare_process_activity_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_rare_process_activity_ecs.json @@ -12,10 +12,7 @@ "partition_field_name": "host.name" } ], - "influencers": [ - "host.name", - "process.executable" - ] + "influencers": ["host.name", "process.executable"] }, "analysis_limits": { "model_memory_limit": "256mb" @@ -35,7 +32,7 @@ { "url_name": "Raw data", "time_range": "1h", - "url_value": "discover#/ml_auditbeat_hosts_process_events_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(index:\u0027INDEX_PATTERN_ID\u0027,query:(language:kuery,query:\u0027host.name:\u0022$host.name$\u0022 AND process.executable:\u0022$process.executable$\u0022\u0027))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(index:\u0027INDEX_PATTERN_ID\u0027,query:(language:kuery,query:\u0027host.name:\u0022$host.name$\u0022 AND process.executable:\u0022$process.executable$\u0022\u0027))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/low_request_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/low_request_rate_ecs.json index 54c2f540e334f..3dfe04766a9e9 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/low_request_rate_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/low_request_rate_ecs.json @@ -1,7 +1,7 @@ { "groups": ["nginx"], "description": "HTTP Access Logs: Detect low request rates (ECS)", - "analysis_config" : { + "analysis_config": { "bucket_span": "15m", "summary_count_field_name": "doc_count", "detectors": [ @@ -27,7 +27,7 @@ "custom_urls": [ { "url_name": "Raw data", - "url_value": "discover#/ml_http_access_filebeat_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027nginx.access\u0027),type:phrase,value:\u0027nginx.access\u0027),query:(match:(event.dataset:(query:\u0027nginx.access\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027nginx.access\u0027),type:phrase,value:\u0027nginx.access\u0027),query:(match:(event.dataset:(query:\u0027nginx.access\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_request_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_request_rate_ecs.json index 6fc7ce7e0699d..209b4e66dbac4 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_request_rate_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_request_rate_ecs.json @@ -1,18 +1,16 @@ { "groups": ["nginx"], "description": "HTTP Access Logs: Detect unusual source IPs - high request rates (ECS)", - "analysis_config" : { + "analysis_config": { "bucket_span": "1h", "detectors": [ - { + { "detector_description": "Nginx access source IP high count", "function": "high_count", "over_field_name": "source.address" } ], - "influencers": [ - "source.address" - ] + "influencers": ["source.address"] }, "data_description": { "time_field": "@timestamp", @@ -27,7 +25,7 @@ }, { "url_name": "Raw data", - "url_value": "discover#/ml_http_access_filebeat_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027nginx.access\u0027),type:phrase,value:\u0027nginx.access\u0027),query:(match:(event.dataset:(query:\u0027nginx.access\u0027,type:phrase)))),(\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:source.address,negate:!f,params:(query:\u0027$source.address$\u0027),type:phrase,value:\u0027$source.address$\u0027),query:(match:(source.address:(query:\u0027$source.address$\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027nginx.access\u0027),type:phrase,value:\u0027nginx.access\u0027),query:(match:(event.dataset:(query:\u0027nginx.access\u0027,type:phrase)))),(\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:source.address,negate:!f,params:(query:\u0027$source.address$\u0027),type:phrase,value:\u0027$source.address$\u0027),query:(match:(source.address:(query:\u0027$source.address$\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_url_count_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_url_count_ecs.json index 1c3f9f96a36b4..dea65ef701cb1 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_url_count_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_url_count_ecs.json @@ -1,19 +1,17 @@ { "groups": ["nginx"], "description": "HTTP Access Logs: Detect unusual source IPs - high distinct count of URLs (ECS)", - "analysis_config" : { + "analysis_config": { "bucket_span": "1h", "detectors": [ - { + { "detector_description": "Nginx access source IP high dc URL", "function": "high_distinct_count", "field_name": "url.original", "over_field_name": "source.address" } ], - "influencers": [ - "source.address" - ] + "influencers": ["source.address"] }, "data_description": { "time_field": "@timestamp", @@ -28,7 +26,7 @@ }, { "url_name": "Raw data", - "url_value": "discover#/ml_http_access_filebeat_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027nginx.access\u0027),type:phrase,value:\u0027nginx.access\u0027),query:(match:(event.dataset:(query:\u0027nginx.access\u0027,type:phrase)))),(\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:source.address,negate:!f,params:(query:\u0027$source.address$\u0027),type:phrase,value:\u0027$source.address$\u0027),query:(match:(source.address:(query:\u0027$source.address$\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027nginx.access\u0027),type:phrase,value:\u0027nginx.access\u0027),query:(match:(event.dataset:(query:\u0027nginx.access\u0027,type:phrase)))),(\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:source.address,negate:!f,params:(query:\u0027$source.address$\u0027),type:phrase,value:\u0027$source.address$\u0027),query:(match:(source.address:(query:\u0027$source.address$\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/status_code_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/status_code_rate_ecs.json index df917ed43c5fa..2475b33aa24f2 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/status_code_rate_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/status_code_rate_ecs.json @@ -1,19 +1,16 @@ { "groups": ["nginx"], "description": "HTTP Access Logs: Detect unusual status code rates (ECS)", - "analysis_config" : { + "analysis_config": { "bucket_span": "15m", "detectors": [ - { + { "detector_description": "Nginx access status code rate", "function": "count", "partition_field_name": "http.response.status_code" } ], - "influencers": [ - "http.response.status_code", - "source.address" - ] + "influencers": ["http.response.status_code", "source.address"] }, "analysis_limits": { "model_memory_limit": "100mb" @@ -34,7 +31,7 @@ }, { "url_name": "Raw data", - "url_value": "discover#/ml_http_access_filebeat_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027nginx.access\u0027),type:phrase,value:\u0027nginx.access\u0027),query:(match:(event.dataset:(query:\u0027nginx.access\u0027,type:phrase)))),(\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:http.response.status_code,negate:!f,params:(query:\u0027$http.response.status_code$\u0027),type:phrase,value:\u0027$http.response.status_code$\u0027),query:(match:(http.response.status_code:(query:\u0027$http.response.status_code$\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027nginx.access\u0027),type:phrase,value:\u0027nginx.access\u0027),query:(match:(event.dataset:(query:\u0027nginx.access\u0027,type:phrase)))),(\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:http.response.status_code,negate:!f,params:(query:\u0027$http.response.status_code$\u0027),type:phrase,value:\u0027$http.response.status_code$\u0027),query:(match:(http.response.status_code:(query:\u0027$http.response.status_code$\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/visitor_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/visitor_rate_ecs.json index 5ff35a7e2aed7..3182ac3fd3a79 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/visitor_rate_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/visitor_rate_ecs.json @@ -1,7 +1,7 @@ { "groups": ["nginx"], "description": "HTTP Access Logs: Detect unusual visitor rates (ECS)", - "analysis_config" : { + "analysis_config": { "bucket_span": "15m", "summary_count_field_name": "dc_source_address", "detectors": [ @@ -27,7 +27,7 @@ "custom_urls": [ { "url_name": "Raw data", - "url_value": "discover#/ml_http_access_filebeat_ecs?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027nginx.access\u0027),type:phrase,value:\u0027nginx.access\u0027),query:(match:(event.dataset:(query:\u0027nginx.access\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" + "url_value": "discover#/?_g=(time:(from:\u0027$earliest$\u0027,mode:absolute,to:\u0027$latest$\u0027))&_a=(columns:!(_source),filters:!((\u0027$state\u0027:(store:appState),meta:(alias:!n,disabled:!f,index:\u0027INDEX_PATTERN_ID\u0027,key:event.dataset,negate:!f,params:(query:\u0027nginx.access\u0027),type:phrase,value:\u0027nginx.access\u0027),query:(match:(event.dataset:(query:\u0027nginx.access\u0027,type:phrase))))),index:\u0027INDEX_PATTERN_ID\u0027,interval:auto,query:(language:kuery,query:\u0027\u0027),sort:!(\u0027@timestamp\u0027,desc))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/logo.json index 40a5c59677147..dfd22f6b1140b 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/logo.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/logo.json @@ -1,3 +1,3 @@ { - "icon": "securityAnalyticsApp" + "icon": "logoSecurity" } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/logo.json index 6b02648ccf287..dfd22f6b1140b 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/logo.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/logo.json @@ -1,3 +1,3 @@ { - "icon": "securityAnalyticsApp" -} \ No newline at end of file + "icon": "logoSecurity" +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/logo.json index 6b02648ccf287..dfd22f6b1140b 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/logo.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/logo.json @@ -1,3 +1,3 @@ { - "icon": "securityAnalyticsApp" -} \ No newline at end of file + "icon": "logoSecurity" +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/logo.json index 40a5c59677147..dfd22f6b1140b 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/logo.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/logo.json @@ -1,3 +1,3 @@ { - "icon": "securityAnalyticsApp" + "icon": "logoSecurity" } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/logo.json index 6b02648ccf287..dfd22f6b1140b 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/logo.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/logo.json @@ -1,3 +1,3 @@ { - "icon": "securityAnalyticsApp" -} \ No newline at end of file + "icon": "logoSecurity" +} diff --git a/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js b/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js index dcbabd879b47a..86d80c394137f 100644 --- a/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js +++ b/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js @@ -34,7 +34,7 @@ const anomalyDetectorTypeFilter = { }, }; -export function jobAuditMessagesProvider({ callAsCurrentUser, callAsInternalUser }) { +export function jobAuditMessagesProvider({ callAsInternalUser }) { // search for audit messages, // jobId is optional. without it, all jobs will be listed. // from is optional and should be a string formatted in ES time units. e.g. 12h, 1d, 7d @@ -100,7 +100,7 @@ export function jobAuditMessagesProvider({ callAsCurrentUser, callAsInternalUser } try { - const resp = await callAsCurrentUser('search', { + const resp = await callAsInternalUser('search', { index: ML_NOTIFICATION_INDEX_PATTERN, ignore_unavailable: true, rest_total_hits_as_int: true, @@ -155,7 +155,7 @@ export function jobAuditMessagesProvider({ callAsCurrentUser, callAsInternalUser levelsPerJobAggSize = jobIds.length; } - const resp = await callAsCurrentUser('search', { + const resp = await callAsInternalUser('search', { index: ML_NOTIFICATION_INDEX_PATTERN, ignore_unavailable: true, rest_total_hits_as_int: true, diff --git a/x-pack/plugins/ml/server/models/job_service/jobs.ts b/x-pack/plugins/ml/server/models/job_service/jobs.ts index e9ed2d0941d96..0aa1cfdae13c7 100644 --- a/x-pack/plugins/ml/server/models/job_service/jobs.ts +++ b/x-pack/plugins/ml/server/models/job_service/jobs.ts @@ -48,7 +48,7 @@ interface Results { } export function jobsProvider(mlClusterClient: ILegacyScopedClusterClient) { - const { callAsCurrentUser, callAsInternalUser } = mlClusterClient; + const { callAsInternalUser } = mlClusterClient; const { forceDeleteDatafeed, getDatafeedIdsByJobId } = datafeedsProvider(mlClusterClient); const { getAuditMessagesSummary } = jobAuditMessagesProvider(mlClusterClient); @@ -400,7 +400,7 @@ export function jobsProvider(mlClusterClient: ILegacyScopedClusterClient) { const detailed = true; const jobIds = []; try { - const tasksList = await callAsCurrentUser('tasks.list', { actions, detailed }); + const tasksList = await callAsInternalUser('tasks.list', { actions, detailed }); Object.keys(tasksList.nodes).forEach((nodeId) => { const tasks = tasksList.nodes[nodeId].tasks; Object.keys(tasks).forEach((taskId) => { diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts index 4f97238a4a0b5..5ade86806f383 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts @@ -9,9 +9,9 @@ import { ILegacyScopedClusterClient } from 'kibana/server'; import { ML_RESULTS_INDEX_PATTERN } from '../../../../../common/constants/index_patterns'; import { CategoryId, Category } from '../../../../../common/types/categories'; -export function topCategoriesProvider({ callAsCurrentUser }: ILegacyScopedClusterClient) { +export function topCategoriesProvider({ callAsInternalUser }: ILegacyScopedClusterClient) { async function getTotalCategories(jobId: string): Promise<{ total: number }> { - const totalResp = await callAsCurrentUser('search', { + const totalResp = await callAsInternalUser('search', { index: ML_RESULTS_INDEX_PATTERN, size: 0, body: { @@ -37,7 +37,7 @@ export function topCategoriesProvider({ callAsCurrentUser }: ILegacyScopedCluste } async function getTopCategoryCounts(jobId: string, numberOfCategories: number) { - const top: SearchResponse = await callAsCurrentUser('search', { + const top: SearchResponse = await callAsInternalUser('search', { index: ML_RESULTS_INDEX_PATTERN, size: 0, body: { @@ -99,7 +99,7 @@ export function topCategoriesProvider({ callAsCurrentUser }: ILegacyScopedCluste field: 'category_id', }, }; - const result: SearchResponse = await callAsCurrentUser('search', { + const result: SearchResponse = await callAsInternalUser('search', { index: ML_RESULTS_INDEX_PATTERN, size, body: { diff --git a/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts b/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts index 663ee846571e7..9c0efe259844c 100644 --- a/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts +++ b/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts @@ -75,7 +75,6 @@ function getFieldObject(fieldType: PartitionFieldsType, aggs: any) { } export const getPartitionFieldsValuesFactory = ({ - callAsCurrentUser, callAsInternalUser, }: ILegacyScopedClusterClient) => /** @@ -102,7 +101,7 @@ export const getPartitionFieldsValuesFactory = ({ const isModelPlotEnabled = job?.model_plot_config?.enabled; - const resp = await callAsCurrentUser('search', { + const resp = await callAsInternalUser('search', { index: ML_RESULTS_INDEX_PATTERN, size: 0, body: { diff --git a/x-pack/plugins/ml/server/models/results_service/results_service.ts b/x-pack/plugins/ml/server/models/results_service/results_service.ts index 8e904143263d7..04997e517bba9 100644 --- a/x-pack/plugins/ml/server/models/results_service/results_service.ts +++ b/x-pack/plugins/ml/server/models/results_service/results_service.ts @@ -31,7 +31,7 @@ interface Influencer { } export function resultsServiceProvider(mlClusterClient: ILegacyScopedClusterClient) { - const { callAsCurrentUser } = mlClusterClient; + const { callAsInternalUser } = mlClusterClient; // Obtains data for the anomalies table, aggregating anomalies by day or hour as requested. // Return an Object with properties 'anomalies' and 'interval' (interval used to aggregate anomalies, // one of day, hour or second. Note 'auto' can be provided as the aggregationInterval in the request, @@ -134,7 +134,7 @@ export function resultsServiceProvider(mlClusterClient: ILegacyScopedClusterClie }); } - const resp: SearchResponse = await callAsCurrentUser('search', { + const resp: SearchResponse = await callAsInternalUser('search', { index: ML_RESULTS_INDEX_PATTERN, rest_total_hits_as_int: true, size: maxRecords, @@ -288,7 +288,7 @@ export function resultsServiceProvider(mlClusterClient: ILegacyScopedClusterClie }, }; - const resp = await callAsCurrentUser('search', query); + const resp = await callAsInternalUser('search', query); const maxScore = _.get(resp, ['aggregations', 'max_score', 'value'], null); return { maxScore }; @@ -326,7 +326,7 @@ export function resultsServiceProvider(mlClusterClient: ILegacyScopedClusterClie // Size of job terms agg, consistent with maximum number of jobs supported by Java endpoints. const maxJobs = 10000; - const resp = await callAsCurrentUser('search', { + const resp = await callAsInternalUser('search', { index: ML_RESULTS_INDEX_PATTERN, size: 0, body: { @@ -370,7 +370,7 @@ export function resultsServiceProvider(mlClusterClient: ILegacyScopedClusterClie // from the given index and job ID. // Returned response consists of a list of examples against category ID. async function getCategoryExamples(jobId: string, categoryIds: any, maxExamples: number) { - const resp = await callAsCurrentUser('search', { + const resp = await callAsInternalUser('search', { index: ML_RESULTS_INDEX_PATTERN, rest_total_hits_as_int: true, size: ANOMALIES_TABLE_DEFAULT_QUERY_SIZE, // Matches size of records in anomaly summary table. @@ -405,7 +405,7 @@ export function resultsServiceProvider(mlClusterClient: ILegacyScopedClusterClie // Returned response contains four properties - categoryId, regex, examples // and terms (space delimited String of the common tokens matched in values of the category). async function getCategoryDefinition(jobId: string, categoryId: string) { - const resp = await callAsCurrentUser('search', { + const resp = await callAsInternalUser('search', { index: ML_RESULTS_INDEX_PATTERN, rest_total_hits_as_int: true, size: 1, diff --git a/x-pack/plugins/ml/server/plugin.ts b/x-pack/plugins/ml/server/plugin.ts index 812db744d1bda..3c3824a785032 100644 --- a/x-pack/plugins/ml/server/plugin.ts +++ b/x-pack/plugins/ml/server/plugin.ts @@ -75,7 +75,7 @@ export class MlServerPlugin implements Plugin { try { const { analyticsId } = request.params; - const results = await context.ml!.mlClient.callAsCurrentUser( + const results = await context.ml!.mlClient.callAsInternalUser( 'ml.updateDataFrameAnalytics', { body: request.body, diff --git a/x-pack/plugins/ml/server/routes/results_service.ts b/x-pack/plugins/ml/server/routes/results_service.ts index c7fcebd2a29a5..c9370362816fa 100644 --- a/x-pack/plugins/ml/server/routes/results_service.ts +++ b/x-pack/plugins/ml/server/routes/results_service.ts @@ -5,6 +5,7 @@ */ import { RequestHandlerContext } from 'kibana/server'; +import { schema } from '@kbn/config-schema'; import { wrapError } from '../client/error_wrapper'; import { RouteInitialization } from '../types'; import { @@ -15,6 +16,7 @@ import { partitionFieldValuesSchema, } from './schemas/results_service_schema'; import { resultsServiceProvider } from '../models/results_service'; +import { ML_RESULTS_INDEX_PATTERN } from '../../common/constants/index_patterns'; function getAnomaliesTableData(context: RequestHandlerContext, payload: any) { const rs = resultsServiceProvider(context.ml!.mlClient); @@ -232,4 +234,35 @@ export function resultsServiceRoutes({ router, mlLicense }: RouteInitialization) } }) ); + + /** + * @apiGroup ResultsService + * + * @api {post} /api/ml/results/anomaly_search Performs a search on the anomaly results index + * @apiName AnomalySearch + */ + router.post( + { + path: '/api/ml/results/anomaly_search', + validate: { + body: schema.maybe(schema.any()), + }, + options: { + tags: ['access:ml:canGetJobs'], + }, + }, + mlLicense.fullLicenseAPIGuard(async (context, request, response) => { + const body = { + ...request.body, + index: ML_RESULTS_INDEX_PATTERN, + }; + try { + return response.ok({ + body: await context.ml!.mlClient.callAsInternalUser('search', body), + }); + } catch (error) { + return response.customError(wrapError(error)); + } + }) + ); } diff --git a/x-pack/plugins/ml/server/shared_services/providers/system.ts b/x-pack/plugins/ml/server/shared_services/providers/system.ts index ec2662014546e..d292abc438a2f 100644 --- a/x-pack/plugins/ml/server/shared_services/providers/system.ts +++ b/x-pack/plugins/ml/server/shared_services/providers/system.ts @@ -37,7 +37,7 @@ export function getMlSystemProvider( return { mlSystemProvider(mlClusterClient: ILegacyScopedClusterClient, request: KibanaRequest) { // const hasMlCapabilities = getHasMlCapabilities(request); - const { callAsCurrentUser, callAsInternalUser } = mlClusterClient; + const { callAsInternalUser } = mlClusterClient; return { async mlCapabilities() { isMinimumLicense(); @@ -77,7 +77,7 @@ export function getMlSystemProvider( // integration and currently alerting does not supply a request object. // await hasMlCapabilities(['canAccessML']); - return callAsCurrentUser('search', { + return callAsInternalUser('search', { ...searchParams, index: ML_RESULTS_INDEX_PATTERN, }); diff --git a/x-pack/plugins/monitoring/public/alerts/badge.tsx b/x-pack/plugins/monitoring/public/alerts/badge.tsx index 4518d2c56cabb..02963e9457ab5 100644 --- a/x-pack/plugins/monitoring/public/alerts/badge.tsx +++ b/x-pack/plugins/monitoring/public/alerts/badge.tsx @@ -23,18 +23,25 @@ import { AlertPanel } from './panel'; import { Legacy } from '../legacy_shims'; import { isInSetupMode } from '../lib/setup_mode'; -function getDateFromState(states: CommonAlertState[]) { - const timestamp = states[0].state.ui.triggeredMS; +function getDateFromState(state: CommonAlertState) { + const timestamp = state.state.ui.triggeredMS; const tz = Legacy.shims.uiSettings.get('dateFormat:tz'); return formatDateTimeLocal(timestamp, false, tz === 'Browser' ? null : tz); } export const numberOfAlertsLabel = (count: number) => `${count} alert${count > 1 ? 's' : ''}`; +interface AlertInPanel { + alert: CommonAlertStatus; + alertState: CommonAlertState; +} + interface Props { alerts: { [alertTypeId: string]: CommonAlertStatus }; + stateFilter: (state: AlertState) => boolean; } export const AlertsBadge: React.FC = (props: Props) => { + const { stateFilter = () => true } = props; const [showPopover, setShowPopover] = React.useState(null); const inSetupMode = isInSetupMode(); const alerts = Object.values(props.alerts).filter(Boolean); @@ -93,15 +100,20 @@ export const AlertsBadge: React.FC = (props: Props) => { ); } else { const byType = { - [AlertSeverity.Danger]: [] as CommonAlertStatus[], - [AlertSeverity.Warning]: [] as CommonAlertStatus[], - [AlertSeverity.Success]: [] as CommonAlertStatus[], + [AlertSeverity.Danger]: [] as AlertInPanel[], + [AlertSeverity.Warning]: [] as AlertInPanel[], + [AlertSeverity.Success]: [] as AlertInPanel[], }; for (const alert of alerts) { for (const alertState of alert.states) { - const state = alertState.state as AlertState; - byType[state.ui.severity].push(alert); + if (alertState.firing && stateFilter(alertState.state)) { + const state = alertState.state as AlertState; + byType[state.ui.severity].push({ + alertState, + alert, + }); + } } } @@ -127,14 +139,14 @@ export const AlertsBadge: React.FC = (props: Props) => { { id: 0, title: `Alerts`, - items: list.map(({ alert, states }, index) => { + items: list.map(({ alert, alertState }, index) => { return { name: ( -

{getDateFromState(states)}

+

{getDateFromState(alertState)}

- {alert.label} + {alert.alert.label}
), panel: index + 1, @@ -144,9 +156,9 @@ export const AlertsBadge: React.FC = (props: Props) => { ...list.map((alertStatus, index) => { return { id: index + 1, - title: getDateFromState(alertStatus.states), + title: getDateFromState(alertStatus.alertState), width: 400, - content: , + content: , }; }), ]; diff --git a/x-pack/plugins/monitoring/public/alerts/callout.tsx b/x-pack/plugins/monitoring/public/alerts/callout.tsx index d000f470da334..cad98dd1e6aec 100644 --- a/x-pack/plugins/monitoring/public/alerts/callout.tsx +++ b/x-pack/plugins/monitoring/public/alerts/callout.tsx @@ -10,7 +10,7 @@ import { EuiCallOut, EuiSpacer } from '@elastic/eui'; import { CommonAlertStatus } from '../../common/types'; import { AlertSeverity } from '../../common/enums'; import { replaceTokens } from './lib/replace_tokens'; -import { AlertMessage } from '../../server/alerts/types'; +import { AlertMessage, AlertState } from '../../server/alerts/types'; const TYPES = [ { @@ -31,16 +31,17 @@ const TYPES = [ interface Props { alerts: { [alertTypeId: string]: CommonAlertStatus }; + stateFilter: (state: AlertState) => boolean; } export const AlertsCallout: React.FC = (props: Props) => { - const { alerts } = props; + const { alerts, stateFilter = () => true } = props; const callouts = TYPES.map((type) => { const list = []; for (const alertTypeId of Object.keys(alerts)) { const alertInstance = alerts[alertTypeId]; - for (const { state } of alertInstance.states) { - if (state.ui.severity === type.severity) { + for (const { firing, state } of alertInstance.states) { + if (firing && stateFilter(state) && state.ui.severity === type.severity) { list.push(state); } } diff --git a/x-pack/plugins/monitoring/public/alerts/panel.tsx b/x-pack/plugins/monitoring/public/alerts/panel.tsx index 3c5a4ef55a96b..91a426cc8798e 100644 --- a/x-pack/plugins/monitoring/public/alerts/panel.tsx +++ b/x-pack/plugins/monitoring/public/alerts/panel.tsx @@ -18,7 +18,7 @@ import { EuiListGroupItem, } from '@elastic/eui'; -import { CommonAlertStatus } from '../../common/types'; +import { CommonAlertStatus, CommonAlertState } from '../../common/types'; import { AlertMessage } from '../../server/alerts/types'; import { Legacy } from '../legacy_shims'; import { replaceTokens } from './lib/replace_tokens'; @@ -30,10 +30,12 @@ import { BASE_ALERT_API_PATH } from '../../../alerts/common'; interface Props { alert: CommonAlertStatus; + alertState?: CommonAlertState; } export const AlertPanel: React.FC = (props: Props) => { const { - alert: { states, alert }, + alert: { alert }, + alertState, } = props; const [showFlyout, setShowFlyout] = React.useState(false); const [isEnabled, setIsEnabled] = React.useState(alert.rawAlert.enabled); @@ -190,20 +192,14 @@ export const AlertPanel: React.FC = (props: Props) => { ); - if (inSetupMode) { + if (inSetupMode || !alertState) { return
{configurationUi}
; } - const firingStates = states.filter((state) => state.firing); - if (!firingStates.length) { - return
{configurationUi}
; - } - - const firingState = firingStates[0]; const nextStepsUi = - firingState.state.ui.message.nextSteps && firingState.state.ui.message.nextSteps.length ? ( + alertState.state.ui.message.nextSteps && alertState.state.ui.message.nextSteps.length ? ( - {firingState.state.ui.message.nextSteps.map((step: AlertMessage, index: number) => ( + {alertState.state.ui.message.nextSteps.map((step: AlertMessage, index: number) => ( ))} @@ -213,7 +209,7 @@ export const AlertPanel: React.FC = (props: Props) => {
-
{replaceTokens(firingState.state.ui.message)}
+
{replaceTokens(alertState.state.ui.message)}
{nextStepsUi ? : null} {nextStepsUi} diff --git a/x-pack/plugins/monitoring/public/alerts/status.tsx b/x-pack/plugins/monitoring/public/alerts/status.tsx index 9c262884d7257..0407ddfecf5e9 100644 --- a/x-pack/plugins/monitoring/public/alerts/status.tsx +++ b/x-pack/plugins/monitoring/public/alerts/status.tsx @@ -11,14 +11,17 @@ import { CommonAlertStatus } from '../../common/types'; import { AlertSeverity } from '../../common/enums'; import { AlertState } from '../../server/alerts/types'; import { AlertsBadge } from './badge'; +import { isInSetupMode } from '../lib/setup_mode'; interface Props { alerts: { [alertTypeId: string]: CommonAlertStatus }; showBadge: boolean; showOnlyCount: boolean; + stateFilter: (state: AlertState) => boolean; } export const AlertsStatus: React.FC = (props: Props) => { - const { alerts, showBadge = false, showOnlyCount = false } = props; + const { alerts, showBadge = false, showOnlyCount = false, stateFilter = () => true } = props; + const inSetupMode = isInSetupMode(); if (!alerts) { return null; @@ -26,21 +29,26 @@ export const AlertsStatus: React.FC = (props: Props) => { let atLeastOneDanger = false; const count = Object.values(alerts).reduce((cnt, alertStatus) => { - if (alertStatus.states.length) { + const firingStates = alertStatus.states.filter((state) => state.firing); + const firingAndFilterStates = firingStates.filter((state) => stateFilter(state.state)); + cnt += firingAndFilterStates.length; + if (firingStates.length) { if (!atLeastOneDanger) { for (const state of alertStatus.states) { - if ((state.state as AlertState).ui.severity === AlertSeverity.Danger) { + if ( + stateFilter(state.state) && + (state.state as AlertState).ui.severity === AlertSeverity.Danger + ) { atLeastOneDanger = true; break; } } } - cnt++; } return cnt; }, 0); - if (count === 0) { + if (count === 0 && (!inSetupMode || showOnlyCount)) { return ( = (props: Props) => { ); } - if (showBadge) { - return ; + if (showBadge || inSetupMode) { + return ; } const severity = atLeastOneDanger ? AlertSeverity.Danger : AlertSeverity.Warning; diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/node/node.js b/x-pack/plugins/monitoring/public/components/elasticsearch/node/node.js index f91e251030d76..ac1a5212a8d26 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/node/node.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/node/node.js @@ -70,10 +70,14 @@ export const Node = ({ - + state.nodeId === nodeId} + /> - + state.nodeId === nodeId} /> {metricsToShow.map((metric, index) => ( diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/node_detail_status/index.js b/x-pack/plugins/monitoring/public/components/elasticsearch/node_detail_status/index.js index 85b4d0daddade..77d0b294f66d0 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/node_detail_status/index.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/node_detail_status/index.js @@ -11,7 +11,7 @@ import { formatMetric } from '../../../lib/format_number'; import { i18n } from '@kbn/i18n'; import { AlertsStatus } from '../../../alerts/status'; -export function NodeDetailStatus({ stats, alerts = {} }) { +export function NodeDetailStatus({ stats, alerts = {}, alertsStateFilter = () => true }) { const { transport_address: transportAddress, usedHeap, @@ -33,7 +33,7 @@ export function NodeDetailStatus({ stats, alerts = {} }) { label: i18n.translate('xpack.monitoring.elasticsearch.nodeDetailStatus.alerts', { defaultMessage: 'Alerts', }), - value: , + value: , }, { label: i18n.translate('xpack.monitoring.elasticsearch.nodeDetailStatus.transportAddress', { diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/nodes.js b/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/nodes.js index c2e5c8e22a1c0..b7463fe6532b7 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/nodes.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/nodes.js @@ -131,8 +131,14 @@ const getColumns = (showCgroupMetricsElasticsearch, setupMode, clusterUuid, aler field: 'alerts', width: '175px', sortable: true, - render: () => { - return ; + render: (_field, node) => { + return ( + state.nodeId === node.resolver} + /> + ); }, }); diff --git a/x-pack/plugins/monitoring/public/lib/internal_monitoring_toasts.tsx b/x-pack/plugins/monitoring/public/lib/internal_monitoring_toasts.tsx new file mode 100644 index 0000000000000..b6ecb631d005a --- /dev/null +++ b/x-pack/plugins/monitoring/public/lib/internal_monitoring_toasts.tsx @@ -0,0 +1,123 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiSpacer, EuiLink } from '@elastic/eui'; +import { Legacy } from '../legacy_shims'; +import { toMountPoint } from '../../../../../src/plugins/kibana_react/public'; +import { isInSetupMode, toggleSetupMode } from './setup_mode'; + +export interface MonitoringIndicesTypes { + legacyIndices: number; + metricbeatIndices: number; +} + +const enterSetupModeLabel = () => + i18n.translate('xpack.monitoring.internalMonitoringToast.enterSetupMode', { + defaultMessage: 'Enter setup mode', + }); + +const learnMoreLabel = () => + i18n.translate('xpack.monitoring.internalMonitoringToast.learnMoreAction', { + defaultMessage: 'Learn more', + }); + +const showIfLegacyOnlyIndices = () => { + const { ELASTIC_WEBSITE_URL } = Legacy.shims.docLinks; + const toast = Legacy.shims.toastNotifications.addWarning({ + title: toMountPoint( + + ), + text: toMountPoint( +
+

+ {i18n.translate('xpack.monitoring.internalMonitoringToast.description', { + defaultMessage: `It appears you are using "Legacy Collection" for Stack Monitoring. + This method of monitoring will no longer be supported in the next major release (8.0.0). + Please follow the steps in setup mode to start monitoring with Metricbeat.`, + })} +

+ { + Legacy.shims.toastNotifications.remove(toast); + toggleSetupMode(true); + }} + > + {enterSetupModeLabel()} + + + + + {learnMoreLabel()} + +
+ ), + }); +}; + +const showIfLegacyAndMetricbeatIndices = () => { + const { ELASTIC_WEBSITE_URL } = Legacy.shims.docLinks; + const toast = Legacy.shims.toastNotifications.addWarning({ + title: toMountPoint( + + ), + text: toMountPoint( +
+

+ {i18n.translate('xpack.monitoring.internalAndMetricbeatMonitoringToast.description', { + defaultMessage: `It appears you are using both Metricbeat and "Legacy Collection" for Stack Monitoring. + In 8.0.0, you must use Metricbeat to collect monitoring data. + Please follow the steps in setup mode to migrate the rest of the monitoring to Metricbeat.`, + })} +

+ { + Legacy.shims.toastNotifications.remove(toast); + toggleSetupMode(true); + }} + > + {enterSetupModeLabel()} + + + + + {learnMoreLabel()} + +
+ ), + }); +}; + +export const showInternalMonitoringToast = ({ + legacyIndices, + metricbeatIndices, +}: MonitoringIndicesTypes) => { + if (isInSetupMode()) { + return; + } + + if (legacyIndices && !metricbeatIndices) { + showIfLegacyOnlyIndices(); + } else if (legacyIndices && metricbeatIndices) { + showIfLegacyAndMetricbeatIndices(); + } +}; diff --git a/x-pack/plugins/monitoring/public/services/clusters.js b/x-pack/plugins/monitoring/public/services/clusters.js index 5173984dbe868..7f772ac1e1bcd 100644 --- a/x-pack/plugins/monitoring/public/services/clusters.js +++ b/x-pack/plugins/monitoring/public/services/clusters.js @@ -7,6 +7,7 @@ import { ajaxErrorHandlersProvider } from '../lib/ajax_error_handler'; import { Legacy } from '../legacy_shims'; import { STANDALONE_CLUSTER_CLUSTER_UUID } from '../../common/constants'; +import { showInternalMonitoringToast } from '../lib/internal_monitoring_toasts'; import { showSecurityToast } from '../alerts/lib/security_toasts'; function formatClusters(clusters) { @@ -21,6 +22,7 @@ function formatCluster(cluster) { } let once = false; +let inTransit = false; export function monitoringClustersProvider($injector) { return (clusterUuid, ccs, codePaths) => { @@ -63,19 +65,39 @@ export function monitoringClustersProvider($injector) { }); } - if (!once) { + function ensureMetricbeatEnabled() { + if (Legacy.shims.isCloud) { + return Promise.resolve(); + } + + return $http + .get('../api/monitoring/v1/elasticsearch_settings/check/internal_monitoring') + .then(({ data }) => { + showInternalMonitoringToast({ + legacyIndices: data.legacy_indices, + metricbeatIndices: data.mb_indices, + }); + }) + .catch((err) => { + const Private = $injector.get('Private'); + const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); + return ajaxErrorHandlers(err); + }); + } + + if (!once && !inTransit) { + inTransit = true; return getClusters().then((clusters) => { if (clusters.length) { - return ensureAlertsEnabled() - .then(({ data }) => { + Promise.all([ensureAlertsEnabled(), ensureMetricbeatEnabled()]) + .then(([{ data }]) => { showSecurityToast(data); once = true; - return clusters; }) .catch(() => { // Intentionally swallow the error as this will retry the next page load - return clusters; - }); + }) + .finally(() => (inTransit = false)); } return clusters; }); diff --git a/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.test.ts b/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.test.ts index 1a66560ae124a..2596252c92d11 100644 --- a/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.test.ts +++ b/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.test.ts @@ -372,5 +372,197 @@ describe('CpuUsageAlert', () => { state: 'firing', }); }); + + it('should show proper counts for resolved and firing nodes', async () => { + (fetchCpuUsageNodeStats as jest.Mock).mockImplementation(() => { + return [ + { + ...stat, + cpuUsage: 1, + }, + { + ...stat, + nodeId: 'anotherNode', + nodeName: 'anotherNode', + cpuUsage: 99, + }, + ]; + }); + (getState as jest.Mock).mockImplementation(() => { + return { + alertStates: [ + { + cluster: { + clusterUuid, + clusterName, + }, + ccs: null, + cpuUsage: 91, + nodeId, + nodeName, + ui: { + isFiring: true, + message: null, + severity: 'danger', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + { + cluster: { + clusterUuid, + clusterName, + }, + ccs: null, + cpuUsage: 100, + nodeId: 'anotherNode', + nodeName: 'anotherNode', + ui: { + isFiring: true, + message: null, + severity: 'danger', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }; + }); + const alert = new CpuUsageAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + const count = 1; + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid, clusterName }, + ccs: null, + cpuUsage: 1, + nodeId, + nodeName, + ui: { + isFiring: false, + message: { + text: + 'The cpu usage on node myNodeName is now under the threshold, currently reporting at 1.00% as of #resolved', + tokens: [ + { + startToken: '#resolved', + type: 'time', + isAbsolute: true, + isRelative: false, + timestamp: 1, + }, + ], + }, + severity: 'danger', + resolvedMS: 1, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + { + ccs: null, + cluster: { clusterUuid, clusterName }, + cpuUsage: 99, + nodeId: 'anotherNode', + nodeName: 'anotherNode', + ui: { + isFiring: true, + message: { + text: + 'Node #start_linkanotherNode#end_link is reporting cpu usage of 99.00% at #absolute', + nextSteps: [ + { + text: '#start_linkCheck hot threads#end_link', + tokens: [ + { + startToken: '#start_link', + endToken: '#end_link', + type: 'docLink', + partialUrl: + '{elasticWebsiteUrl}/guide/en/elasticsearch/reference/{docLinkVersion}/cluster-nodes-hot-threads.html', + }, + ], + }, + { + text: '#start_linkCheck long running tasks#end_link', + tokens: [ + { + startToken: '#start_link', + endToken: '#end_link', + type: 'docLink', + partialUrl: + '{elasticWebsiteUrl}/guide/en/elasticsearch/reference/{docLinkVersion}/tasks.html', + }, + ], + }, + ], + tokens: [ + { + startToken: '#absolute', + type: 'time', + isAbsolute: true, + isRelative: false, + timestamp: 1, + }, + { + startToken: '#start_link', + endToken: '#end_link', + type: 'link', + url: 'elasticsearch/nodes/anotherNode', + }, + ], + }, + severity: 'danger', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledTimes(1); + // expect(scheduleActions.mock.calls[0]).toEqual([ + // 'default', + // { + // internalFullMessage: `CPU usage alert is resolved for ${count} node(s) in cluster: ${clusterName}.`, + // internalShortMessage: `CPU usage alert is resolved for ${count} node(s) in cluster: ${clusterName}.`, + // clusterName, + // count, + // nodes: `${nodeName}:1.00`, + // state: 'resolved', + // }, + // ]); + expect(scheduleActions.mock.calls[0]).toEqual([ + 'default', + { + action: + '[View nodes](http://localhost:5601/app/monitoring#elasticsearch/nodes?_g=(cluster_uuid:abc123))', + actionPlain: 'Verify CPU levels across affected nodes.', + internalFullMessage: + 'CPU usage alert is firing for 1 node(s) in cluster: testCluster. [View nodes](http://localhost:5601/app/monitoring#elasticsearch/nodes?_g=(cluster_uuid:abc123))', + internalShortMessage: + 'CPU usage alert is firing for 1 node(s) in cluster: testCluster. Verify CPU levels across affected nodes.', + nodes: 'anotherNode:99.00', + clusterName, + count, + state: 'firing', + }, + ]); + }); }); }); diff --git a/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.ts b/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.ts index b543a4c976377..4742f55487045 100644 --- a/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.ts +++ b/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.ts @@ -291,13 +291,6 @@ export class CpuUsageAlert extends BaseAlert { return; } - const nodes = instanceState.alertStates - .map((_state) => { - const state = _state as AlertCpuUsageState; - return `${state.nodeName}:${state.cpuUsage.toFixed(2)}`; - }) - .join(','); - const ccs = instanceState.alertStates.reduce((accum: string, state): string => { if (state.ccs) { return state.ccs; @@ -305,35 +298,16 @@ export class CpuUsageAlert extends BaseAlert { return accum; }, ''); - const count = instanceState.alertStates.length; - if (!instanceState.alertStates[0].ui.isFiring) { - instance.scheduleActions('default', { - internalShortMessage: i18n.translate( - 'xpack.monitoring.alerts.cpuUsage.resolved.internalShortMessage', - { - defaultMessage: `CPU usage alert is resolved for {count} node(s) in cluster: {clusterName}.`, - values: { - count, - clusterName: cluster.clusterName, - }, - } - ), - internalFullMessage: i18n.translate( - 'xpack.monitoring.alerts.cpuUsage.resolved.internalFullMessage', - { - defaultMessage: `CPU usage alert is resolved for {count} node(s) in cluster: {clusterName}.`, - values: { - count, - clusterName: cluster.clusterName, - }, - } - ), - state: RESOLVED, - nodes, - count, - clusterName: cluster.clusterName, - }); - } else { + const firingCount = instanceState.alertStates.filter((alertState) => alertState.ui.isFiring) + .length; + const firingNodes = instanceState.alertStates + .filter((_state) => (_state as AlertCpuUsageState).ui.isFiring) + .map((_state) => { + const state = _state as AlertCpuUsageState; + return `${state.nodeName}:${state.cpuUsage.toFixed(2)}`; + }) + .join(','); + if (firingCount > 0) { const shortActionText = i18n.translate('xpack.monitoring.alerts.cpuUsage.shortAction', { defaultMessage: 'Verify CPU levels across affected nodes.', }); @@ -354,7 +328,7 @@ export class CpuUsageAlert extends BaseAlert { { defaultMessage: `CPU usage alert is firing for {count} node(s) in cluster: {clusterName}. {shortActionText}`, values: { - count, + count: firingCount, clusterName: cluster.clusterName, shortActionText, }, @@ -365,19 +339,58 @@ export class CpuUsageAlert extends BaseAlert { { defaultMessage: `CPU usage alert is firing for {count} node(s) in cluster: {clusterName}. {action}`, values: { - count, + count: firingCount, clusterName: cluster.clusterName, action, }, } ), state: FIRING, - nodes, - count, + nodes: firingNodes, + count: firingCount, clusterName: cluster.clusterName, action, actionPlain: shortActionText, }); + } else { + const resolvedCount = instanceState.alertStates.filter( + (alertState) => !alertState.ui.isFiring + ).length; + const resolvedNodes = instanceState.alertStates + .filter((_state) => !(_state as AlertCpuUsageState).ui.isFiring) + .map((_state) => { + const state = _state as AlertCpuUsageState; + return `${state.nodeName}:${state.cpuUsage.toFixed(2)}`; + }) + .join(','); + if (resolvedCount > 0) { + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.cpuUsage.resolved.internalShortMessage', + { + defaultMessage: `CPU usage alert is resolved for {count} node(s) in cluster: {clusterName}.`, + values: { + count: resolvedCount, + clusterName: cluster.clusterName, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.cpuUsage.resolved.internalFullMessage', + { + defaultMessage: `CPU usage alert is resolved for {count} node(s) in cluster: {clusterName}.`, + values: { + count: resolvedCount, + clusterName: cluster.clusterName, + }, + } + ), + state: RESOLVED, + nodes: resolvedNodes, + count: resolvedCount, + clusterName: cluster.clusterName, + }); + } } } diff --git a/x-pack/plugins/monitoring/server/config.test.ts b/x-pack/plugins/monitoring/server/config.test.ts index 16d52f684109e..32b8691bd6049 100644 --- a/x-pack/plugins/monitoring/server/config.test.ts +++ b/x-pack/plugins/monitoring/server/config.test.ts @@ -27,33 +27,6 @@ describe('config schema', () => { }, "enabled": true, }, - "elasticsearch": Object { - "apiVersion": "master", - "customHeaders": Object {}, - "healthCheck": Object { - "delay": "PT2.5S", - }, - "ignoreVersionMismatch": false, - "logFetchCount": 10, - "logQueries": false, - "pingTimeout": "PT30S", - "preserveHost": true, - "requestHeadersWhitelist": Array [ - "authorization", - ], - "requestTimeout": "PT30S", - "shardTimeout": "PT30S", - "sniffInterval": false, - "sniffOnConnectionFault": false, - "sniffOnStart": false, - "ssl": Object { - "alwaysPresentCertificate": false, - "keystore": Object {}, - "truststore": Object {}, - "verificationMode": "full", - }, - "startupTimeout": "PT5S", - }, "enabled": true, "kibana": Object { "collection": Object { @@ -125,9 +98,6 @@ describe('createConfig()', () => { it('should wrap in Elasticsearch config', async () => { const config = createConfig( configSchema.validate({ - elasticsearch: { - hosts: 'http://localhost:9200', - }, ui: { elasticsearch: { hosts: 'http://localhost:9200', @@ -135,7 +105,6 @@ describe('createConfig()', () => { }, }) ); - expect(config.elasticsearch.hosts).toEqual(['http://localhost:9200']); expect(config.ui.elasticsearch.hosts).toEqual(['http://localhost:9200']); }); @@ -147,9 +116,6 @@ describe('createConfig()', () => { }; const config = createConfig( configSchema.validate({ - elasticsearch: { - ssl, - }, ui: { elasticsearch: { ssl, @@ -162,7 +128,6 @@ describe('createConfig()', () => { key: 'contents-of-packages/kbn-dev-utils/certs/elasticsearch.key', certificateAuthorities: ['contents-of-packages/kbn-dev-utils/certs/ca.crt'], }); - expect(config.elasticsearch.ssl).toEqual(expected); expect(config.ui.elasticsearch.ssl).toEqual(expected); }); }); diff --git a/x-pack/plugins/monitoring/server/config.ts b/x-pack/plugins/monitoring/server/config.ts index a430be8da6a5f..789211c43db31 100644 --- a/x-pack/plugins/monitoring/server/config.ts +++ b/x-pack/plugins/monitoring/server/config.ts @@ -21,7 +21,6 @@ export const monitoringElasticsearchConfigSchema = elasticsearchConfigSchema.ext export const configSchema = schema.object({ enabled: schema.boolean({ defaultValue: true }), - elasticsearch: monitoringElasticsearchConfigSchema, ui: schema.object({ enabled: schema.boolean({ defaultValue: true }), ccs: schema.object({ @@ -86,7 +85,6 @@ export type MonitoringConfig = ReturnType; export function createConfig(config: TypeOf) { return { ...config, - elasticsearch: new ElasticsearchConfig(config.elasticsearch as ElasticsearchConfigType), ui: { ...config.ui, elasticsearch: new MonitoringElasticsearchConfig(config.ui.elasticsearch), diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/__tests__/bulk_uploader.js b/x-pack/plugins/monitoring/server/kibana_monitoring/__tests__/bulk_uploader.js index 3421f5d3830d6..da12bde966091 100644 --- a/x-pack/plugins/monitoring/server/kibana_monitoring/__tests__/bulk_uploader.js +++ b/x-pack/plugins/monitoring/server/kibana_monitoring/__tests__/bulk_uploader.js @@ -6,10 +6,8 @@ import { noop } from 'lodash'; import sinon from 'sinon'; -import moment from 'moment'; import expect from '@kbn/expect'; import { BulkUploader } from '../bulk_uploader'; -import { MONITORING_SYSTEM_API_VERSION } from '../../../common/constants'; const FETCH_INTERVAL = 300; const CHECK_DELAY = 500; @@ -314,92 +312,5 @@ describe('BulkUploader', () => { done(); }, CHECK_DELAY); }); - - it('uses a direct connection to the monitoring cluster, when configured', (done) => { - const dateInIndex = '2020.02.10'; - const oldNow = moment.now; - moment.now = () => 1581310800000; - const prodClusterUuid = '1sdfd5'; - const prodCluster = { - callWithInternalUser: sinon - .stub() - .withArgs('monitoring.bulk') - .callsFake((arg) => { - let resolution = null; - if (arg === 'info') { - resolution = { cluster_uuid: prodClusterUuid }; - } - return new Promise((resolve) => resolve(resolution)); - }), - }; - const monitoringCluster = { - callWithInternalUser: sinon - .stub() - .withArgs('bulk') - .callsFake(() => { - return new Promise((resolve) => setTimeout(resolve, CHECK_DELAY + 1)); - }), - }; - - const collectorFetch = sinon.stub().returns({ - type: 'kibana_stats', - result: { type: 'kibana_stats', payload: { testData: 12345 } }, - }); - - const collectors = new MockCollectorSet(server, [ - { - fetch: collectorFetch, - isReady: () => true, - formatForBulkUpload: (result) => result, - isUsageCollector: false, - }, - ]); - const customServer = { - ...server, - elasticsearchPlugin: { - createCluster: () => monitoringCluster, - getCluster: (name) => { - if (name === 'admin' || name === 'data') { - return prodCluster; - } - return monitoringCluster; - }, - }, - config: { - get: (key) => { - if (key === 'monitoring.elasticsearch') { - return { - hosts: ['http://localhost:9200'], - username: 'tester', - password: 'testing', - ssl: {}, - }; - } - return null; - }, - }, - }; - const kbnServerStatus = { toJSON: () => ({ overall: { state: 'green' } }) }; - const kbnServerVersion = 'master'; - const uploader = new BulkUploader({ - ...customServer, - interval: FETCH_INTERVAL, - kbnServerStatus, - kbnServerVersion, - }); - uploader.start(collectors); - setTimeout(() => { - uploader.stop(); - const firstCallArgs = monitoringCluster.callWithInternalUser.firstCall.args; - expect(firstCallArgs[0]).to.be('bulk'); - expect(firstCallArgs[1].body[0].index._index).to.be( - `.monitoring-kibana-${MONITORING_SYSTEM_API_VERSION}-${dateInIndex}` - ); - expect(firstCallArgs[1].body[1].type).to.be('kibana_stats'); - expect(firstCallArgs[1].body[1].cluster_uuid).to.be(prodClusterUuid); - moment.now = oldNow; - done(); - }, CHECK_DELAY); - }); }); }); diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/bulk_uploader.js b/x-pack/plugins/monitoring/server/kibana_monitoring/bulk_uploader.js index 6035837bac85d..b23b4fc888120 100644 --- a/x-pack/plugins/monitoring/server/kibana_monitoring/bulk_uploader.js +++ b/x-pack/plugins/monitoring/server/kibana_monitoring/bulk_uploader.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { defaultsDeep, uniq, compact, get } from 'lodash'; +import { defaultsDeep, uniq, compact } from 'lodash'; import { TELEMETRY_COLLECTION_INTERVAL, @@ -12,7 +12,6 @@ import { } from '../../common/constants'; import { sendBulkPayload, monitoringBulk } from './lib'; -import { hasMonitoringCluster } from '../es_client/instantiate_client'; /* * Handles internal Kibana stats collection and uploading data to Monitoring @@ -31,13 +30,11 @@ import { hasMonitoringCluster } from '../es_client/instantiate_client'; * @param {Object} xpackInfo server.plugins.xpack_main.info object */ export class BulkUploader { - constructor({ config, log, interval, elasticsearch, kibanaStats }) { + constructor({ log, interval, elasticsearch, kibanaStats }) { if (typeof interval !== 'number') { throw new Error('interval number of milliseconds is required'); } - this._hasDirectConnectionToMonitoringCluster = false; - this._productionClusterUuid = null; this._timer = null; // Hold sending and fetching usage until monitoring.bulk is successful. This means that we // send usage data on the second tick. But would save a lot of bandwidth fetching usage on @@ -54,15 +51,6 @@ export class BulkUploader { plugins: [monitoringBulk], }); - if (hasMonitoringCluster(config.elasticsearch)) { - this._log.info(`Detected direct connection to monitoring cluster`); - this._hasDirectConnectionToMonitoringCluster = true; - this._cluster = elasticsearch.legacy.createClient('monitoring-direct', config.elasticsearch); - elasticsearch.legacy.client.callAsInternalUser('info').then((data) => { - this._productionClusterUuid = get(data, 'cluster_uuid'); - }); - } - this.kibanaStats = kibanaStats; this.kibanaStatusGetter = null; } @@ -181,14 +169,7 @@ export class BulkUploader { } async _onPayload(payload) { - return await sendBulkPayload( - this._cluster, - this._interval, - payload, - this._log, - this._hasDirectConnectionToMonitoringCluster, - this._productionClusterUuid - ); + return await sendBulkPayload(this._cluster, this._interval, payload, this._log); } getKibanaStats(type) { diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/lib/send_bulk_payload.js b/x-pack/plugins/monitoring/server/kibana_monitoring/lib/send_bulk_payload.js index 9607b45d7e408..66799e4aa651a 100644 --- a/x-pack/plugins/monitoring/server/kibana_monitoring/lib/send_bulk_payload.js +++ b/x-pack/plugins/monitoring/server/kibana_monitoring/lib/send_bulk_payload.js @@ -3,64 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import moment from 'moment'; -import { chunk, get } from 'lodash'; -import { - MONITORING_SYSTEM_API_VERSION, - KIBANA_SYSTEM_ID, - KIBANA_STATS_TYPE_MONITORING, - KIBANA_SETTINGS_TYPE, -} from '../../../common/constants'; - -const SUPPORTED_TYPES = [KIBANA_STATS_TYPE_MONITORING, KIBANA_SETTINGS_TYPE]; -export function formatForNormalBulkEndpoint(payload, productionClusterUuid) { - const dateSuffix = moment.utc().format('YYYY.MM.DD'); - return chunk(payload, 2).reduce((accum, chunk) => { - const type = get(chunk[0], 'index._type'); - if (!type || !SUPPORTED_TYPES.includes(type)) { - return accum; - } - - const { timestamp } = chunk[1]; - - accum.push({ - index: { - _index: `.monitoring-kibana-${MONITORING_SYSTEM_API_VERSION}-${dateSuffix}`, - }, - }); - accum.push({ - [type]: chunk[1], - type, - timestamp, - cluster_uuid: productionClusterUuid, - }); - return accum; - }, []); -} +import { MONITORING_SYSTEM_API_VERSION, KIBANA_SYSTEM_ID } from '../../../common/constants'; /* * Send the Kibana usage data to the ES Monitoring Bulk endpoint */ -export async function sendBulkPayload( - cluster, - interval, - payload, - log, - hasDirectConnectionToMonitoringCluster = false, - productionClusterUuid = null -) { - if (hasDirectConnectionToMonitoringCluster) { - if (productionClusterUuid === null) { - log.warn( - `Unable to determine production cluster uuid to use for shipping monitoring data. Kibana monitoring data will appear in a standalone cluster in the Stack Monitoring UI.` - ); - } - const formattedPayload = formatForNormalBulkEndpoint(payload, productionClusterUuid); - return await cluster.callAsInternalUser('bulk', { - body: formattedPayload, - }); - } - +export async function sendBulkPayload(cluster, interval, payload) { return cluster.callAsInternalUser('monitoring.bulk', { system_id: KIBANA_SYSTEM_ID, system_api_version: MONITORING_SYSTEM_API_VERSION, diff --git a/x-pack/plugins/monitoring/server/plugin.ts b/x-pack/plugins/monitoring/server/plugin.ts index 39ec5fe1ffaa7..86022a0e863d5 100644 --- a/x-pack/plugins/monitoring/server/plugin.ts +++ b/x-pack/plugins/monitoring/server/plugin.ts @@ -25,6 +25,7 @@ import { LOGGING_TAG, KIBANA_MONITORING_LOGGING_TAG, KIBANA_STATS_TYPE_MONITORING, + ALERTS, } from '../common/constants'; import { MonitoringConfig, createConfig, configSchema } from './config'; // @ts-ignore @@ -242,6 +243,7 @@ export class Plugin { app: ['monitoring', 'kibana'], catalogue: ['monitoring'], privileges: null, + alerting: ALERTS, reserved: { description: i18n.translate('xpack.monitoring.feature.reserved.description', { defaultMessage: 'To grant users access, you should also assign the monitoring_user role.', @@ -256,6 +258,9 @@ export class Plugin { all: [], read: [], }, + alerting: { + all: ALERTS, + }, ui: [], }, }, diff --git a/x-pack/plugins/monitoring/server/routes/api/v1/elasticsearch_settings/check/internal_monitoring.ts b/x-pack/plugins/monitoring/server/routes/api/v1/elasticsearch_settings/check/internal_monitoring.ts new file mode 100644 index 0000000000000..4473d824c9e30 --- /dev/null +++ b/x-pack/plugins/monitoring/server/routes/api/v1/elasticsearch_settings/check/internal_monitoring.ts @@ -0,0 +1,85 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { RequestHandlerContext } from 'kibana/server'; +// @ts-ignore +import { getIndexPatterns } from '../../../../../lib/cluster/get_index_patterns'; +// @ts-ignore +import { handleError } from '../../../../../lib/errors'; +import { RouteDependencies } from '../../../../../types'; + +const queryBody = { + size: 0, + aggs: { + types: { + terms: { + field: '_index', + size: 10, + }, + }, + }, +}; + +const checkLatestMonitoringIsLegacy = async (context: RequestHandlerContext, index: string) => { + const { client: esClient } = context.core.elasticsearch.legacy; + const result = await esClient.callAsCurrentUser('search', { + index, + body: queryBody, + }); + + const { aggregations } = result; + const counts = { + legacyIndicesCount: 0, + mbIndicesCount: 0, + }; + + if (!aggregations) { + return counts; + } + + const { + types: { buckets }, + } = aggregations; + counts.mbIndicesCount = buckets.filter(({ key }: { key: string }) => key.includes('-mb-')).length; + + counts.legacyIndicesCount = buckets.length - counts.mbIndicesCount; + return counts; +}; + +export function internalMonitoringCheckRoute(server: unknown, npRoute: RouteDependencies) { + npRoute.router.get( + { + path: '/api/monitoring/v1/elasticsearch_settings/check/internal_monitoring', + validate: false, + }, + async (context, _request, response) => { + try { + const typeCount = { + legacy_indices: 0, + mb_indices: 0, + }; + + const { esIndexPattern, kbnIndexPattern, lsIndexPattern } = getIndexPatterns(server); + const indexCounts = await Promise.all([ + checkLatestMonitoringIsLegacy(context, esIndexPattern), + checkLatestMonitoringIsLegacy(context, kbnIndexPattern), + checkLatestMonitoringIsLegacy(context, lsIndexPattern), + ]); + + indexCounts.forEach((counts) => { + typeCount.legacy_indices += counts.legacyIndicesCount; + typeCount.mb_indices += counts.mbIndicesCount; + }); + + return response.ok({ + body: typeCount, + }); + } catch (err) { + throw handleError(err); + } + } + ); +} diff --git a/x-pack/plugins/monitoring/server/routes/api/v1/elasticsearch_settings/index.js b/x-pack/plugins/monitoring/server/routes/api/v1/elasticsearch_settings/index.js index d7ef71efc0b51..906057d221868 100644 --- a/x-pack/plugins/monitoring/server/routes/api/v1/elasticsearch_settings/index.js +++ b/x-pack/plugins/monitoring/server/routes/api/v1/elasticsearch_settings/index.js @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +export { internalMonitoringCheckRoute } from './check/internal_monitoring'; export { clusterSettingsCheckRoute } from './check/cluster'; export { nodesSettingsCheckRoute } from './check/nodes'; export { setCollectionEnabledRoute } from './set/collection_enabled'; diff --git a/x-pack/plugins/monitoring/server/routes/api/v1/ui.js b/x-pack/plugins/monitoring/server/routes/api/v1/ui.js index de0213ec84689..e8daf52582437 100644 --- a/x-pack/plugins/monitoring/server/routes/api/v1/ui.js +++ b/x-pack/plugins/monitoring/server/routes/api/v1/ui.js @@ -20,6 +20,7 @@ export { ccrShardRoute, } from './elasticsearch'; export { + internalMonitoringCheckRoute, clusterSettingsCheckRoute, nodesSettingsCheckRoute, setCollectionEnabledRoute, diff --git a/x-pack/plugins/observability/public/application/application.test.tsx b/x-pack/plugins/observability/public/application/application.test.tsx new file mode 100644 index 0000000000000..db7fca140be89 --- /dev/null +++ b/x-pack/plugins/observability/public/application/application.test.tsx @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { renderApp } from './'; +import { Observable } from 'rxjs'; +import { CoreStart, AppMountParameters } from 'src/core/public'; + +describe('renderApp', () => { + it('renders', () => { + const core = ({ + application: { currentAppId$: new Observable(), navigateToUrl: () => {} }, + chrome: { docTitle: { change: () => {} }, setBreadcrumbs: () => {} }, + i18n: { Context: ({ children }: { children: React.ReactNode }) => children }, + uiSettings: { get: () => false }, + } as unknown) as CoreStart; + const params = ({ + element: window.document.createElement('div'), + } as unknown) as AppMountParameters; + + expect(() => { + const unmount = renderApp(core, params); + unmount(); + }).not.toThrowError(); + }); +}); diff --git a/x-pack/plugins/observability/public/application/index.tsx b/x-pack/plugins/observability/public/application/index.tsx index d76c033a41756..4c0147dc3cd51 100644 --- a/x-pack/plugins/observability/public/application/index.tsx +++ b/x-pack/plugins/observability/public/application/index.tsx @@ -23,13 +23,10 @@ const observabilityLabelBreadcrumb = { }; function getTitleFromBreadCrumbs(breadcrumbs: Breadcrumbs) { - return breadcrumbs - .map(({ text }) => text) - .reverse() - .join(' | '); + return breadcrumbs.map(({ text }) => text).reverse(); } -const App = () => { +function App() { return ( <> @@ -42,7 +39,7 @@ const App = () => { const breadcrumb = [observabilityLabelBreadcrumb, ...route.breadcrumb]; useEffect(() => { core.chrome.setBreadcrumbs(breadcrumb); - document.title = getTitleFromBreadCrumbs(breadcrumb); + core.chrome.docTitle.change(getTitleFromBreadCrumbs(breadcrumb)); }, [core, breadcrumb]); const { query, path: pathParams } = useRouteParams(route.params); @@ -53,7 +50,7 @@ const App = () => { ); -}; +} export const renderApp = (core: CoreStart, { element }: AppMountParameters) => { const i18nCore = core.i18n; diff --git a/x-pack/plugins/observability/public/components/app/chart_container/index.tsx b/x-pack/plugins/observability/public/components/app/chart_container/index.tsx index 2a0c25773eae5..b68ddbd06c778 100644 --- a/x-pack/plugins/observability/public/components/app/chart_container/index.tsx +++ b/x-pack/plugins/observability/public/components/app/chart_container/index.tsx @@ -18,12 +18,12 @@ interface Props { const CHART_HEIGHT = 170; -export const ChartContainer = ({ +export function ChartContainer({ isInitialLoad, children, iconSize = 'xl', height = CHART_HEIGHT, -}: Props) => { +}: Props) { if (isInitialLoad) { return (
{children}; -}; +} diff --git a/x-pack/plugins/observability/public/components/app/empty_section/index.tsx b/x-pack/plugins/observability/public/components/app/empty_section/index.tsx index 4c830b2b2f094..5a2e64459358d 100644 --- a/x-pack/plugins/observability/public/components/app/empty_section/index.tsx +++ b/x-pack/plugins/observability/public/components/app/empty_section/index.tsx @@ -11,7 +11,7 @@ interface Props { section: ISection; } -export const EmptySection = ({ section }: Props) => { +export function EmptySection({ section }: Props) { return ( { } /> ); -}; +} diff --git a/x-pack/plugins/observability/public/components/app/header/index.tsx b/x-pack/plugins/observability/public/components/app/header/index.tsx index 531e6abf3d236..0e35fbb008bee 100644 --- a/x-pack/plugins/observability/public/components/app/header/index.tsx +++ b/x-pack/plugins/observability/public/components/app/header/index.tsx @@ -38,12 +38,12 @@ interface Props { showGiveFeedback?: boolean; } -export const Header = ({ +export function Header({ color, restrictWidth, showAddData = false, showGiveFeedback = false, -}: Props) => { +}: Props) { const { core } = usePluginContext(); return ( @@ -91,4 +91,4 @@ export const Header = ({ ); -}; +} diff --git a/x-pack/plugins/observability/public/components/app/ingest_manager_panel/index.tsx b/x-pack/plugins/observability/public/components/app/ingest_manager_panel/index.tsx index 41bcfa1da7fa1..1ab9f75632d9d 100644 --- a/x-pack/plugins/observability/public/components/app/ingest_manager_panel/index.tsx +++ b/x-pack/plugins/observability/public/components/app/ingest_manager_panel/index.tsx @@ -12,7 +12,7 @@ import { i18n } from '@kbn/i18n'; import { EuiText } from '@elastic/eui'; import { EuiLink } from '@elastic/eui'; -export const IngestManagerPanel = () => { +export function IngestManagerPanel() { return ( { ); -}; +} diff --git a/x-pack/plugins/observability/public/components/app/layout/with_header.tsx b/x-pack/plugins/observability/public/components/app/layout/with_header.tsx index 27b25f0056055..a77487e1244e6 100644 --- a/x-pack/plugins/observability/public/components/app/layout/with_header.tsx +++ b/x-pack/plugins/observability/public/components/app/layout/with_header.tsx @@ -32,23 +32,25 @@ interface Props { showGiveFeedback?: boolean; } -export const WithHeaderLayout = ({ +export function WithHeaderLayout({ headerColor, bodyColor, children, restrictWidth, showAddData, showGiveFeedback, -}: Props) => ( - -
- - {children} - - -); +}: Props) { + return ( + +
+ + {children} + + + ); +} diff --git a/x-pack/plugins/observability/public/components/app/news_feed/index.tsx b/x-pack/plugins/observability/public/components/app/news_feed/index.tsx index 2fbd6659bcb5a..625ae94c90aa2 100644 --- a/x-pack/plugins/observability/public/components/app/news_feed/index.tsx +++ b/x-pack/plugins/observability/public/components/app/news_feed/index.tsx @@ -23,7 +23,7 @@ interface Props { items: INewsItem[]; } -export const NewsFeed = ({ items }: Props) => { +export function NewsFeed({ items }: Props) { return ( // The news feed is manually added/edited, to prevent any errors caused by typos or missing fields, // wraps the component with EuiErrorBoundary to avoid breaking the entire page. @@ -46,11 +46,11 @@ export const NewsFeed = ({ items }: Props) => { ); -}; +} const limitString = (string: string, limit: number) => truncate(string, { length: limit }); -const NewsItem = ({ item }: { item: INewsItem }) => { +function NewsItem({ item }: { item: INewsItem }) { const theme = useContext(ThemeContext); return ( @@ -98,4 +98,4 @@ const NewsItem = ({ item }: { item: INewsItem }) => { ); -}; +} diff --git a/x-pack/plugins/observability/public/components/app/resources/index.tsx b/x-pack/plugins/observability/public/components/app/resources/index.tsx index 929802df3329b..47ac5f0f6d301 100644 --- a/x-pack/plugins/observability/public/components/app/resources/index.tsx +++ b/x-pack/plugins/observability/public/components/app/resources/index.tsx @@ -31,7 +31,7 @@ const resources = [ }, ]; -export const Resources = () => { +export function Resources() { return ( @@ -46,4 +46,4 @@ export const Resources = () => { ); -}; +} diff --git a/x-pack/plugins/observability/public/components/app/section/alerts/index.tsx b/x-pack/plugins/observability/public/components/app/section/alerts/index.tsx index c0dc67b3373b1..02e841ec50ee2 100644 --- a/x-pack/plugins/observability/public/components/app/section/alerts/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/alerts/index.tsx @@ -33,7 +33,7 @@ interface Props { alerts: Alert[]; } -export const AlertsSection = ({ alerts }: Props) => { +export function AlertsSection({ alerts }: Props) { const { core } = usePluginContext(); const [filter, setFilter] = useState(ALL_TYPES); @@ -130,4 +130,4 @@ export const AlertsSection = ({ alerts }: Props) => { ); -}; +} diff --git a/x-pack/plugins/observability/public/components/app/section/apm/index.tsx b/x-pack/plugins/observability/public/components/app/section/apm/index.tsx index dce80ed324456..a1d51ffda6afd 100644 --- a/x-pack/plugins/observability/public/components/app/section/apm/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/apm/index.tsx @@ -30,7 +30,7 @@ function formatTpm(value?: number) { return numeral(value).format('0.00a'); } -export const APMSection = ({ absoluteTime, relativeTime, bucketSize }: Props) => { +export function APMSection({ absoluteTime, relativeTime, bucketSize }: Props) { const theme = useContext(ThemeContext); const history = useHistory(); @@ -43,7 +43,7 @@ export const APMSection = ({ absoluteTime, relativeTime, bucketSize }: Props) => bucketSize, }); } - }, [start, end, bucketSize]); + }, [start, end, bucketSize, relativeTime]); const { appLink, stats, series } = data || {}; @@ -121,4 +121,4 @@ export const APMSection = ({ absoluteTime, relativeTime, bucketSize }: Props) => ); -}; +} diff --git a/x-pack/plugins/observability/public/components/app/section/error_panel/index.tsx b/x-pack/plugins/observability/public/components/app/section/error_panel/index.tsx index 8f0781b8f0269..2413580e90a07 100644 --- a/x-pack/plugins/observability/public/components/app/section/error_panel/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/error_panel/index.tsx @@ -7,7 +7,7 @@ import { EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -export const ErrorPanel = () => { +export function ErrorPanel() { return ( @@ -19,4 +19,4 @@ export const ErrorPanel = () => { ); -}; +} diff --git a/x-pack/plugins/observability/public/components/app/section/index.tsx b/x-pack/plugins/observability/public/components/app/section/index.tsx index 9ba524259ea1c..6c6d107b714be 100644 --- a/x-pack/plugins/observability/public/components/app/section/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/index.tsx @@ -20,7 +20,7 @@ interface Props { appLink?: AppLink; } -export const SectionContainer = ({ title, appLink, children, hasError }: Props) => { +export function SectionContainer({ title, appLink, children, hasError }: Props) { const { core } = usePluginContext(); return ( ); -}; +} diff --git a/x-pack/plugins/observability/public/components/app/section/logs/index.tsx b/x-pack/plugins/observability/public/components/app/section/logs/index.tsx index 9b232ea33cbfb..aa1dc1640125e 100644 --- a/x-pack/plugins/observability/public/components/app/section/logs/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/logs/index.tsx @@ -45,7 +45,7 @@ function getColorPerItem(series?: LogsFetchDataResponse['series']) { return colorsPerItem; } -export const LogsSection = ({ absoluteTime, relativeTime, bucketSize }: Props) => { +export function LogsSection({ absoluteTime, relativeTime, bucketSize }: Props) { const history = useHistory(); const { start, end } = absoluteTime; @@ -57,7 +57,7 @@ export const LogsSection = ({ absoluteTime, relativeTime, bucketSize }: Props) = bucketSize, }); } - }, [start, end, bucketSize]); + }, [start, end, bucketSize, relativeTime]); const min = moment.utc(absoluteTime.start).valueOf(); const max = moment.utc(absoluteTime.end).valueOf(); @@ -160,4 +160,4 @@ export const LogsSection = ({ absoluteTime, relativeTime, bucketSize }: Props) = ); -}; +} diff --git a/x-pack/plugins/observability/public/components/app/section/metrics/index.tsx b/x-pack/plugins/observability/public/components/app/section/metrics/index.tsx index 9e5fdadaf4e5f..8bce8205902fa 100644 --- a/x-pack/plugins/observability/public/components/app/section/metrics/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/metrics/index.tsx @@ -46,7 +46,7 @@ const StyledProgress = styled.div<{ color?: string }>` } `; -export const MetricsSection = ({ absoluteTime, relativeTime, bucketSize }: Props) => { +export function MetricsSection({ absoluteTime, relativeTime, bucketSize }: Props) { const theme = useContext(ThemeContext); const { start, end } = absoluteTime; @@ -58,7 +58,7 @@ export const MetricsSection = ({ absoluteTime, relativeTime, bucketSize }: Props bucketSize, }); } - }, [start, end, bucketSize]); + }, [start, end, bucketSize, relativeTime]); const isLoading = status === FETCH_STATUS.LOADING; @@ -162,9 +162,9 @@ export const MetricsSection = ({ absoluteTime, relativeTime, bucketSize }: Props ); -}; +} -const AreaChart = ({ +function AreaChart({ serie, isLoading, color, @@ -172,7 +172,7 @@ const AreaChart = ({ serie?: Series; isLoading: boolean; color: string; -}) => { +}) { const chartTheme = useChartTheme(); return ( @@ -191,4 +191,4 @@ const AreaChart = ({ )} ); -}; +} diff --git a/x-pack/plugins/observability/public/components/app/section/uptime/index.tsx b/x-pack/plugins/observability/public/components/app/section/uptime/index.tsx index 73a566460a593..cfb06af3224c7 100644 --- a/x-pack/plugins/observability/public/components/app/section/uptime/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/uptime/index.tsx @@ -35,7 +35,7 @@ interface Props { bucketSize?: string; } -export const UptimeSection = ({ absoluteTime, relativeTime, bucketSize }: Props) => { +export function UptimeSection({ absoluteTime, relativeTime, bucketSize }: Props) { const theme = useContext(ThemeContext); const history = useHistory(); @@ -48,7 +48,7 @@ export const UptimeSection = ({ absoluteTime, relativeTime, bucketSize }: Props) bucketSize, }); } - }, [start, end, bucketSize]); + }, [start, end, bucketSize, relativeTime]); const min = moment.utc(absoluteTime.start).valueOf(); const max = moment.utc(absoluteTime.end).valueOf(); @@ -138,9 +138,9 @@ export const UptimeSection = ({ absoluteTime, relativeTime, bucketSize }: Props) ); -}; +} -const UptimeBarSeries = ({ +function UptimeBarSeries({ id, label, series, @@ -152,7 +152,7 @@ const UptimeBarSeries = ({ series?: Series; color: string; ticktFormatter: TickFormatter; -}) => { +}) { if (!series) { return null; } @@ -188,4 +188,4 @@ const UptimeBarSeries = ({ /> ); -}; +} diff --git a/x-pack/plugins/observability/public/components/app/styled_stat/index.tsx b/x-pack/plugins/observability/public/components/app/styled_stat/index.tsx index fe38df6484c29..a58a0c8309723 100644 --- a/x-pack/plugins/observability/public/components/app/styled_stat/index.tsx +++ b/x-pack/plugins/observability/public/components/app/styled_stat/index.tsx @@ -21,7 +21,7 @@ interface Props extends Partial { const EMPTY_VALUE = '--'; -export const StyledStat = (props: Props) => { +export function StyledStat(props: Props) { const { description = EMPTY_VALUE, title = EMPTY_VALUE, ...rest } = props; return ; -}; +} diff --git a/x-pack/plugins/observability/public/components/shared/action_menu/index.tsx b/x-pack/plugins/observability/public/components/shared/action_menu/index.tsx index ea79f4d08d701..55746ff6576a9 100644 --- a/x-pack/plugins/observability/public/components/shared/action_menu/index.tsx +++ b/x-pack/plugins/observability/public/components/shared/action_menu/index.tsx @@ -14,37 +14,45 @@ import { EuiPopoverProps, } from '@elastic/eui'; -import React, { HTMLAttributes } from 'react'; +import React, { HTMLAttributes, ReactNode } from 'react'; import { EuiListGroupItemProps } from '@elastic/eui/src/components/list_group/list_group_item'; import styled from 'styled-components'; type Props = EuiPopoverProps & HTMLAttributes; -export const SectionTitle: React.FC<{}> = (props) => ( - <> - -
{props.children}
-
- - -); - -export const SectionSubtitle: React.FC<{}> = (props) => ( - <> - - {props.children} - - - -); - -export const SectionLinks: React.FC<{}> = (props) => ( - - {props.children} - -); - -export const SectionSpacer: React.FC<{}> = () => ; +export function SectionTitle({ children }: { children?: ReactNode }) { + return ( + <> + +
{children}
+
+ + + ); +} + +export function SectionSubtitle({ children }: { children?: ReactNode }) { + return ( + <> + + {children} + + + + ); +} + +export function SectionLinks({ children }: { children?: ReactNode }) { + return ( + + {children} + + ); +} + +export function SectionSpacer() { + return ; +} export const Section = styled.div` margin-bottom: 24px; @@ -54,10 +62,14 @@ export const Section = styled.div` `; export type SectionLinkProps = EuiListGroupItemProps; -export const SectionLink: React.FC = (props) => ( - -); +export function SectionLink(props: SectionLinkProps) { + return ; +} -export const ActionMenuDivider: React.FC<{}> = (props) => ; +export function ActionMenuDivider() { + return ; +} -export const ActionMenu: React.FC = (props) => ; +export function ActionMenu(props: Props) { + return ; +} diff --git a/x-pack/plugins/observability/public/components/shared/data_picker/index.tsx b/x-pack/plugins/observability/public/components/shared/data_picker/index.tsx index cc77c1ed72b4a..1c4f465a1d301 100644 --- a/x-pack/plugins/observability/public/components/shared/data_picker/index.tsx +++ b/x-pack/plugins/observability/public/components/shared/data_picker/index.tsx @@ -31,7 +31,7 @@ interface Props { refreshInterval: number; } -export const DatePicker = ({ rangeFrom, rangeTo, refreshPaused, refreshInterval }: Props) => { +export function DatePicker({ rangeFrom, rangeTo, refreshPaused, refreshInterval }: Props) { const location = useLocation(); const history = useHistory(); @@ -86,4 +86,4 @@ export const DatePicker = ({ rangeFrom, rangeTo, refreshPaused, refreshInterval onRefresh={onTimeChange} /> ); -}; +} diff --git a/x-pack/plugins/observability/public/pages/home/index.tsx b/x-pack/plugins/observability/public/pages/home/index.tsx index 59513fc047f17..349533346f2ad 100644 --- a/x-pack/plugins/observability/public/pages/home/index.tsx +++ b/x-pack/plugins/observability/public/pages/home/index.tsx @@ -8,7 +8,7 @@ import { useHistory } from 'react-router-dom'; import { fetchHasData } from '../../data_handler'; import { useFetcher } from '../../hooks/use_fetcher'; -export const HomePage = () => { +export function HomePage() { const history = useHistory(); const { data = {} } = useFetcher(() => fetchHasData(), []); @@ -23,4 +23,4 @@ export const HomePage = () => { } return <>; -}; +} diff --git a/x-pack/plugins/observability/public/pages/landing/index.tsx b/x-pack/plugins/observability/public/pages/landing/index.tsx index 81485953f8713..4d8bd4bf2c789 100644 --- a/x-pack/plugins/observability/public/pages/landing/index.tsx +++ b/x-pack/plugins/observability/public/pages/landing/index.tsx @@ -27,7 +27,7 @@ const EuiCardWithoutPadding = styled(EuiCard)` padding: 0; `; -export const LandingPage = () => { +export function LandingPage() { const { core } = usePluginContext(); const theme = useContext(ThemeContext); @@ -124,4 +124,4 @@ export const LandingPage = () => { ); -}; +} diff --git a/x-pack/plugins/observability/public/pages/overview/index.tsx b/x-pack/plugins/observability/public/pages/overview/index.tsx index 088fab032d930..32bdb00577bd2 100644 --- a/x-pack/plugins/observability/public/pages/overview/index.tsx +++ b/x-pack/plugins/observability/public/pages/overview/index.tsx @@ -38,14 +38,14 @@ function calculatetBucketSize({ start, end }: { start?: number; end?: number }) } } -export const OverviewPage = ({ routeParams }: Props) => { +export function OverviewPage({ routeParams }: Props) { const { core } = usePluginContext(); const { data: alerts = [], status: alertStatus } = useFetcher(() => { return getObservabilityAlerts({ core }); - }, []); + }, [core]); - const { data: newsFeed } = useFetcher(() => getNewsFeed({ core }), []); + const { data: newsFeed } = useFetcher(() => getNewsFeed({ core }), [core]); const theme = useContext(ThemeContext); const timePickerTime = useKibanaUISettings(UI_SETTINGS.TIMEPICKER_TIME_DEFAULTS); @@ -206,4 +206,4 @@ export const OverviewPage = ({ routeParams }: Props) => { ); -}; +} diff --git a/x-pack/plugins/observability/public/pages/overview/loading_observability.tsx b/x-pack/plugins/observability/public/pages/overview/loading_observability.tsx index 90e3104443e6b..0f4fa9b864744 100644 --- a/x-pack/plugins/observability/public/pages/overview/loading_observability.tsx +++ b/x-pack/plugins/observability/public/pages/overview/loading_observability.tsx @@ -20,7 +20,7 @@ const CentralizedFlexGroup = styled(EuiFlexGroup)` min-height: calc(100vh - ${(props) => props.theme.eui.euiHeaderChildSize}); `; -export const LoadingObservability = () => { +export function LoadingObservability() { const theme = useContext(ThemeContext); return ( @@ -50,4 +50,4 @@ export const LoadingObservability = () => { ); -}; +} diff --git a/x-pack/plugins/observability/public/typings/eui_styled_components.tsx b/x-pack/plugins/observability/public/typings/eui_styled_components.tsx index aab16f9d79c4b..9e547b58bc736 100644 --- a/x-pack/plugins/observability/public/typings/eui_styled_components.tsx +++ b/x-pack/plugins/observability/public/typings/eui_styled_components.tsx @@ -16,23 +16,25 @@ export interface EuiTheme { darkMode: boolean; } -const EuiThemeProvider = < +function EuiThemeProvider< OuterTheme extends styledComponents.DefaultTheme = styledComponents.DefaultTheme >({ darkMode = false, ...otherProps }: Omit, 'theme'> & { darkMode?: boolean; -}) => ( - ({ - ...outerTheme, - eui: darkMode ? euiDarkVars : euiLightVars, - darkMode, - })} - /> -); +}) { + return ( + ({ + ...outerTheme, + eui: darkMode ? euiDarkVars : euiLightVars, + darkMode, + })} + /> + ); +} const { default: euiStyled, diff --git a/x-pack/plugins/reporting/server/export_types/png/create_job/index.ts b/x-pack/plugins/reporting/server/export_types/png/create_job/index.ts index b63f2a09041b3..9227354520b6e 100644 --- a/x-pack/plugins/reporting/server/export_types/png/create_job/index.ts +++ b/x-pack/plugins/reporting/server/export_types/png/create_job/index.ts @@ -13,7 +13,6 @@ export const scheduleTaskFnFactory: ScheduleTaskFnFactory> = function createJobFactoryFn(reporting) { const config = reporting.getConfig(); - const setupDeps = reporting.getPluginSetupDeps(); const crypto = cryptoFactory(config.get('encryptionKey')); return async function scheduleTask( @@ -32,7 +31,7 @@ export const scheduleTaskFnFactory: ScheduleTaskFnFactory> = function createJobFactoryFn(reporting) { const config = reporting.getConfig(); - const setupDeps = reporting.getPluginSetupDeps(); const crypto = cryptoFactory(config.get('encryptionKey')); return async function scheduleTaskFn( @@ -26,7 +25,7 @@ export const scheduleTaskFnFactory: ScheduleTaskFnFactory { + const t = ({ + api: new ApiActions(versionNumber), + app: new AppActions(versionNumber), + login: 'login:', + savedObject: new SavedObjectActions(versionNumber), + alerting: new AlertingActions(versionNumber), + space: new SpaceActions(versionNumber), + ui: new UIActions(versionNumber), + version: `version:${versionNumber}`, + } as unknown) as jest.Mocked; + return t; +}; + +export const actionsMock = { create }; diff --git a/x-pack/plugins/security/server/authorization/actions/actions.ts b/x-pack/plugins/security/server/authorization/actions/actions.ts index 00293e88abe76..34258bdcf972d 100644 --- a/x-pack/plugins/security/server/authorization/actions/actions.ts +++ b/x-pack/plugins/security/server/authorization/actions/actions.ts @@ -9,6 +9,7 @@ import { AppActions } from './app'; import { SavedObjectActions } from './saved_object'; import { SpaceActions } from './space'; import { UIActions } from './ui'; +import { AlertingActions } from './alerting'; /** Actions are used to create the "actions" that are associated with Elasticsearch's * application privileges, and are used to perform the authorization checks implemented @@ -23,6 +24,8 @@ export class Actions { public readonly savedObject = new SavedObjectActions(this.versionNumber); + public readonly alerting = new AlertingActions(this.versionNumber); + public readonly space = new SpaceActions(this.versionNumber); public readonly ui = new UIActions(this.versionNumber); diff --git a/x-pack/plugins/security/server/authorization/actions/alerting.test.ts b/x-pack/plugins/security/server/authorization/actions/alerting.test.ts new file mode 100644 index 0000000000000..744543f38a914 --- /dev/null +++ b/x-pack/plugins/security/server/authorization/actions/alerting.test.ts @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { AlertingActions } from './alerting'; + +const version = '1.0.0-zeta1'; + +describe('#get', () => { + [null, undefined, '', 1, true, {}].forEach((alertType: any) => { + test(`alertType of ${JSON.stringify(alertType)} throws error`, () => { + const alertingActions = new AlertingActions(version); + expect(() => + alertingActions.get(alertType, 'consumer', 'foo-action') + ).toThrowErrorMatchingSnapshot(); + }); + }); + + [null, undefined, '', 1, true, {}].forEach((operation: any) => { + test(`operation of ${JSON.stringify(operation)} throws error`, () => { + const alertingActions = new AlertingActions(version); + expect(() => + alertingActions.get('foo-alertType', 'consumer', operation) + ).toThrowErrorMatchingSnapshot(); + }); + }); + + [null, '', 1, true, undefined, {}].forEach((consumer: any) => { + test(`consumer of ${JSON.stringify(consumer)} throws error`, () => { + const alertingActions = new AlertingActions(version); + expect(() => + alertingActions.get('foo-alertType', consumer, 'operation') + ).toThrowErrorMatchingSnapshot(); + }); + }); + + test('returns `alerting:${alertType}/${consumer}/${operation}`', () => { + const alertingActions = new AlertingActions(version); + expect(alertingActions.get('foo-alertType', 'consumer', 'bar-operation')).toBe( + 'alerting:1.0.0-zeta1:foo-alertType/consumer/bar-operation' + ); + }); +}); diff --git a/x-pack/plugins/security/server/authorization/actions/alerting.ts b/x-pack/plugins/security/server/authorization/actions/alerting.ts new file mode 100644 index 0000000000000..99d04efe6892d --- /dev/null +++ b/x-pack/plugins/security/server/authorization/actions/alerting.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { isString } from 'lodash'; + +export class AlertingActions { + private readonly prefix: string; + + constructor(versionNumber: string) { + this.prefix = `alerting:${versionNumber}:`; + } + + public get(alertTypeId: string, consumer: string, operation: string): string { + if (!alertTypeId || !isString(alertTypeId)) { + throw new Error('alertTypeId is required and must be a string'); + } + + if (!operation || !isString(operation)) { + throw new Error('operation is required and must be a string'); + } + + if (!consumer || !isString(consumer)) { + throw new Error('consumer is required and must be a string'); + } + + return `${this.prefix}${alertTypeId}/${consumer}/${operation}`; + } +} diff --git a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.test.ts b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.test.ts index 45f55b34baf96..f9405214aac5a 100644 --- a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.test.ts +++ b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.test.ts @@ -20,6 +20,9 @@ const mockRequest = httpServerMock.createKibanaRequest(); const createMockAuthz = (options: MockAuthzOptions) => { const mock = authorizationMock.create({ version: '1.0.0-zeta1' }); + // plug actual ui actions into mock Actions with + mock.actions = actions; + mock.checkPrivilegesDynamicallyWithRequest.mockImplementation((request) => { expect(request).toBe(mockRequest); @@ -50,7 +53,7 @@ describe('usingPrivileges', () => { new Feature({ id: 'fooFeature', name: 'Foo Feature', - app: ['fooApp'], + app: ['fooApp', 'foo'], navLinkId: 'foo', privileges: null, }), @@ -126,7 +129,7 @@ describe('usingPrivileges', () => { new Feature({ id: 'fooFeature', name: 'Foo Feature', - app: [], + app: ['foo'], navLinkId: 'foo', privileges: null, }), @@ -259,7 +262,7 @@ describe('usingPrivileges', () => { id: 'barFeature', name: 'Bar Feature', navLinkId: 'bar', - app: [], + app: ['bar'], privileges: null, }), ], @@ -409,7 +412,7 @@ describe('all', () => { new Feature({ id: 'fooFeature', name: 'Foo Feature', - app: [], + app: ['foo'], navLinkId: 'foo', privileges: null, }), diff --git a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts index a9b3fa54d3617..c126be1b07f6e 100644 --- a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts +++ b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts @@ -18,12 +18,11 @@ export function disableUICapabilitiesFactory( logger: Logger, authz: AuthorizationServiceSetup ) { - // nav links are sourced from two places: - // 1) The `navLinkId` property. This is deprecated and will be removed (https://github.com/elastic/kibana/issues/66217) - // 2) The apps property. The Kibana Platform associates nav links to the app which registers it, in a 1:1 relationship. - // This behavior is replacing the `navLinkId` property above. + // nav links are sourced from the apps property. + // The Kibana Platform associates nav links to the app which registers it, in a 1:1 relationship. + // This behavior is replacing the `navLinkId` property. const featureNavLinkIds = features - .flatMap((feature) => [feature.navLinkId, ...feature.app]) + .flatMap((feature) => feature.app) .filter((navLinkId) => navLinkId != null); const shouldDisableFeatureUICapability = ( diff --git a/x-pack/plugins/security/server/authorization/index.mock.ts b/x-pack/plugins/security/server/authorization/index.mock.ts index 930ede4157723..62b254d132d9e 100644 --- a/x-pack/plugins/security/server/authorization/index.mock.ts +++ b/x-pack/plugins/security/server/authorization/index.mock.ts @@ -3,16 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - -import { Actions } from '.'; import { AuthorizationMode } from './mode'; +import { actionsMock } from './actions/actions.mock'; export const authorizationMock = { create: ({ version = 'mock-version', applicationName = 'mock-application', }: { version?: string; applicationName?: string } = {}) => ({ - actions: new Actions(version), + actions: actionsMock.create(version), checkPrivilegesWithRequest: jest.fn(), checkPrivilegesDynamicallyWithRequest: jest.fn(), checkSavedObjectsPrivilegesWithRequest: jest.fn(), diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.test.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.test.ts new file mode 100644 index 0000000000000..99d69602db137 --- /dev/null +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.test.ts @@ -0,0 +1,178 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Actions } from '../../actions'; +import { FeaturePrivilegeAlertingBuilder } from './alerting'; +import { Feature, FeatureKibanaPrivileges } from '../../../../../features/server'; + +const version = '1.0.0-zeta1'; + +describe(`feature_privilege_builder`, () => { + describe(`alerting`, () => { + test('grants no privileges by default', () => { + const actions = new Actions(version); + const alertingFeaturePrivileges = new FeaturePrivilegeAlertingBuilder(actions); + + const privilege: FeatureKibanaPrivileges = { + alerting: { + all: [], + read: [], + }, + + savedObject: { + all: [], + read: [], + }, + ui: [], + }; + + const feature = new Feature({ + id: 'my-feature', + name: 'my-feature', + app: [], + privileges: { + all: privilege, + read: privilege, + }, + }); + + expect(alertingFeaturePrivileges.getActions(privilege, feature)).toEqual([]); + }); + + describe(`within feature`, () => { + test('grants `read` privileges under feature consumer', () => { + const actions = new Actions(version); + const alertingFeaturePrivileges = new FeaturePrivilegeAlertingBuilder(actions); + + const privilege: FeatureKibanaPrivileges = { + alerting: { + all: [], + read: ['alert-type'], + }, + + savedObject: { + all: [], + read: [], + }, + ui: [], + }; + + const feature = new Feature({ + id: 'my-feature', + name: 'my-feature', + app: [], + privileges: { + all: privilege, + read: privilege, + }, + }); + + expect(alertingFeaturePrivileges.getActions(privilege, feature)).toMatchInlineSnapshot(` + Array [ + "alerting:1.0.0-zeta1:alert-type/my-feature/get", + "alerting:1.0.0-zeta1:alert-type/my-feature/getAlertState", + "alerting:1.0.0-zeta1:alert-type/my-feature/find", + ] + `); + }); + + test('grants `all` privileges under feature consumer', () => { + const actions = new Actions(version); + const alertingFeaturePrivileges = new FeaturePrivilegeAlertingBuilder(actions); + + const privilege: FeatureKibanaPrivileges = { + alerting: { + all: ['alert-type'], + read: [], + }, + + savedObject: { + all: [], + read: [], + }, + ui: [], + }; + + const feature = new Feature({ + id: 'my-feature', + name: 'my-feature', + app: [], + privileges: { + all: privilege, + read: privilege, + }, + }); + + expect(alertingFeaturePrivileges.getActions(privilege, feature)).toMatchInlineSnapshot(` + Array [ + "alerting:1.0.0-zeta1:alert-type/my-feature/get", + "alerting:1.0.0-zeta1:alert-type/my-feature/getAlertState", + "alerting:1.0.0-zeta1:alert-type/my-feature/find", + "alerting:1.0.0-zeta1:alert-type/my-feature/create", + "alerting:1.0.0-zeta1:alert-type/my-feature/delete", + "alerting:1.0.0-zeta1:alert-type/my-feature/update", + "alerting:1.0.0-zeta1:alert-type/my-feature/updateApiKey", + "alerting:1.0.0-zeta1:alert-type/my-feature/enable", + "alerting:1.0.0-zeta1:alert-type/my-feature/disable", + "alerting:1.0.0-zeta1:alert-type/my-feature/muteAll", + "alerting:1.0.0-zeta1:alert-type/my-feature/unmuteAll", + "alerting:1.0.0-zeta1:alert-type/my-feature/muteInstance", + "alerting:1.0.0-zeta1:alert-type/my-feature/unmuteInstance", + ] + `); + }); + + test('grants both `all` and `read` privileges under feature consumer', () => { + const actions = new Actions(version); + const alertingFeaturePrivileges = new FeaturePrivilegeAlertingBuilder(actions); + + const privilege: FeatureKibanaPrivileges = { + alerting: { + all: ['alert-type'], + read: ['readonly-alert-type'], + }, + + savedObject: { + all: [], + read: [], + }, + ui: [], + }; + + const feature = new Feature({ + id: 'my-feature', + name: 'my-feature', + app: [], + privileges: { + all: privilege, + read: privilege, + }, + }); + + expect(alertingFeaturePrivileges.getActions(privilege, feature)).toMatchInlineSnapshot(` + Array [ + "alerting:1.0.0-zeta1:alert-type/my-feature/get", + "alerting:1.0.0-zeta1:alert-type/my-feature/getAlertState", + "alerting:1.0.0-zeta1:alert-type/my-feature/find", + "alerting:1.0.0-zeta1:alert-type/my-feature/create", + "alerting:1.0.0-zeta1:alert-type/my-feature/delete", + "alerting:1.0.0-zeta1:alert-type/my-feature/update", + "alerting:1.0.0-zeta1:alert-type/my-feature/updateApiKey", + "alerting:1.0.0-zeta1:alert-type/my-feature/enable", + "alerting:1.0.0-zeta1:alert-type/my-feature/disable", + "alerting:1.0.0-zeta1:alert-type/my-feature/muteAll", + "alerting:1.0.0-zeta1:alert-type/my-feature/unmuteAll", + "alerting:1.0.0-zeta1:alert-type/my-feature/muteInstance", + "alerting:1.0.0-zeta1:alert-type/my-feature/unmuteInstance", + "alerting:1.0.0-zeta1:readonly-alert-type/my-feature/get", + "alerting:1.0.0-zeta1:readonly-alert-type/my-feature/getAlertState", + "alerting:1.0.0-zeta1:readonly-alert-type/my-feature/find", + ] + `); + }); + }); + }); +}); diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.ts new file mode 100644 index 0000000000000..42dd7794ba184 --- /dev/null +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/alerting.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { uniq } from 'lodash'; +import { Feature, FeatureKibanaPrivileges } from '../../../../../features/server'; +import { BaseFeaturePrivilegeBuilder } from './feature_privilege_builder'; + +const readOperations: string[] = ['get', 'getAlertState', 'find']; +const writeOperations: string[] = [ + 'create', + 'delete', + 'update', + 'updateApiKey', + 'enable', + 'disable', + 'muteAll', + 'unmuteAll', + 'muteInstance', + 'unmuteInstance', +]; +const allOperations: string[] = [...readOperations, ...writeOperations]; + +export class FeaturePrivilegeAlertingBuilder extends BaseFeaturePrivilegeBuilder { + public getActions(privilegeDefinition: FeatureKibanaPrivileges, feature: Feature): string[] { + const getAlertingPrivilege = ( + operations: string[], + privilegedTypes: readonly string[], + consumer: string + ) => + privilegedTypes.flatMap((type) => + operations.map((operation) => this.actions.alerting.get(type, consumer, operation)) + ); + + return uniq([ + ...getAlertingPrivilege(allOperations, privilegeDefinition.alerting?.all ?? [], feature.id), + ...getAlertingPrivilege(readOperations, privilegeDefinition.alerting?.read ?? [], feature.id), + ]); + } +} diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts index 3d6dfbdac0251..76b664cbbe2a7 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts @@ -14,6 +14,7 @@ import { FeaturePrivilegeBuilder } from './feature_privilege_builder'; import { FeaturePrivilegeManagementBuilder } from './management'; import { FeaturePrivilegeNavlinkBuilder } from './navlink'; import { FeaturePrivilegeSavedObjectBuilder } from './saved_object'; +import { FeaturePrivilegeAlertingBuilder } from './alerting'; import { FeaturePrivilegeUIBuilder } from './ui'; export { FeaturePrivilegeBuilder }; @@ -26,6 +27,7 @@ export const featurePrivilegeBuilderFactory = (actions: Actions): FeaturePrivile new FeaturePrivilegeNavlinkBuilder(actions), new FeaturePrivilegeSavedObjectBuilder(actions), new FeaturePrivilegeUIBuilder(actions), + new FeaturePrivilegeAlertingBuilder(actions), ]; return { diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/navlink.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/navlink.ts index f25632407be86..a6e5a01c7dba8 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/navlink.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/navlink.ts @@ -9,9 +9,6 @@ import { BaseFeaturePrivilegeBuilder } from './feature_privilege_builder'; export class FeaturePrivilegeNavlinkBuilder extends BaseFeaturePrivilegeBuilder { public getActions(privilegeDefinition: FeatureKibanaPrivileges, feature: Feature): string[] { - const appNavLinks = feature.app.map((app) => this.actions.ui.get('navLinks', app)); - return feature.navLinkId - ? [this.actions.ui.get('navLinks', feature.navLinkId), ...appNavLinks] - : appNavLinks; + return (privilegeDefinition.app ?? []).map((app) => this.actions.ui.get('navLinks', app)); } } diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.test.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.test.ts index 485783253d29d..bb1f0c33fdee9 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.test.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.test.ts @@ -41,6 +41,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, read: { @@ -54,6 +58,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -80,6 +87,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -96,6 +107,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -118,6 +132,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, read: { @@ -131,6 +149,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -158,6 +179,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -181,6 +206,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, read: { @@ -194,6 +223,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -218,6 +250,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-sub-type'], read: ['read-sub-type'], }, + alerting: { + all: ['alerting-all-sub-type'], + read: ['alerting-read-sub-type'], + }, ui: ['ui-sub-type'], }, ], @@ -247,6 +283,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -263,6 +303,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -286,6 +329,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, read: { @@ -299,6 +346,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -323,6 +373,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-sub-type'], read: ['read-sub-type'], }, + alerting: { + all: ['alerting-all-sub-type'], + read: ['alerting-read-sub-type'], + }, ui: ['ui-sub-type'], }, ], @@ -352,6 +406,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -368,6 +426,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -391,6 +452,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, read: { @@ -404,6 +469,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -429,6 +497,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-sub-type'], read: ['read-sub-type'], }, + alerting: { + all: ['alerting-all-sub-type'], + read: ['alerting-read-sub-type'], + }, ui: ['ui-sub-type'], }, ], @@ -459,6 +531,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type', 'all-sub-type'], read: ['read-type', 'read-sub-type'], }, + alerting: { + all: ['alerting-all-type', 'alerting-all-sub-type'], + read: ['alerting-read-type', 'alerting-read-sub-type'], + }, ui: ['ui-action', 'ui-sub-type'], }, }, @@ -476,6 +552,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-sub-type'], read: ['read-type', 'read-sub-type'], }, + alerting: { + all: ['alerting-all-sub-type'], + read: ['alerting-read-type', 'alerting-read-sub-type'], + }, ui: ['ui-action', 'ui-sub-type'], }, }, @@ -499,6 +579,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, read: { @@ -512,6 +596,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -536,6 +623,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, ], @@ -565,6 +655,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -581,6 +675,10 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + all: [], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -604,6 +702,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, read: { @@ -617,6 +719,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -642,6 +747,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-sub-type'], read: ['read-sub-type'], }, + alerting: { + all: ['alerting-all-sub-type'], + read: ['alerting-read-sub-type'], + }, ui: ['ui-sub-type'], }, ], @@ -672,6 +781,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type', 'all-sub-type'], read: ['read-type', 'read-sub-type'], }, + alerting: { + all: ['alerting-all-type', 'alerting-all-sub-type'], + read: ['alerting-read-type', 'alerting-read-sub-type'], + }, ui: ['ui-action', 'ui-sub-type'], }, }, @@ -688,6 +801,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -737,6 +853,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-sub-type'], read: ['read-sub-type'], }, + alerting: { + all: ['alerting-all-sub-type'], + read: ['alerting-read-sub-type'], + }, ui: ['ui-sub-type'], }, ], @@ -767,6 +887,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-sub-type'], read: ['read-sub-type'], }, + alerting: { + all: ['alerting-all-sub-type'], + read: ['alerting-read-sub-type'], + }, ui: ['ui-sub-type'], }, }, @@ -784,6 +908,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-sub-type'], read: ['read-sub-type'], }, + alerting: { + all: ['alerting-all-sub-type'], + read: ['alerting-read-sub-type'], + }, ui: ['ui-sub-type'], }, }, @@ -807,6 +935,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, read: { @@ -820,6 +952,9 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -867,6 +1002,10 @@ describe('featurePrivilegeIterator', () => { all: ['all-type'], read: ['read-type'], }, + alerting: { + all: ['alerting-all-type'], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, @@ -883,6 +1022,10 @@ describe('featurePrivilegeIterator', () => { all: [], read: ['read-type'], }, + alerting: { + all: [], + read: ['alerting-read-type'], + }, ui: ['ui-action'], }, }, diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.ts index 029b2e77f7812..17c9464b14756 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.ts @@ -72,6 +72,14 @@ function mergeWithSubFeatures( mergedConfig.savedObject.read, subFeaturePrivilege.savedObject.read ); + + mergedConfig.alerting = { + all: mergeArrays(mergedConfig.alerting?.all ?? [], subFeaturePrivilege.alerting?.all ?? []), + read: mergeArrays( + mergedConfig.alerting?.read ?? [], + subFeaturePrivilege.alerting?.read ?? [] + ), + }; } return mergedConfig; } diff --git a/x-pack/plugins/security/server/authorization/privileges/privileges.test.ts b/x-pack/plugins/security/server/authorization/privileges/privileges.test.ts index d8ece8f68d425..89ac73c220756 100644 --- a/x-pack/plugins/security/server/authorization/privileges/privileges.test.ts +++ b/x-pack/plugins/security/server/authorization/privileges/privileges.test.ts @@ -54,20 +54,8 @@ describe('features', () => { const actual = privileges.get(); expect(actual).toHaveProperty('features.foo-feature', { - all: [ - actions.login, - actions.version, - actions.ui.get('navLinks', 'kibana:foo'), - actions.ui.get('navLinks', 'app-1'), - actions.ui.get('navLinks', 'app-2'), - ], - read: [ - actions.login, - actions.version, - actions.ui.get('navLinks', 'kibana:foo'), - actions.ui.get('navLinks', 'app-1'), - actions.ui.get('navLinks', 'app-2'), - ], + all: [actions.login, actions.version], + read: [actions.login, actions.version], }); }); @@ -275,7 +263,6 @@ describe('features', () => { actions.ui.get('catalogue', 'all-catalogue-2'), actions.ui.get('management', 'all-management', 'all-management-1'), actions.ui.get('management', 'all-management', 'all-management-2'), - actions.ui.get('navLinks', 'kibana:foo'), actions.savedObject.get('all-savedObject-all-1', 'bulk_get'), actions.savedObject.get('all-savedObject-all-1', 'get'), actions.savedObject.get('all-savedObject-all-1', 'find'), @@ -386,7 +373,6 @@ describe('features', () => { actions.ui.get('catalogue', 'read-catalogue-2'), actions.ui.get('management', 'read-management', 'read-management-1'), actions.ui.get('management', 'read-management', 'read-management-2'), - actions.ui.get('navLinks', 'kibana:foo'), actions.savedObject.get('read-savedObject-all-1', 'bulk_get'), actions.savedObject.get('read-savedObject-all-1', 'get'), actions.savedObject.get('read-savedObject-all-1', 'find'), @@ -644,12 +630,7 @@ describe('reserved', () => { const privileges = privilegesFactory(actions, mockXPackMainPlugin as any, mockLicenseService); const actual = privileges.get(); - expect(actual).toHaveProperty('reserved.foo', [ - actions.version, - actions.ui.get('navLinks', 'kibana:foo'), - actions.ui.get('navLinks', 'app-1'), - actions.ui.get('navLinks', 'app-2'), - ]); + expect(actual).toHaveProperty('reserved.foo', [actions.version]); }); test(`actions only specified at the privilege are alright too`, () => { diff --git a/x-pack/plugins/security/server/authorization/privileges/privileges.ts b/x-pack/plugins/security/server/authorization/privileges/privileges.ts index f9ee5fc750127..5d8ef3f376cac 100644 --- a/x-pack/plugins/security/server/authorization/privileges/privileges.ts +++ b/x-pack/plugins/security/server/authorization/privileges/privileges.ts @@ -90,7 +90,6 @@ export function privilegesFactory( delete featurePrivileges[feature.id]; } } - return { features: featurePrivileges, global: { diff --git a/x-pack/plugins/security/server/mocks.ts b/x-pack/plugins/security/server/mocks.ts index c2d99433b0346..4ce0ec6e3c10e 100644 --- a/x-pack/plugins/security/server/mocks.ts +++ b/x-pack/plugins/security/server/mocks.ts @@ -17,6 +17,7 @@ function createSetupMock() { authz: { actions: mockAuthz.actions, checkPrivilegesWithRequest: mockAuthz.checkPrivilegesWithRequest, + checkPrivilegesDynamicallyWithRequest: mockAuthz.checkPrivilegesDynamicallyWithRequest, mode: mockAuthz.mode, }, registerSpacesService: jest.fn(), diff --git a/x-pack/plugins/security/server/plugin.test.ts b/x-pack/plugins/security/server/plugin.test.ts index 243bad0ec3e71..db015d246f591 100644 --- a/x-pack/plugins/security/server/plugin.test.ts +++ b/x-pack/plugins/security/server/plugin.test.ts @@ -69,6 +69,9 @@ describe('Security Plugin', () => { }, "authz": Object { "actions": Actions { + "alerting": AlertingActions { + "prefix": "alerting:version:", + }, "api": ApiActions { "prefix": "api:version:", }, @@ -88,6 +91,7 @@ describe('Security Plugin', () => { "version": "version:version", "versionNumber": "version", }, + "checkPrivilegesDynamicallyWithRequest": [Function], "checkPrivilegesWithRequest": [Function], "mode": Object { "useRbacForRequest": [Function], diff --git a/x-pack/plugins/security/server/plugin.ts b/x-pack/plugins/security/server/plugin.ts index c4b16c9eec872..1753eb7b62ed1 100644 --- a/x-pack/plugins/security/server/plugin.ts +++ b/x-pack/plugins/security/server/plugin.ts @@ -51,7 +51,10 @@ export interface SecurityPluginSetup { | 'grantAPIKeyAsInternalUser' | 'invalidateAPIKeyAsInternalUser' >; - authz: Pick; + authz: Pick< + AuthorizationServiceSetup, + 'actions' | 'checkPrivilegesDynamicallyWithRequest' | 'checkPrivilegesWithRequest' | 'mode' + >; license: SecurityLicense; audit: Pick; @@ -206,6 +209,7 @@ export class Plugin { authz: { actions: authz.actions, checkPrivilegesWithRequest: authz.checkPrivilegesWithRequest, + checkPrivilegesDynamicallyWithRequest: authz.checkPrivilegesDynamicallyWithRequest, mode: authz.mode, }, diff --git a/x-pack/plugins/security_solution/README.md b/x-pack/plugins/security_solution/README.md new file mode 100644 index 0000000000000..6680dbf1a149b --- /dev/null +++ b/x-pack/plugins/security_solution/README.md @@ -0,0 +1,130 @@ +# Security Solution + +Welcome to the Kibana Security Solution plugin! This README will go over getting started with development and testing. + +## Development + +## Tests + +The endpoint specific tests leverage the ingest manager to install the endpoint package. Before the api integration +and functional tests are run the ingest manager is initialized. This initialization process includes reaching out to +a package registry service to install the endpoint package. The endpoint tests support three different ways to run +the tests given the constraint on an available package registry. + +1. Using Docker +2. Running your own local package registry +3. Using the default external package registry + +These scenarios will be outlined the sections below. + +### Endpoint API Integration Tests Location + +The endpoint api integration tests are located [here](../../test/security_solution_endpoint_api_int) + +### Endpoint Functional Tests Location + +The endpoint functional tests are located [here](../../test/security_solution_endpoint) + +### Using Docker + +To run the tests using the recommended docker image version you must have `docker` installed. The testing infrastructure +will stand up a docker container using the image defined [here](../../test/ingest_manager_api_integration/config.ts#L15) + +Make sure you're in the Kibana root directory. + +#### Endpoint API Integration Tests + +In one terminal, run: + +```bash +INGEST_MANAGEMENT_PACKAGE_REGISTRY_PORT=12345 yarn test:ftr:server --config x-pack/test/security_solution_endpoint_api_int/config.ts +``` + +In another terminal, run: + +```bash +INGEST_MANAGEMENT_PACKAGE_REGISTRY_PORT=12345 yarn test:ftr:runner --config x-pack/test/security_solution_endpoint_api_int/config.ts +``` + +#### Endpoint Functional Tests + +In one terminal, run: + +```bash +INGEST_MANAGEMENT_PACKAGE_REGISTRY_PORT=12345 yarn test:ftr:server --config x-pack/test/security_solution_endpoint/config.ts +``` + +In another terminal, run: + +```bash +INGEST_MANAGEMENT_PACKAGE_REGISTRY_PORT=12345 yarn test:ftr:runner --config x-pack/test/security_solution_endpoint/config.ts +``` + +### Running your own package registry + +If you are doing endpoint package development it will be useful to run your own package registry to serve the latest package you're building. +To do this use the following commands: + +Make sure you're in the Kibana root directory. + +#### Endpoint API Integration Tests + +In one terminal, run: + +```bash +PACKAGE_REGISTRY_URL_OVERRIDE= yarn test:ftr:server --config x-pack/test/security_solution_endpoint_api_int/config.ts +``` + +In another terminal, run: + +```bash +PACKAGE_REGISTRY_URL_OVERRIDE= yarn test:ftr:runner --config x-pack/test/security_solution_endpoint_api_int/config.ts +``` + +#### Endpoint Functional Tests + +In one terminal, run: + +```bash +PACKAGE_REGISTRY_URL_OVERRIDE= yarn test:ftr:server --config x-pack/test/security_solution_endpoint/config.ts +``` + +In another terminal, run: + +```bash +PACKAGE_REGISTRY_URL_OVERRIDE= yarn test:ftr:runner --config x-pack/test/security_solution_endpoint/config.ts +``` + +### Using the default public registry + +If you don't have docker installed and don't want to run your own registry, you can run the tests using the ingest manager's default public package registry. The actual package registry used is [here](../../plugins/ingest_manager/common/constants/epm.ts#L9) + +Make sure you're in the Kibana root directory. + +#### Endpoint API Integration Tests + +In one terminal, run: + +```bash +yarn test:ftr:server --config x-pack/test/security_solution_endpoint_api_int/config.ts +``` + +In another terminal, run: + +```bash +yarn test:ftr:runner --config x-pack/test/security_solution_endpoint_api_int/config.ts +``` + +#### Endpoint Functional Tests + +In one terminal, run: + +```bash +yarn test:ftr:server --config x-pack/test/security_solution_endpoint/config.ts +``` + +In another terminal, run: + +```bash +yarn test:ftr:runner --config x-pack/test/security_solution_endpoint/config.ts +``` diff --git a/x-pack/plugins/security_solution/common/constants.ts b/x-pack/plugins/security_solution/common/constants.ts index f934d90c740a5..c74cf888a2db6 100644 --- a/x-pack/plugins/security_solution/common/constants.ts +++ b/x-pack/plugins/security_solution/common/constants.ts @@ -32,6 +32,7 @@ export const DEFAULT_INTERVAL_PAUSE = true; export const DEFAULT_INTERVAL_TYPE = 'manual'; export const DEFAULT_INTERVAL_VALUE = 300000; // ms export const DEFAULT_TIMEPICKER_QUICK_RANGES = 'timepicker:quickRanges'; +export const SCROLLING_DISABLED_CLASS_NAME = 'scrolling-disabled'; export const FILTERS_GLOBAL_HEIGHT = 109; // px export const FULL_SCREEN_TOGGLED_CLASS_NAME = 'fullScreenToggled'; export const NO_ALERT_INDEX = 'no-alert-index-049FC71A-4C2C-446F-9901-37XMC5024C51'; diff --git a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.test.ts b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.test.ts index 1c7a2a5de6594..2cebaacc67681 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.test.ts @@ -5,14 +5,13 @@ */ import { - buildQueryExceptions, - buildExceptionItemEntries, + buildExceptionListQueries, + buildExceptionItem, operatorBuilder, buildExists, buildMatch, buildMatchAny, - evaluateValues, - formatQuery, + buildEntry, getLanguageBooleanOperator, buildNested, } from './build_exceptions_query'; @@ -30,7 +29,6 @@ import { getEntryMatchAnyMock } from '../../../lists/common/schemas/types/entry_ import { getEntryExistsMock } from '../../../lists/common/schemas/types/entry_exists.mock'; describe('build_exceptions_query', () => { - let exclude: boolean; const makeMatchEntry = ({ field, value = 'value-1', @@ -97,10 +95,6 @@ describe('build_exceptions_query', () => { operator: 'excluded', }); - beforeEach(() => { - exclude = true; - }); - describe('getLanguageBooleanOperator', () => { test('it returns value as uppercase if language is "lucene"', () => { const result = getLanguageBooleanOperator({ language: 'lucene', value: 'not' }); @@ -143,14 +137,14 @@ describe('build_exceptions_query', () => { describe('kuery', () => { test('it returns formatted wildcard string when operator is "excluded"', () => { const query = buildExists({ - item: existsEntryWithExcluded, + entry: existsEntryWithExcluded, language: 'kuery', }); expect(query).toEqual('not host.name:*'); }); test('it returns formatted wildcard string when operator is "included"', () => { const query = buildExists({ - item: existsEntryWithIncluded, + entry: existsEntryWithIncluded, language: 'kuery', }); expect(query).toEqual('host.name:*'); @@ -160,14 +154,14 @@ describe('build_exceptions_query', () => { describe('lucene', () => { test('it returns formatted wildcard string when operator is "excluded"', () => { const query = buildExists({ - item: existsEntryWithExcluded, + entry: existsEntryWithExcluded, language: 'lucene', }); expect(query).toEqual('NOT _exists_host.name'); }); test('it returns formatted wildcard string when operator is "included"', () => { const query = buildExists({ - item: existsEntryWithIncluded, + entry: existsEntryWithIncluded, language: 'lucene', }); expect(query).toEqual('_exists_host.name'); @@ -179,14 +173,14 @@ describe('build_exceptions_query', () => { describe('kuery', () => { test('it returns formatted string when operator is "included"', () => { const query = buildMatch({ - item: matchEntryWithIncluded, + entry: matchEntryWithIncluded, language: 'kuery', }); expect(query).toEqual('host.name:"suricata"'); }); test('it returns formatted string when operator is "excluded"', () => { const query = buildMatch({ - item: matchEntryWithExcluded, + entry: matchEntryWithExcluded, language: 'kuery', }); expect(query).toEqual('not host.name:"suricata"'); @@ -196,14 +190,14 @@ describe('build_exceptions_query', () => { describe('lucene', () => { test('it returns formatted string when operator is "included"', () => { const query = buildMatch({ - item: matchEntryWithIncluded, + entry: matchEntryWithIncluded, language: 'lucene', }); expect(query).toEqual('host.name:"suricata"'); }); test('it returns formatted string when operator is "excluded"', () => { const query = buildMatch({ - item: matchEntryWithExcluded, + entry: matchEntryWithExcluded, language: 'lucene', }); expect(query).toEqual('NOT host.name:"suricata"'); @@ -229,7 +223,7 @@ describe('build_exceptions_query', () => { describe('kuery', () => { test('it returns empty string if given an empty array for "values"', () => { const exceptionSegment = buildMatchAny({ - item: entryWithIncludedAndNoValues, + entry: entryWithIncludedAndNoValues, language: 'kuery', }); expect(exceptionSegment).toEqual(''); @@ -237,7 +231,7 @@ describe('build_exceptions_query', () => { test('it returns formatted string when "values" includes only one item', () => { const exceptionSegment = buildMatchAny({ - item: entryWithIncludedAndOneValue, + entry: entryWithIncludedAndOneValue, language: 'kuery', }); @@ -246,7 +240,7 @@ describe('build_exceptions_query', () => { test('it returns formatted string when operator is "included"', () => { const exceptionSegment = buildMatchAny({ - item: matchAnyEntryWithIncludedAndTwoValues, + entry: matchAnyEntryWithIncludedAndTwoValues, language: 'kuery', }); @@ -255,7 +249,7 @@ describe('build_exceptions_query', () => { test('it returns formatted string when operator is "excluded"', () => { const exceptionSegment = buildMatchAny({ - item: entryWithExcludedAndTwoValues, + entry: entryWithExcludedAndTwoValues, language: 'kuery', }); @@ -266,7 +260,7 @@ describe('build_exceptions_query', () => { describe('lucene', () => { test('it returns formatted string when operator is "included"', () => { const exceptionSegment = buildMatchAny({ - item: matchAnyEntryWithIncludedAndTwoValues, + entry: matchAnyEntryWithIncludedAndTwoValues, language: 'lucene', }); @@ -274,7 +268,7 @@ describe('build_exceptions_query', () => { }); test('it returns formatted string when operator is "excluded"', () => { const exceptionSegment = buildMatchAny({ - item: entryWithExcludedAndTwoValues, + entry: entryWithExcludedAndTwoValues, language: 'lucene', }); @@ -282,7 +276,7 @@ describe('build_exceptions_query', () => { }); test('it returns formatted string when "values" includes only one item', () => { const exceptionSegment = buildMatchAny({ - item: entryWithIncludedAndOneValue, + entry: entryWithIncludedAndOneValue, language: 'lucene', }); @@ -295,7 +289,7 @@ describe('build_exceptions_query', () => { // NOTE: Only KQL supports nested describe('kuery', () => { test('it returns formatted query when one item in nested entry', () => { - const item: EntryNested = { + const entry: EntryNested = { field: 'parent', type: 'nested', entries: [ @@ -307,35 +301,35 @@ describe('build_exceptions_query', () => { }, ], }; - const result = buildNested({ item, language: 'kuery' }); + const result = buildNested({ entry, language: 'kuery' }); expect(result).toEqual('parent:{ nestedField:"value-1" }'); }); test('it returns formatted query when entry item is "exists"', () => { - const item: EntryNested = { + const entry: EntryNested = { field: 'parent', type: 'nested', entries: [{ ...getEntryExistsMock(), field: 'nestedField', operator: 'included' }], }; - const result = buildNested({ item, language: 'kuery' }); + const result = buildNested({ entry, language: 'kuery' }); expect(result).toEqual('parent:{ nestedField:* }'); }); test('it returns formatted query when entry item is "exists" and operator is "excluded"', () => { - const item: EntryNested = { + const entry: EntryNested = { field: 'parent', type: 'nested', entries: [{ ...getEntryExistsMock(), field: 'nestedField', operator: 'excluded' }], }; - const result = buildNested({ item, language: 'kuery' }); + const result = buildNested({ entry, language: 'kuery' }); expect(result).toEqual('parent:{ not nestedField:* }'); }); test('it returns formatted query when entry item is "match_any"', () => { - const item: EntryNested = { + const entry: EntryNested = { field: 'parent', type: 'nested', entries: [ @@ -347,13 +341,13 @@ describe('build_exceptions_query', () => { }, ], }; - const result = buildNested({ item, language: 'kuery' }); + const result = buildNested({ entry, language: 'kuery' }); expect(result).toEqual('parent:{ nestedField:("value1" or "value2") }'); }); test('it returns formatted query when entry item is "match_any" and operator is "excluded"', () => { - const item: EntryNested = { + const entry: EntryNested = { field: 'parent', type: 'nested', entries: [ @@ -365,13 +359,13 @@ describe('build_exceptions_query', () => { }, ], }; - const result = buildNested({ item, language: 'kuery' }); + const result = buildNested({ entry, language: 'kuery' }); expect(result).toEqual('parent:{ not nestedField:("value1" or "value2") }'); }); test('it returns formatted query when multiple items in nested entry', () => { - const item: EntryNested = { + const entry: EntryNested = { field: 'parent', type: 'nested', entries: [ @@ -389,34 +383,34 @@ describe('build_exceptions_query', () => { }, ], }; - const result = buildNested({ item, language: 'kuery' }); + const result = buildNested({ entry, language: 'kuery' }); expect(result).toEqual('parent:{ nestedField:"value-1" and nestedFieldB:"value-2" }'); }); }); }); - describe('evaluateValues', () => { + describe('buildEntry', () => { describe('kuery', () => { test('it returns formatted wildcard string when "type" is "exists"', () => { - const result = evaluateValues({ - item: existsEntryWithIncluded, + const result = buildEntry({ + entry: existsEntryWithIncluded, language: 'kuery', }); expect(result).toEqual('host.name:*'); }); test('it returns formatted string when "type" is "match"', () => { - const result = evaluateValues({ - item: matchEntryWithIncluded, + const result = buildEntry({ + entry: matchEntryWithIncluded, language: 'kuery', }); expect(result).toEqual('host.name:"suricata"'); }); test('it returns formatted string when "type" is "match_any"', () => { - const result = evaluateValues({ - item: matchAnyEntryWithIncludedAndTwoValues, + const result = buildEntry({ + entry: matchAnyEntryWithIncludedAndTwoValues, language: 'kuery', }); expect(result).toEqual('host.name:("suricata" or "auditd")'); @@ -424,95 +418,35 @@ describe('build_exceptions_query', () => { }); describe('lucene', () => { - describe('kuery', () => { - test('it returns formatted wildcard string when "type" is "exists"', () => { - const result = evaluateValues({ - item: existsEntryWithIncluded, - language: 'lucene', - }); - expect(result).toEqual('_exists_host.name'); - }); - - test('it returns formatted string when "type" is "match"', () => { - const result = evaluateValues({ - item: matchEntryWithIncluded, - language: 'lucene', - }); - expect(result).toEqual('host.name:"suricata"'); - }); - - test('it returns formatted string when "type" is "match_any"', () => { - const result = evaluateValues({ - item: matchAnyEntryWithIncludedAndTwoValues, - language: 'lucene', - }); - expect(result).toEqual('host.name:("suricata" OR "auditd")'); - }); - }); - }); - }); - - describe('formatQuery', () => { - describe('exclude is true', () => { - describe('when query is empty string', () => { - test('it returns empty string if "exceptions" is empty array', () => { - const formattedQuery = formatQuery({ exceptions: [], language: 'kuery', exclude: true }); - expect(formattedQuery).toEqual(''); - }); - - test('it returns expected query string when single exception in array', () => { - const formattedQuery = formatQuery({ - exceptions: ['b:("value-1" or "value-2") and not c:*'], - language: 'kuery', - exclude: true, - }); - expect(formattedQuery).toEqual('not ((b:("value-1" or "value-2") and not c:*))'); - }); - }); - - test('it returns expected query string when multiple exceptions in array', () => { - const formattedQuery = formatQuery({ - exceptions: ['b:("value-1" or "value-2") and not c:*', 'not d:*'], - language: 'kuery', - exclude: true, + test('it returns formatted wildcard string when "type" is "exists"', () => { + const result = buildEntry({ + entry: existsEntryWithIncluded, + language: 'lucene', }); - expect(formattedQuery).toEqual( - 'not ((b:("value-1" or "value-2") and not c:*) or (not d:*))' - ); + expect(result).toEqual('_exists_host.name'); }); - }); - describe('exclude is false', () => { - describe('when query is empty string', () => { - test('it returns empty string if "exceptions" is empty array', () => { - const formattedQuery = formatQuery({ exceptions: [], language: 'kuery', exclude: false }); - expect(formattedQuery).toEqual(''); - }); - - test('it returns expected query string when single exception in array', () => { - const formattedQuery = formatQuery({ - exceptions: ['b:("value-1" or "value-2") and not c:*'], - language: 'kuery', - exclude: false, - }); - expect(formattedQuery).toEqual('(b:("value-1" or "value-2") and not c:*)'); + test('it returns formatted string when "type" is "match"', () => { + const result = buildEntry({ + entry: matchEntryWithIncluded, + language: 'lucene', }); + expect(result).toEqual('host.name:"suricata"'); }); - test('it returns expected query string when multiple exceptions in array', () => { - const formattedQuery = formatQuery({ - exceptions: ['b:("value-1" or "value-2") and not c:*', 'not d:*'], - language: 'kuery', - exclude: false, + test('it returns formatted string when "type" is "match_any"', () => { + const result = buildEntry({ + entry: matchAnyEntryWithIncludedAndTwoValues, + language: 'lucene', }); - expect(formattedQuery).toEqual('(b:("value-1" or "value-2") and not c:*) or (not d:*)'); + expect(result).toEqual('host.name:("suricata" OR "auditd")'); }); }); }); - describe('buildExceptionItemEntries', () => { + describe('buildExceptionItem', () => { test('it returns empty string if empty lists array passed in', () => { - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries: [], }); @@ -525,7 +459,7 @@ describe('build_exceptions_query', () => { makeMatchAnyEntry({ field: 'b' }), makeMatchEntry({ field: 'c', operator: 'excluded', value: 'value-3' }), ]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries: payload, }); @@ -545,7 +479,7 @@ describe('build_exceptions_query', () => { ], }, ]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -566,7 +500,7 @@ describe('build_exceptions_query', () => { }, makeExistsEntry({ field: 'd' }), ]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -587,7 +521,7 @@ describe('build_exceptions_query', () => { }, makeExistsEntry({ field: 'e', operator: 'excluded' }), ]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'lucene', entries, }); @@ -599,7 +533,7 @@ describe('build_exceptions_query', () => { describe('exists', () => { test('it returns expected query when list includes single list item with operator of "included"', () => { const entries: EntriesArray = [makeExistsEntry({ field: 'b' })]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -610,7 +544,7 @@ describe('build_exceptions_query', () => { test('it returns expected query when list includes single list item with operator of "excluded"', () => { const entries: EntriesArray = [makeExistsEntry({ field: 'b', operator: 'excluded' })]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -628,7 +562,7 @@ describe('build_exceptions_query', () => { entries: [makeMatchEntry({ field: 'c', operator: 'included', value: 'value-1' })], }, ]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -650,7 +584,7 @@ describe('build_exceptions_query', () => { }, makeExistsEntry({ field: 'e' }), ]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -663,7 +597,7 @@ describe('build_exceptions_query', () => { describe('match', () => { test('it returns expected query when list includes single list item with operator of "included"', () => { const entries: EntriesArray = [makeMatchEntry({ field: 'b', value: 'value' })]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -676,7 +610,7 @@ describe('build_exceptions_query', () => { const entries: EntriesArray = [ makeMatchEntry({ field: 'b', operator: 'excluded', value: 'value' }), ]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -694,7 +628,7 @@ describe('build_exceptions_query', () => { entries: [makeMatchEntry({ field: 'c', operator: 'included', value: 'valueC' })], }, ]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -716,7 +650,7 @@ describe('build_exceptions_query', () => { }, makeMatchEntry({ field: 'e', value: 'valueE' }), ]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -730,7 +664,7 @@ describe('build_exceptions_query', () => { describe('match_any', () => { test('it returns expected query when list includes single list item with operator of "included"', () => { const entries: EntriesArray = [makeMatchAnyEntry({ field: 'b' })]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -741,7 +675,7 @@ describe('build_exceptions_query', () => { test('it returns expected query when list includes single list item with operator of "excluded"', () => { const entries: EntriesArray = [makeMatchAnyEntry({ field: 'b', operator: 'excluded' })]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -759,7 +693,7 @@ describe('build_exceptions_query', () => { entries: [makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' })], }, ]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -773,7 +707,7 @@ describe('build_exceptions_query', () => { makeMatchAnyEntry({ field: 'b' }), makeMatchAnyEntry({ field: 'c' }), ]; - const query = buildExceptionItemEntries({ + const query = buildExceptionItem({ language: 'kuery', entries, }); @@ -784,15 +718,15 @@ describe('build_exceptions_query', () => { }); }); - describe('buildQueryExceptions', () => { + describe('buildExceptionListQueries', () => { test('it returns empty array if lists is empty array', () => { - const query = buildQueryExceptions({ language: 'kuery', lists: [] }); + const query = buildExceptionListQueries({ language: 'kuery', lists: [] }); expect(query).toEqual([]); }); test('it returns empty array if lists is undefined', () => { - const query = buildQueryExceptions({ language: 'kuery', lists: undefined }); + const query = buildExceptionListQueries({ language: 'kuery', lists: undefined }); expect(query).toEqual([]); }); @@ -812,14 +746,24 @@ describe('build_exceptions_query', () => { }, makeMatchAnyEntry({ field: 'e', operator: 'excluded' }), ]; - const query = buildQueryExceptions({ + const queries = buildExceptionListQueries({ language: 'kuery', lists: [payload, payload2], }); - const expectedQuery = - 'not ((some.parentField:{ nested.field:"some value" } and some.not.nested.field:"some value") or (b:("value-1" or "value-2") and parent:{ c:"valueC" and d:"valueD" } and not e:("value-1" or "value-2")))'; + const expectedQueries = [ + { + query: + 'some.parentField:{ nested.field:"some value" } and some.not.nested.field:"some value"', + language: 'kuery', + }, + { + query: + 'b:("value-1" or "value-2") and parent:{ c:"valueC" and d:"valueD" } and not e:("value-1" or "value-2")', + language: 'kuery', + }, + ]; - expect(query).toEqual([{ query: expectedQuery, language: 'kuery' }]); + expect(queries).toEqual(expectedQueries); }); test('it returns expected query when lists exist and language is "lucene"', () => { @@ -827,78 +771,58 @@ describe('build_exceptions_query', () => { payload.entries = [makeMatchAnyEntry({ field: 'a' }), makeMatchAnyEntry({ field: 'b' })]; const payload2 = getExceptionListItemSchemaMock(); payload2.entries = [makeMatchAnyEntry({ field: 'c' }), makeMatchAnyEntry({ field: 'd' })]; - const query = buildQueryExceptions({ + const queries = buildExceptionListQueries({ language: 'lucene', lists: [payload, payload2], }); - const expectedQuery = - 'NOT ((a:("value-1" OR "value-2") AND b:("value-1" OR "value-2")) OR (c:("value-1" OR "value-2") AND d:("value-1" OR "value-2")))'; + const expectedQueries = [ + { + query: 'a:("value-1" OR "value-2") AND b:("value-1" OR "value-2")', + language: 'lucene', + }, + { + query: 'c:("value-1" OR "value-2") AND d:("value-1" OR "value-2")', + language: 'lucene', + }, + ]; - expect(query).toEqual([{ query: expectedQuery, language: 'lucene' }]); + expect(queries).toEqual(expectedQueries); }); - describe('when "exclude" is false', () => { - beforeEach(() => { - exclude = false; + test('it builds correct queries for nested excluded fields', () => { + const payload = getExceptionListItemSchemaMock(); + const payload2 = getExceptionListItemSchemaMock(); + payload2.entries = [ + makeMatchAnyEntry({ field: 'b' }), + { + field: 'parent', + type: 'nested', + entries: [ + // TODO: these operators are not being respected. buildNested needs to be updated + makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' }), + makeMatchEntry({ field: 'd', operator: 'excluded', value: 'valueD' }), + ], + }, + makeMatchAnyEntry({ field: 'e' }), + ]; + const queries = buildExceptionListQueries({ + language: 'kuery', + lists: [payload, payload2], }); - - test('it returns empty array if lists is empty array', () => { - const query = buildQueryExceptions({ + const expectedQueries = [ + { + query: + 'some.parentField:{ nested.field:"some value" } and some.not.nested.field:"some value"', language: 'kuery', - lists: [], - exclude, - }); - - expect(query).toEqual([]); - }); - - test('it returns empty array if lists is undefined', () => { - const query = buildQueryExceptions({ language: 'kuery', lists: undefined, exclude }); - - expect(query).toEqual([]); - }); - - test('it returns expected query when lists exist and language is "kuery"', () => { - const payload = getExceptionListItemSchemaMock(); - const payload2 = getExceptionListItemSchemaMock(); - payload2.entries = [ - makeMatchAnyEntry({ field: 'b' }), - { - field: 'parent', - type: 'nested', - entries: [ - makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' }), - makeMatchEntry({ field: 'd', operator: 'excluded', value: 'valueD' }), - ], - }, - makeMatchAnyEntry({ field: 'e' }), - ]; - const query = buildQueryExceptions({ + }, + { + query: + 'b:("value-1" or "value-2") and parent:{ not c:"valueC" and not d:"valueD" } and e:("value-1" or "value-2")', language: 'kuery', - lists: [payload, payload2], - exclude, - }); - const expectedQuery = - '(some.parentField:{ nested.field:"some value" } and some.not.nested.field:"some value") or (b:("value-1" or "value-2") and parent:{ not c:"valueC" and not d:"valueD" } and e:("value-1" or "value-2"))'; - - expect(query).toEqual([{ query: expectedQuery, language: 'kuery' }]); - }); - - test('it returns expected query when lists exist and language is "lucene"', () => { - const payload = getExceptionListItemSchemaMock(); - payload.entries = [makeMatchAnyEntry({ field: 'a' }), makeMatchAnyEntry({ field: 'b' })]; - const payload2 = getExceptionListItemSchemaMock(); - payload2.entries = [makeMatchAnyEntry({ field: 'c' }), makeMatchAnyEntry({ field: 'd' })]; - const query = buildQueryExceptions({ - language: 'lucene', - lists: [payload, payload2], - exclude, - }); - const expectedQuery = - '(a:("value-1" OR "value-2") AND b:("value-1" OR "value-2")) OR (c:("value-1" OR "value-2") AND d:("value-1" OR "value-2"))'; + }, + ]; - expect(query).toEqual([{ query: expectedQuery, language: 'lucene' }]); - }); + expect(queries).toEqual(expectedQueries); }); }); }); diff --git a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts index ff492dcda3b66..c64d0b124b67a 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts @@ -64,13 +64,13 @@ export const operatorBuilder = ({ }; export const buildExists = ({ - item, + entry, language, }: { - item: EntryExists; + entry: EntryExists; language: Language; }): string => { - const { operator, field } = item; + const { operator, field } = entry; const exceptionOperator = operatorBuilder({ operator, language }); switch (language) { @@ -84,26 +84,26 @@ export const buildExists = ({ }; export const buildMatch = ({ - item, + entry, language, }: { - item: EntryMatch; + entry: EntryMatch; language: Language; }): string => { - const { value, operator, field } = item; + const { value, operator, field } = entry; const exceptionOperator = operatorBuilder({ operator, language }); return `${exceptionOperator}${field}:"${value}"`; }; export const buildMatchAny = ({ - item, + entry, language, }: { - item: EntryMatchAny; + entry: EntryMatchAny; language: Language; }): string => { - const { value, operator, field } = item; + const { value, operator, field } = entry; switch (value.length) { case 0: @@ -118,67 +118,40 @@ export const buildMatchAny = ({ }; export const buildNested = ({ - item, + entry, language, }: { - item: EntryNested; + entry: EntryNested; language: Language; }): string => { - const { field, entries } = item; + const { field, entries: subentries } = entry; const and = getLanguageBooleanOperator({ language, value: 'and' }); - const values = entries.map((entry) => evaluateValues({ item: entry, language })); + const values = subentries.map((subentry) => buildEntry({ entry: subentry, language })); return `${field}:{ ${values.join(` ${and} `)} }`; }; -export const evaluateValues = ({ - item, +export const buildEntry = ({ + entry, language, }: { - item: Entry | EntryNested; + entry: Entry | EntryNested; language: Language; }): string => { - if (entriesExists.is(item)) { - return buildExists({ item, language }); - } else if (entriesMatch.is(item)) { - return buildMatch({ item, language }); - } else if (entriesMatchAny.is(item)) { - return buildMatchAny({ item, language }); - } else if (entriesNested.is(item)) { - return buildNested({ item, language }); + if (entriesExists.is(entry)) { + return buildExists({ entry, language }); + } else if (entriesMatch.is(entry)) { + return buildMatch({ entry, language }); + } else if (entriesMatchAny.is(entry)) { + return buildMatchAny({ entry, language }); + } else if (entriesNested.is(entry)) { + return buildNested({ entry, language }); } else { return ''; } }; -export const formatQuery = ({ - exceptions, - language, - exclude, -}: { - exceptions: string[]; - language: Language; - exclude: boolean; -}): string => { - if (exceptions == null || (exceptions != null && exceptions.length === 0)) { - return ''; - } - - const or = getLanguageBooleanOperator({ language, value: 'or' }); - const not = getLanguageBooleanOperator({ language, value: 'not' }); - const formattedExceptionItems = exceptions.map((exceptionItem, index) => { - if (index === 0) { - return `(${exceptionItem})`; - } - - return `${or} (${exceptionItem})`; - }); - - const exceptionItemsQuery = formattedExceptionItems.join(' '); - return exclude ? `${not} (${exceptionItemsQuery})` : exceptionItemsQuery; -}; - -export const buildExceptionItemEntries = ({ +export const buildExceptionItem = ({ entries, language, }: { @@ -186,22 +159,19 @@ export const buildExceptionItemEntries = ({ language: Language; }): string => { const and = getLanguageBooleanOperator({ language, value: 'and' }); - const exceptionItemEntries = entries.reduce((accum, listItem) => { - const exceptionSegment = evaluateValues({ item: listItem, language }); - return [...accum, exceptionSegment]; - }, []); + const exceptionItemEntries = entries.map((entry) => { + return buildEntry({ entry, language }); + }); return exceptionItemEntries.join(` ${and} `); }; -export const buildQueryExceptions = ({ +export const buildExceptionListQueries = ({ language, lists, - exclude = true, }: { language: Language; lists: Array | undefined; - exclude?: boolean; }): DataQuery[] => { if (lists == null || (lists != null && lists.length === 0)) { return []; @@ -211,7 +181,7 @@ export const buildQueryExceptions = ({ const { entries } = exceptionItem; if (entries != null && entries.length > 0 && !hasLargeValueList(entries)) { - return [...acc, buildExceptionItemEntries({ entries, language })]; + return [...acc, buildExceptionItem({ entries, language })]; } else { return acc; } @@ -220,12 +190,11 @@ export const buildQueryExceptions = ({ if (exceptionItems.length === 0) { return []; } else { - const formattedQuery = formatQuery({ exceptions: exceptionItems, language, exclude }); - return [ - { - query: formattedQuery, + return exceptionItems.map((exceptionItem) => { + return { + query: exceptionItem, language, - }, - ]; + }; + }); } }; diff --git a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.test.ts b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.test.ts index a8eb4e7bbb15b..72ef230a42342 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.test.ts @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getQueryFilter } from './get_query_filter'; -import { Filter } from 'src/plugins/data/public'; +import { getQueryFilter, buildExceptionFilter } from './get_query_filter'; +import { Filter, EsQueryConfig } from 'src/plugins/data/public'; import { getExceptionListItemSchemaMock } from '../../../lists/common/schemas/response/exception_list_item_schema.mock'; describe('get_filter', () => { @@ -363,49 +363,151 @@ describe('get_filter', () => { bool: { filter: [ { bool: { minimum_should_match: 1, should: [{ match: { 'host.name': 'linux' } }] } }, + ], + must: [], + must_not: [ { bool: { - must_not: { - bool: { - filter: [ - { - nested: { - path: 'some.parentField', - query: { - bool: { - minimum_should_match: 1, - should: [ - { - match_phrase: { - 'some.parentField.nested.field': 'some value', + should: [ + { + bool: { + filter: [ + { + nested: { + path: 'some.parentField', + query: { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.parentField.nested.field': 'some value', + }, }, + ], + }, + }, + score_mode: 'none', + }, + }, + { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.not.nested.field': 'some value', }, - ], + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + ], + should: [], + }, + }); + }); + + test('it should work with a list with multiple items', () => { + const esQuery = getQueryFilter( + 'host.name: linux', + 'kuery', + [], + ['auditbeat-*'], + [getExceptionListItemSchemaMock(), getExceptionListItemSchemaMock()] + ); + expect(esQuery).toEqual({ + bool: { + filter: [ + { bool: { minimum_should_match: 1, should: [{ match: { 'host.name': 'linux' } }] } }, + ], + must: [], + must_not: [ + { + bool: { + should: [ + { + bool: { + filter: [ + { + nested: { + path: 'some.parentField', + query: { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.parentField.nested.field': 'some value', + }, + }, + ], + }, }, + score_mode: 'none', }, - score_mode: 'none', }, - }, - { - bool: { - minimum_should_match: 1, - should: [ - { - match_phrase: { - 'some.not.nested.field': 'some value', + { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.not.nested.field': 'some value', + }, + }, + ], + }, + }, + ], + }, + }, + { + bool: { + filter: [ + { + nested: { + path: 'some.parentField', + query: { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.parentField.nested.field': 'some value', + }, + }, + ], }, }, - ], + score_mode: 'none', + }, }, - }, - ], + { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.not.nested.field': 'some value', + }, + }, + ], + }, + }, + ], + }, }, - }, + ], }, }, ], - must: [], - must_not: [], should: [], }, }); @@ -455,32 +557,137 @@ describe('get_filter', () => { { bool: { minimum_should_match: 1, should: [{ match: { 'host.name': 'linux' } }] } }, { bool: { - filter: [ + should: [ { - nested: { - path: 'some.parentField', - query: { - bool: { - minimum_should_match: 1, - should: [ - { - match_phrase: { - 'some.parentField.nested.field': 'some value', + bool: { + filter: [ + { + nested: { + path: 'some.parentField', + query: { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.parentField.nested.field': 'some value', + }, + }, + ], }, }, - ], + score_mode: 'none', + }, }, - }, - score_mode: 'none', + { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.not.nested.field': 'some value', + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + ], + must: [], + must_not: [], + should: [], + }, + }); + }); + + test('it should work with a list with multiple items', () => { + const esQuery = getQueryFilter( + 'host.name: linux', + 'kuery', + [], + ['auditbeat-*'], + [getExceptionListItemSchemaMock(), getExceptionListItemSchemaMock()], + false + ); + expect(esQuery).toEqual({ + bool: { + filter: [ + { bool: { minimum_should_match: 1, should: [{ match: { 'host.name': 'linux' } }] } }, + { + bool: { + should: [ + { + bool: { + filter: [ + { + nested: { + path: 'some.parentField', + query: { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.parentField.nested.field': 'some value', + }, + }, + ], + }, + }, + score_mode: 'none', + }, + }, + { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.not.nested.field': 'some value', + }, + }, + ], + }, + }, + ], }, }, { bool: { - minimum_should_match: 1, - should: [ + filter: [ { - match_phrase: { - 'some.not.nested.field': 'some value', + nested: { + path: 'some.parentField', + query: { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.parentField.nested.field': 'some value', + }, + }, + ], + }, + }, + score_mode: 'none', + }, + }, + { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.not.nested.field': 'some value', + }, + }, + ], }, }, ], @@ -703,4 +910,179 @@ describe('get_filter', () => { }); }); }); + + describe('buildExceptionFilter', () => { + const config: EsQueryConfig = { + allowLeadingWildcards: true, + queryStringOptions: { analyze_wildcard: true }, + ignoreFilterIfFieldNotInIndex: false, + dateFormatTZ: 'Zulu', + }; + test('it should build a filter without chunking exception items', () => { + const exceptionFilter = buildExceptionFilter( + [ + { language: 'kuery', query: 'host.name: linux and some.field: value' }, + { language: 'kuery', query: 'user.name: name' }, + ], + { + fields: [], + title: 'auditbeat-*', + }, + config, + true, + 2 + ); + expect(exceptionFilter).toEqual({ + meta: { + alias: null, + negate: true, + disabled: false, + }, + query: { + bool: { + should: [ + { + bool: { + filter: [ + { + bool: { + minimum_should_match: 1, + should: [ + { + match: { + 'host.name': 'linux', + }, + }, + ], + }, + }, + { + bool: { + minimum_should_match: 1, + should: [ + { + match: { + 'some.field': 'value', + }, + }, + ], + }, + }, + ], + }, + }, + { + bool: { + minimum_should_match: 1, + should: [ + { + match: { + 'user.name': 'name', + }, + }, + ], + }, + }, + ], + }, + }, + }); + }); + + test('it should properly chunk exception items', () => { + const exceptionFilter = buildExceptionFilter( + [ + { language: 'kuery', query: 'host.name: linux and some.field: value' }, + { language: 'kuery', query: 'user.name: name' }, + { language: 'kuery', query: 'file.path: /safe/path' }, + ], + { + fields: [], + title: 'auditbeat-*', + }, + config, + true, + 2 + ); + expect(exceptionFilter).toEqual({ + meta: { + alias: null, + negate: true, + disabled: false, + }, + query: { + bool: { + should: [ + { + bool: { + should: [ + { + bool: { + filter: [ + { + bool: { + minimum_should_match: 1, + should: [ + { + match: { + 'host.name': 'linux', + }, + }, + ], + }, + }, + { + bool: { + minimum_should_match: 1, + should: [ + { + match: { + 'some.field': 'value', + }, + }, + ], + }, + }, + ], + }, + }, + { + bool: { + minimum_should_match: 1, + should: [ + { + match: { + 'user.name': 'name', + }, + }, + ], + }, + }, + ], + }, + }, + { + bool: { + should: [ + { + bool: { + minimum_should_match: 1, + should: [ + { + match: { + 'file.path': '/safe/path', + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + }); + }); + }); }); diff --git a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts index a41589b5d0231..466a004c14c66 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts @@ -6,20 +6,21 @@ import { Filter, + Query, IIndexPattern, isFilterDisabled, buildEsQuery, - Query as DataQuery, + EsQueryConfig, } from '../../../../../src/plugins/data/common'; import { ExceptionListItemSchema, CreateExceptionListItemSchema, } from '../../../lists/common/schemas'; -import { buildQueryExceptions } from './build_exceptions_query'; -import { Query, Language, Index } from './schemas/common/schemas'; +import { buildExceptionListQueries } from './build_exceptions_query'; +import { Query as QueryString, Language, Index } from './schemas/common/schemas'; export const getQueryFilter = ( - query: Query, + query: QueryString, language: Language, filters: Array>, index: Index, @@ -31,7 +32,14 @@ export const getQueryFilter = ( title: index.join(), }; - const initialQuery = [{ query, language }]; + const config: EsQueryConfig = { + allowLeadingWildcards: true, + queryStringOptions: { analyze_wildcard: true }, + ignoreFilterIfFieldNotInIndex: false, + dateFormatTZ: 'Zulu', + }; + + const enabledFilters = ((filters as unknown) as Filter[]).filter((f) => !isFilterDisabled(f)); /* * Pinning exceptions to 'kuery' because lucene * does not support nested queries, while our exceptions @@ -39,16 +47,78 @@ export const getQueryFilter = ( * buildEsQuery, this allows us to offer nested queries * regardless */ - const exceptions = buildQueryExceptions({ language: 'kuery', lists, exclude: excludeExceptions }); - const queries: DataQuery[] = [...initialQuery, ...exceptions]; + const exceptionQueries = buildExceptionListQueries({ language: 'kuery', lists }); + if (exceptionQueries.length > 0) { + // Assume that `indices.query.bool.max_clause_count` is at least 1024 (the default value), + // allowing us to make 1024-item chunks of exception list items. + // Discussion at https://issues.apache.org/jira/browse/LUCENE-4835 indicates that 1024 is a + // very conservative value. + const exceptionFilter = buildExceptionFilter( + exceptionQueries, + indexPattern, + config, + excludeExceptions, + 1024 + ); + enabledFilters.push(exceptionFilter); + } + const initialQuery = { query, language }; - const config = { - allowLeadingWildcards: true, - queryStringOptions: { analyze_wildcard: true }, - ignoreFilterIfFieldNotInIndex: false, - dateFormatTZ: 'Zulu', - }; + return buildEsQuery(indexPattern, initialQuery, enabledFilters, config); +}; - const enabledFilters = ((filters as unknown) as Filter[]).filter((f) => !isFilterDisabled(f)); - return buildEsQuery(indexPattern, queries, enabledFilters, config); +export const buildExceptionFilter = ( + exceptionQueries: Query[], + indexPattern: IIndexPattern, + config: EsQueryConfig, + excludeExceptions: boolean, + chunkSize: number +) => { + const exceptionFilter: Filter = { + meta: { + alias: null, + negate: excludeExceptions, + disabled: false, + }, + query: { + bool: { + should: undefined, + }, + }, + }; + if (exceptionQueries.length <= chunkSize) { + const query = buildEsQuery(indexPattern, exceptionQueries, [], config); + exceptionFilter.query.bool.should = query.bool.filter; + } else { + const chunkedFilters: Filter[] = []; + for (let index = 0; index < exceptionQueries.length; index += chunkSize) { + const exceptionQueriesChunk = exceptionQueries.slice(index, index + chunkSize); + const esQueryChunk = buildEsQuery(indexPattern, exceptionQueriesChunk, [], config); + const filterChunk: Filter = { + meta: { + alias: null, + negate: false, + disabled: false, + }, + query: { + bool: { + should: esQueryChunk.bool.filter, + }, + }, + }; + chunkedFilters.push(filterChunk); + } + // Here we build a query with only the exceptions: it will put them all in the `filter` array + // of the resulting object, which would AND the exceptions together. When creating exceptionFilter, + // we move the `filter` array to `should` so they are OR'd together instead. + // This gets around the problem with buildEsQuery not allowing callers to specify whether queries passed in + // should be ANDed or ORed together. + exceptionFilter.query.bool.should = buildEsQuery( + indexPattern, + [], + chunkedFilters, + config + ).bool.filter; + } + return exceptionFilter; }; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/common/schemas.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/common/schemas.ts index 273ea72a2ffe3..21fa780badd84 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/common/schemas.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/common/schemas.ts @@ -222,8 +222,9 @@ export const risk_score_mapping_value = t.string; export const risk_score_mapping_item = t.exact( t.type({ field: risk_score_mapping_field, - operator, value: risk_score_mapping_value, + operator, + risk_score: riskScoreOrUndefined, }) ); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackged_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackged_rules_schema.test.ts index 5fd2c3dbbf894..3cad48ec18fc1 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackged_rules_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackged_rules_schema.test.ts @@ -1446,11 +1446,13 @@ describe('add prepackaged rules schema', () => { exceptions_list: [ { id: 'some_uuid', + list_id: 'list_id_single', namespace_type: 'single', type: 'detection', }, { - id: 'some_uuid', + id: 'endpoint_list', + list_id: 'endpoint_list', namespace_type: 'agnostic', type: 'endpoint', }, @@ -1535,6 +1537,7 @@ describe('add prepackaged rules schema', () => { const checked = exactCheck(payload, decoded); const message = pipe(checked, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "exceptions_list,list_id"', 'Invalid value "undefined" supplied to "exceptions_list,type"', 'Invalid value "not a namespace type" supplied to "exceptions_list,namespace_type"', ]); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.test.ts index 71f3964956249..c2c2f4784f2b5 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.test.ts @@ -1513,11 +1513,13 @@ describe('create rules schema', () => { exceptions_list: [ { id: 'some_uuid', + list_id: 'list_id_single', namespace_type: 'single', type: 'detection', }, { - id: 'some_uuid', + id: 'endpoint_list', + list_id: 'endpoint_list', namespace_type: 'agnostic', type: 'endpoint', }, @@ -1600,6 +1602,7 @@ describe('create rules schema', () => { const checked = exactCheck(payload, decoded); const message = pipe(checked, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "exceptions_list,list_id"', 'Invalid value "undefined" supplied to "exceptions_list,type"', 'Invalid value "not a namespace type" supplied to "exceptions_list,namespace_type"', ]); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.test.ts index 828626ef26d6f..00a3f2126f44a 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.test.ts @@ -1642,11 +1642,13 @@ describe('import rules schema', () => { exceptions_list: [ { id: 'some_uuid', + list_id: 'list_id_single', namespace_type: 'single', type: 'detection', }, { - id: 'some_uuid', + id: 'endpoint_list', + list_id: 'endpoint_list', namespace_type: 'agnostic', type: 'endpoint', }, @@ -1730,6 +1732,7 @@ describe('import rules schema', () => { const checked = exactCheck(payload, decoded); const message = pipe(checked, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "exceptions_list,list_id"', 'Invalid value "undefined" supplied to "exceptions_list,type"', 'Invalid value "not a namespace type" supplied to "exceptions_list,namespace_type"', ]); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.test.ts index e75aff1abe3e9..e4fc53b934f58 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.test.ts @@ -1176,11 +1176,13 @@ describe('patch_rules_schema', () => { exceptions_list: [ { id: 'some_uuid', + list_id: 'list_id_single', namespace_type: 'single', type: 'detection', }, { - id: 'some_uuid', + id: 'endpoint_list', + list_id: 'endpoint_list', namespace_type: 'agnostic', type: 'endpoint', }, @@ -1251,6 +1253,7 @@ describe('patch_rules_schema', () => { const checked = exactCheck(payload, decoded); const message = pipe(checked, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "exceptions_list,list_id"', 'Invalid value "undefined" supplied to "exceptions_list,type"', 'Invalid value "not a namespace type" supplied to "exceptions_list,namespace_type"', 'Invalid value "[{"id":"uuid_here","namespace_type":"not a namespace type"}]" supplied to "exceptions_list"', diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.test.ts index d18d2d91b963c..024198d783048 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.test.ts @@ -1448,11 +1448,13 @@ describe('update rules schema', () => { exceptions_list: [ { id: 'some_uuid', + list_id: 'list_id_single', namespace_type: 'single', type: 'detection', }, { - id: 'some_uuid', + id: 'endpoint_list', + list_id: 'endpoint_list', namespace_type: 'agnostic', type: 'endpoint', }, @@ -1534,6 +1536,7 @@ describe('update rules schema', () => { const checked = exactCheck(payload, decoded); const message = pipe(checked, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "exceptions_list,list_id"', 'Invalid value "undefined" supplied to "exceptions_list,type"', 'Invalid value "not a namespace type" supplied to "exceptions_list,namespace_type"', ]); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.mock.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.mock.ts index 0c7853bc3c08a..fec7548811820 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.mock.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.mock.ts @@ -4,17 +4,20 @@ * you may not use this file except in compliance with the Elastic License. */ import { List, ListArray } from './lists'; +import { ENDPOINT_LIST_ID } from '../../../shared_imports'; export const getListMock = (): List => ({ id: 'some_uuid', + list_id: 'list_id_single', namespace_type: 'single', type: 'detection', }); -export const getListAgnosticMock = (): List => ({ - id: 'some_uuid', +export const getEndpointListMock = (): List => ({ + id: ENDPOINT_LIST_ID, + list_id: ENDPOINT_LIST_ID, namespace_type: 'agnostic', type: 'endpoint', }); -export const getListArrayMock = (): ListArray => [getListMock(), getListAgnosticMock()]; +export const getListArrayMock = (): ListArray => [getListMock(), getEndpointListMock()]; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.test.ts index 56ee4630996fd..7a2c167bfd855 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.test.ts @@ -9,7 +9,7 @@ import { left } from 'fp-ts/lib/Either'; import { foldLeftRight, getPaths } from '../../../test_utils'; -import { getListAgnosticMock, getListMock, getListArrayMock } from './lists.mock'; +import { getEndpointListMock, getListMock, getListArrayMock } from './lists.mock'; import { List, ListArray, @@ -31,7 +31,7 @@ describe('Lists', () => { }); test('it should validate a list with "namespace_type" of "agnostic"', () => { - const payload = getListAgnosticMock(); + const payload = getEndpointListMock(); const decoded = list.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -91,7 +91,7 @@ describe('Lists', () => { const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<{| id: string, type: "detection" | "endpoint", namespace_type: "agnostic" | "single" |}>"', + 'Invalid value "1" supplied to "Array<{| id: NonEmptyString, list_id: NonEmptyString, type: "detection" | "endpoint", namespace_type: "agnostic" | "single" |}>"', ]); expect(message.schema).toEqual({}); }); @@ -122,8 +122,8 @@ describe('Lists', () => { const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "(Array<{| id: string, type: "detection" | "endpoint", namespace_type: "agnostic" | "single" |}> | undefined)"', - 'Invalid value "[1]" supplied to "(Array<{| id: string, type: "detection" | "endpoint", namespace_type: "agnostic" | "single" |}> | undefined)"', + 'Invalid value "1" supplied to "(Array<{| id: NonEmptyString, list_id: NonEmptyString, type: "detection" | "endpoint", namespace_type: "agnostic" | "single" |}> | undefined)"', + 'Invalid value "[1]" supplied to "(Array<{| id: NonEmptyString, list_id: NonEmptyString, type: "detection" | "endpoint", namespace_type: "agnostic" | "single" |}> | undefined)"', ]); expect(message.schema).toEqual({}); }); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.ts index e5aaee6d3ec74..fecdd0761aade 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.ts @@ -8,9 +8,12 @@ import * as t from 'io-ts'; import { exceptionListType, namespaceType } from '../../../shared_imports'; +import { NonEmptyString } from './non_empty_string'; + export const list = t.exact( t.type({ - id: t.string, + id: NonEmptyString, + list_id: NonEmptyString, type: exceptionListType, namespace_type: namespaceType, }) diff --git a/x-pack/plugins/security_solution/common/endpoint/generate_data.test.ts b/x-pack/plugins/security_solution/common/endpoint/generate_data.test.ts index fcea86be4ae9e..debe4a3da6a6f 100644 --- a/x-pack/plugins/security_solution/common/endpoint/generate_data.test.ts +++ b/x-pack/plugins/security_solution/common/endpoint/generate_data.test.ts @@ -3,6 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import _ from 'lodash'; import { EndpointDocGenerator, Event, @@ -79,9 +80,9 @@ describe('data generator', () => { const timestamp = new Date().getTime(); const processEvent = generator.generateEvent({ timestamp }); expect(processEvent['@timestamp']).toEqual(timestamp); - expect(processEvent.event.category).toEqual('process'); + expect(processEvent.event.category).toEqual(['process']); expect(processEvent.event.kind).toEqual('event'); - expect(processEvent.event.type).toEqual('start'); + expect(processEvent.event.type).toEqual(['start']); expect(processEvent.agent).not.toBeNull(); expect(processEvent.host).not.toBeNull(); expect(processEvent.process.entity_id).not.toBeNull(); @@ -94,7 +95,7 @@ describe('data generator', () => { expect(processEvent['@timestamp']).toEqual(timestamp); expect(processEvent.event.category).toEqual('dns'); expect(processEvent.event.kind).toEqual('event'); - expect(processEvent.event.type).toEqual('start'); + expect(processEvent.event.type).toEqual(['start']); expect(processEvent.agent).not.toBeNull(); expect(processEvent.host).not.toBeNull(); expect(processEvent.process.entity_id).not.toBeNull(); @@ -332,6 +333,12 @@ describe('data generator', () => { describe('creates alert ancestor tree', () => { let events: Event[]; + const isCategoryProcess = (event: Event) => { + return ( + _.isEqual(event.event.category, ['process']) || _.isEqual(event.event.category, 'process') + ); + }; + beforeEach(() => { events = generator.createAlertEventAncestry({ ancestors: 3, @@ -343,11 +350,7 @@ describe('data generator', () => { it('with n-1 process events', () => { for (let i = events.length - 2; i > 0; ) { const parentEntityIdOfChild = events[i].process.parent?.entity_id; - for ( - ; - --i >= -1 && (events[i].event.kind !== 'event' || events[i].event.category !== 'process'); - - ) { + for (; --i >= -1 && (events[i].event.kind !== 'event' || !isCategoryProcess(events[i])); ) { // related event - skip it } expect(i).toBeGreaterThanOrEqual(0); @@ -361,7 +364,7 @@ describe('data generator', () => { ; previousProcessEventIndex >= -1 && (events[previousProcessEventIndex].event.kind !== 'event' || - events[previousProcessEventIndex].event.category !== 'process'); + !isCategoryProcess(events[previousProcessEventIndex])); previousProcessEventIndex-- ) { // related event - skip it diff --git a/x-pack/plugins/security_solution/common/endpoint/generate_data.ts b/x-pack/plugins/security_solution/common/endpoint/generate_data.ts index 66e786cb02e63..9a92270fc9c14 100644 --- a/x-pack/plugins/security_solution/common/endpoint/generate_data.ts +++ b/x-pack/plugins/security_solution/common/endpoint/generate_data.ts @@ -35,7 +35,7 @@ interface EventOptions { timestamp?: number; entityID?: string; parentEntityID?: string; - eventType?: string; + eventType?: string | string[]; eventCategory?: string | string[]; processName?: string; ancestry?: string[]; @@ -572,9 +572,9 @@ export class EndpointDocGenerator { }, ...detailRecordForEventType, event: { - category: options.eventCategory ? options.eventCategory : 'process', + category: options.eventCategory ? options.eventCategory : ['process'], kind: 'event', - type: options.eventType ? options.eventType : 'start', + type: options.eventType ? options.eventType : ['start'], id: this.seededUUIDv4(), }, host: this.commonInfo.host, @@ -633,7 +633,12 @@ export class EndpointDocGenerator { // place the event in the right array depending on its category if (event.event.kind === 'event') { - if (event.event.category === 'process') { + if ( + (Array.isArray(event.event.category) && + event.event.category.length === 1 && + event.event.category[0] === 'process') || + event.event.category === 'process' + ) { node.lifecycle.push(event); } else { node.relatedEvents.push(event); @@ -812,8 +817,8 @@ export class EndpointDocGenerator { timestamp: timestamp + termProcessDuration * 1000, entityID: root.process.entity_id, parentEntityID: root.process.parent?.entity_id, - eventCategory: 'process', - eventType: 'end', + eventCategory: ['process'], + eventType: ['end'], }) ); } @@ -838,8 +843,8 @@ export class EndpointDocGenerator { timestamp: timestamp + termProcessDuration * 1000, entityID: ancestor.process.entity_id, parentEntityID: ancestor.process.parent?.entity_id, - eventCategory: 'process', - eventType: 'end', + eventCategory: ['process'], + eventType: ['end'], ancestry: ancestor.process.Ext?.ancestry, ancestryArrayLimit: opts.ancestryArraySize, }) @@ -936,8 +941,8 @@ export class EndpointDocGenerator { timestamp: timestamp + processDuration * 1000, entityID: child.process.entity_id, parentEntityID: child.process.parent?.entity_id, - eventCategory: 'process', - eventType: 'end', + eventCategory: ['process'], + eventType: ['end'], ancestry: child.process.Ext?.ancestry, ancestryArrayLimit: opts.ancestryArraySize, }); @@ -1036,7 +1041,7 @@ export class EndpointDocGenerator { config: { artifact_manifest: { value: { - manifest_version: 'WzAsMF0=', + manifest_version: '1.0.0', schema_version: 'v1', artifacts: {}, }, diff --git a/x-pack/plugins/security_solution/common/endpoint/models/event.test.ts b/x-pack/plugins/security_solution/common/endpoint/models/event.test.ts index a0bf00f0274e6..62f923aa6d793 100644 --- a/x-pack/plugins/security_solution/common/endpoint/models/event.test.ts +++ b/x-pack/plugins/security_solution/common/endpoint/models/event.test.ts @@ -4,38 +4,90 @@ * you may not use this file except in compliance with the Elastic License. */ import { EndpointDocGenerator } from '../generate_data'; -import { descriptiveName } from './event'; +import { descriptiveName, isStart } from './event'; +import { ResolverEvent } from '../types'; -describe('Event descriptive names', () => { +describe('Generated documents', () => { let generator: EndpointDocGenerator; beforeEach(() => { generator = new EndpointDocGenerator('seed'); }); - it('returns the right name for a registry event', () => { - const extensions = { registry: { key: `HKLM/Windows/Software/abc` } }; - const event = generator.generateEvent({ eventCategory: 'registry', extensions }); - expect(descriptiveName(event)).toEqual({ subject: `HKLM/Windows/Software/abc` }); - }); + describe('Event descriptive names', () => { + it('returns the right name for a registry event', () => { + const extensions = { registry: { key: `HKLM/Windows/Software/abc` } }; + const event = generator.generateEvent({ eventCategory: 'registry', extensions }); + expect(descriptiveName(event)).toEqual({ subject: `HKLM/Windows/Software/abc` }); + }); - it('returns the right name for a network event', () => { - const randomIP = `${generator.randomIP()}`; - const extensions = { network: { direction: 'outbound', forwarded_ip: randomIP } }; - const event = generator.generateEvent({ eventCategory: 'network', extensions }); - expect(descriptiveName(event)).toEqual({ subject: `${randomIP}`, descriptor: 'outbound' }); - }); + it('returns the right name for a network event', () => { + const randomIP = `${generator.randomIP()}`; + const extensions = { network: { direction: 'outbound', forwarded_ip: randomIP } }; + const event = generator.generateEvent({ eventCategory: 'network', extensions }); + expect(descriptiveName(event)).toEqual({ subject: `${randomIP}`, descriptor: 'outbound' }); + }); - it('returns the right name for a file event', () => { - const extensions = { file: { path: 'C:\\My Documents\\business\\January\\processName' } }; - const event = generator.generateEvent({ eventCategory: 'file', extensions }); - expect(descriptiveName(event)).toEqual({ - subject: 'C:\\My Documents\\business\\January\\processName', + it('returns the right name for a file event', () => { + const extensions = { file: { path: 'C:\\My Documents\\business\\January\\processName' } }; + const event = generator.generateEvent({ eventCategory: 'file', extensions }); + expect(descriptiveName(event)).toEqual({ + subject: 'C:\\My Documents\\business\\January\\processName', + }); + }); + + it('returns the right name for a dns event', () => { + const extensions = { dns: { question: { name: `${generator.randomIP()}` } } }; + const event = generator.generateEvent({ eventCategory: 'dns', extensions }); + expect(descriptiveName(event)).toEqual({ subject: extensions.dns.question.name }); }); }); - it('returns the right name for a dns event', () => { - const extensions = { dns: { question: { name: `${generator.randomIP()}` } } }; - const event = generator.generateEvent({ eventCategory: 'dns', extensions }); - expect(descriptiveName(event)).toEqual({ subject: extensions.dns.question.name }); + describe('Start events', () => { + it('is a start event when event.type is a string', () => { + const event: ResolverEvent = generator.generateEvent({ + eventType: 'start', + }); + expect(isStart(event)).toBeTruthy(); + }); + + it('is a start event when event.type is an array of strings', () => { + const event: ResolverEvent = generator.generateEvent({ + eventType: ['start'], + }); + expect(isStart(event)).toBeTruthy(); + }); + + it('is a start event when event.type is an array of strings and contains start', () => { + let event: ResolverEvent = generator.generateEvent({ + eventType: ['bogus', 'start', 'creation'], + }); + expect(isStart(event)).toBeTruthy(); + + event = generator.generateEvent({ + eventType: ['start', 'bogus'], + }); + expect(isStart(event)).toBeTruthy(); + }); + + it('is not a start event when event.type is not start', () => { + const event: ResolverEvent = generator.generateEvent({ + eventType: ['end'], + }); + expect(isStart(event)).toBeFalsy(); + }); + + it('is not a start event when event.type is empty', () => { + const event: ResolverEvent = generator.generateEvent({ + eventType: [], + }); + expect(isStart(event)).toBeFalsy(); + }); + + it('is not a start event when event.type is bogus', () => { + const event: ResolverEvent = generator.generateEvent({ + eventType: ['bogus'], + }); + expect(isStart(event)).toBeFalsy(); + }); }); }); diff --git a/x-pack/plugins/security_solution/common/endpoint/models/event.ts b/x-pack/plugins/security_solution/common/endpoint/models/event.ts index f53da8fb1f096..216b5cc028588 100644 --- a/x-pack/plugins/security_solution/common/endpoint/models/event.ts +++ b/x-pack/plugins/security_solution/common/endpoint/models/event.ts @@ -9,10 +9,15 @@ export function isLegacyEvent(event: ResolverEvent): event is LegacyEndpointEven return (event as LegacyEndpointEvent).endgame !== undefined; } -export function isProcessStart(event: ResolverEvent): boolean { +export function isStart(event: ResolverEvent): boolean { if (isLegacyEvent(event)) { return event.event?.type === 'process_start' || event.event?.action === 'fork_event'; } + + if (Array.isArray(event.event.type)) { + return event.event.type.includes('start'); + } + return event.event.type === 'start'; } diff --git a/x-pack/plugins/security_solution/common/endpoint/schema/common.ts b/x-pack/plugins/security_solution/common/endpoint/schema/common.ts index 8f2ea1f8a6452..1c910927a7afa 100644 --- a/x-pack/plugins/security_solution/common/endpoint/schema/common.ts +++ b/x-pack/plugins/security_solution/common/endpoint/schema/common.ts @@ -23,8 +23,6 @@ export const encryptionAlgorithm = t.keyof({ export const identifier = t.string; -export const manifestVersion = t.string; - export const manifestSchemaVersion = t.keyof({ v1: null, }); @@ -34,4 +32,7 @@ export const relativeUrl = t.string; export const sha256 = t.string; +export const semanticVersion = t.string; +export type SemanticVersion = t.TypeOf; + export const size = t.number; diff --git a/x-pack/plugins/security_solution/common/endpoint/schema/manifest.ts b/x-pack/plugins/security_solution/common/endpoint/schema/manifest.ts index f8bb8b70f2d5b..f03db881837d5 100644 --- a/x-pack/plugins/security_solution/common/endpoint/schema/manifest.ts +++ b/x-pack/plugins/security_solution/common/endpoint/schema/manifest.ts @@ -11,9 +11,9 @@ import { encryptionAlgorithm, identifier, manifestSchemaVersion, - manifestVersion, relativeUrl, sha256, + semanticVersion, size, } from './common'; @@ -50,7 +50,7 @@ export type ManifestEntryDispatchSchema = t.TypeOf { before(() => { loginAndWaitForPage(HOSTS_URL); diff --git a/x-pack/plugins/security_solution/cypress/integration/value_lists.spec.ts b/x-pack/plugins/security_solution/cypress/integration/value_lists.spec.ts new file mode 100644 index 0000000000000..2804a8ac2ea8c --- /dev/null +++ b/x-pack/plugins/security_solution/cypress/integration/value_lists.spec.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { loginAndWaitForPageWithoutDateRange } from '../tasks/login'; +import { DETECTIONS_URL } from '../urls/navigation'; +import { + waitForAlertsPanelToBeLoaded, + waitForAlertsIndexToBeCreated, + goToManageAlertsDetectionRules, +} from '../tasks/alerts'; +import { + waitForListsIndexToBeCreated, + waitForValueListsModalToBeLoaded, + openValueListsModal, + selectValueListsFile, + uploadValueList, +} from '../tasks/lists'; +import { VALUE_LISTS_TABLE, VALUE_LISTS_ROW } from '../screens/lists'; + +describe('value lists', () => { + describe('management modal', () => { + it('creates a keyword list from an uploaded file', () => { + loginAndWaitForPageWithoutDateRange(DETECTIONS_URL); + waitForAlertsPanelToBeLoaded(); + waitForAlertsIndexToBeCreated(); + waitForListsIndexToBeCreated(); + goToManageAlertsDetectionRules(); + waitForValueListsModalToBeLoaded(); + openValueListsModal(); + selectValueListsFile(); + uploadValueList(); + + cy.get(VALUE_LISTS_TABLE) + .find(VALUE_LISTS_ROW) + .should(($row) => { + expect($row.text()).to.contain('value_list.txt'); + }); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/cypress/screens/lists.ts b/x-pack/plugins/security_solution/cypress/screens/lists.ts new file mode 100644 index 0000000000000..35205a27e5a3c --- /dev/null +++ b/x-pack/plugins/security_solution/cypress/screens/lists.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 VALUE_LISTS_MODAL_ACTIVATOR = '[data-test-subj="open-value-lists-modal-button"]'; +export const VALUE_LISTS_TABLE = '[data-test-subj="value-lists-table"]'; +export const VALUE_LISTS_ROW = '.euiTableRow'; +export const VALUE_LIST_FILE_PICKER = '[data-test-subj="value-list-file-picker"]'; +export const VALUE_LIST_FILE_UPLOAD_BUTTON = '[data-test-subj="value-lists-form-import-action"]'; diff --git a/x-pack/plugins/security_solution/cypress/support/commands.js b/x-pack/plugins/security_solution/cypress/support/commands.js index 8b75f068a53da..789759643e319 100644 --- a/x-pack/plugins/security_solution/cypress/support/commands.js +++ b/x-pack/plugins/security_solution/cypress/support/commands.js @@ -39,3 +39,22 @@ Cypress.Commands.add('stubSecurityApi', function (dataFileName) { cy.fixture(dataFileName).as(`${dataFileName}JSON`); cy.route('POST', 'api/solutions/security/graphql', `@${dataFileName}JSON`); }); + +Cypress.Commands.add( + 'attachFile', + { + prevSubject: 'element', + }, + (input, fileName, fileType = 'text/plain') => { + cy.fixture(fileName) + .then((content) => Cypress.Blob.base64StringToBlob(content, fileType)) + .then((blob) => { + const testFile = new File([blob], fileName, { type: fileType }); + const dataTransfer = new DataTransfer(); + + dataTransfer.items.add(testFile); + input[0].files = dataTransfer.files; + return input; + }); + } +); diff --git a/x-pack/plugins/security_solution/cypress/support/index.d.ts b/x-pack/plugins/security_solution/cypress/support/index.d.ts index 12c11ffd27750..906e526e2c4a0 100644 --- a/x-pack/plugins/security_solution/cypress/support/index.d.ts +++ b/x-pack/plugins/security_solution/cypress/support/index.d.ts @@ -7,5 +7,6 @@ declare namespace Cypress { interface Chainable { stubSecurityApi(dataFileName: string): Chainable; + attachFile(fileName: string, fileType?: string): Chainable; } } diff --git a/x-pack/plugins/security_solution/cypress/tasks/common.ts b/x-pack/plugins/security_solution/cypress/tasks/common.ts index a385ad78f63b7..e16db54599981 100644 --- a/x-pack/plugins/security_solution/cypress/tasks/common.ts +++ b/x-pack/plugins/security_solution/cypress/tasks/common.ts @@ -23,14 +23,14 @@ export const drag = (subject: JQuery) => { clientY: subjectLocation.top, force: true, }) - .wait(1000) + .wait(3000) .trigger('mousemove', { button: primaryButton, clientX: subjectLocation.left + dndSloppyClickDetectionThreshold, clientY: subjectLocation.top, force: true, }) - .wait(1000); + .wait(3000); }; /** Drags the subject being dragged on the specified drop target, but does not drop it */ @@ -44,9 +44,9 @@ export const dragWithoutDrop = (dropTarget: JQuery) => { export const drop = (dropTarget: JQuery) => { cy.wrap(dropTarget) .trigger('mousemove', { button: primaryButton, force: true }) - .wait(1000) + .wait(3000) .trigger('mouseup', { force: true }) - .wait(1000); + .wait(3000); }; export const reload = (afterReload: () => void) => { diff --git a/x-pack/plugins/security_solution/cypress/tasks/es_archiver.ts b/x-pack/plugins/security_solution/cypress/tasks/es_archiver.ts index 5a09a2f753dc4..c0436603a256a 100644 --- a/x-pack/plugins/security_solution/cypress/tasks/es_archiver.ts +++ b/x-pack/plugins/security_solution/cypress/tasks/es_archiver.ts @@ -6,7 +6,7 @@ export const esArchiverLoadEmptyKibana = () => { cy.exec( - `node ../../../scripts/es_archiver empty_kibana load empty--dir ../../test/security_solution_cypress/es_archives --config ../../../test/functional/config.js --es-url ${Cypress.env( + `node ../../../scripts/es_archiver load empty_kibana --dir ../../test/security_solution_cypress/es_archives --config ../../../test/functional/config.js --es-url ${Cypress.env( 'ELASTICSEARCH_URL' )} --kibana-url ${Cypress.config().baseUrl}` ); @@ -30,7 +30,7 @@ export const esArchiverUnload = (folder: string) => { export const esArchiverUnloadEmptyKibana = () => { cy.exec( - `node ../../../scripts/es_archiver unload empty_kibana empty--dir ../../test/security_solution_cypress/es_archives --config ../../../test/functional/config.js --es-url ${Cypress.env( + `node ../../../scripts/es_archiver unload empty_kibana --dir ../../test/security_solution_cypress/es_archives --config ../../../test/functional/config.js --es-url ${Cypress.env( 'ELASTICSEARCH_URL' )} --kibana-url ${Cypress.config().baseUrl}` ); diff --git a/x-pack/plugins/security_solution/cypress/tasks/hosts/events.ts b/x-pack/plugins/security_solution/cypress/tasks/hosts/events.ts index 57c819d967883..1d2c4aa8d0834 100644 --- a/x-pack/plugins/security_solution/cypress/tasks/hosts/events.ts +++ b/x-pack/plugins/security_solution/cypress/tasks/hosts/events.ts @@ -68,7 +68,7 @@ export const dragAndDropColumn = ({ .eq(column) .then((header) => drag(header)); - cy.wait(3000); // wait for DOM updates before moving + cy.wait(5000); // wait for DOM updates before moving cy.get(DRAGGABLE_HEADER) .eq(newPosition) diff --git a/x-pack/plugins/security_solution/cypress/tasks/lists.ts b/x-pack/plugins/security_solution/cypress/tasks/lists.ts new file mode 100644 index 0000000000000..638c69c087adf --- /dev/null +++ b/x-pack/plugins/security_solution/cypress/tasks/lists.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 { + VALUE_LISTS_MODAL_ACTIVATOR, + VALUE_LIST_FILE_PICKER, + VALUE_LIST_FILE_UPLOAD_BUTTON, +} from '../screens/lists'; + +export const waitForListsIndexToBeCreated = () => { + cy.request({ url: '/api/lists/index', retryOnStatusCodeFailure: true }).then((response) => { + if (response.status !== 200) { + cy.wait(7500); + } + }); +}; + +export const waitForValueListsModalToBeLoaded = () => { + cy.get(VALUE_LISTS_MODAL_ACTIVATOR).should('exist'); + cy.get(VALUE_LISTS_MODAL_ACTIVATOR).should('not.be.disabled'); +}; + +export const openValueListsModal = () => { + cy.get(VALUE_LISTS_MODAL_ACTIVATOR).click(); +}; + +export const selectValueListsFile = () => { + cy.get(VALUE_LIST_FILE_PICKER).attachFile('value_list.txt').trigger('change', { force: true }); +}; + +export const uploadValueList = () => { + cy.get(VALUE_LIST_FILE_UPLOAD_BUTTON).click(); +}; diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/columns.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/columns.tsx index 162966a2df28a..5c6c72477bf1f 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/columns.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/columns.tsx @@ -6,6 +6,7 @@ import React, { useCallback } from 'react'; import { EuiAvatar, + EuiBadgeGroup, EuiBadge, EuiLink, EuiTableActionsColumnType, @@ -19,7 +20,6 @@ import { getEmptyTagValue } from '../../../common/components/empty_value'; import { Case } from '../../containers/types'; import { FormattedRelativePreferenceDate } from '../../../common/components/formatted_date'; import { CaseDetailsLink } from '../../../common/components/links'; -import { TruncatableText } from '../../../common/components/truncatable_text'; import * as i18n from './translations'; export type CasesColumns = @@ -35,6 +35,10 @@ const Spacer = styled.span` margin-left: ${({ theme }) => theme.eui.paddingSizes.s}; `; +const TagWrapper = styled(EuiBadgeGroup)` + width: 100%; +`; + const renderStringField = (field: string, dataTestSubj: string) => field != null ? {field} : getEmptyTagValue(); @@ -96,7 +100,7 @@ export const getCasesColumns = ( render: (tags: Case['tags']) => { if (tags != null && tags.length > 0) { return ( - + {tags.map((tag: string, i: number) => ( ))} - + ); } return getEmptyTagValue(); diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx index 23cabd6778cc0..f5ed151ebac3c 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx @@ -14,6 +14,8 @@ import { TestProviders } from '../../../common/mock'; import { useGetCasesMockState } from '../../containers/mock'; import * as i18n from './translations'; +import { useKibana } from '../../../common/lib/kibana'; +import { createUseKibanaMock } from '../../../common/mock/kibana_react'; import { getEmptyTagValue } from '../../../common/components/empty_value'; import { useDeleteCases } from '../../containers/use_delete_cases'; import { useGetCases } from '../../containers/use_get_cases'; @@ -26,6 +28,7 @@ jest.mock('../../containers/use_delete_cases'); jest.mock('../../containers/use_get_cases'); jest.mock('../../containers/use_get_cases_status'); +const useKibanaMock = useKibana as jest.Mock; const useDeleteCasesMock = useDeleteCases as jest.Mock; const useGetCasesMock = useGetCases as jest.Mock; const useGetCasesStatusMock = useGetCasesStatus as jest.Mock; @@ -33,6 +36,8 @@ const useUpdateCasesMock = useUpdateCases as jest.Mock; jest.mock('../../../common/components/link_to'); +jest.mock('../../../common/lib/kibana'); + describe('AllCases', () => { const dispatchResetIsDeleted = jest.fn(); const dispatchResetIsUpdated = jest.fn(); @@ -45,6 +50,7 @@ describe('AllCases', () => { const setSelectedCases = jest.fn(); const updateBulkStatus = jest.fn(); const fetchCasesStatus = jest.fn(); + const onRowClick = jest.fn(); const emptyTag = getEmptyTagValue().props.children; const defaultGetCases = { @@ -77,6 +83,9 @@ describe('AllCases', () => { dispatchResetIsUpdated, updateBulkStatus, }; + + let navigateToApp: jest.Mock; + /* eslint-disable no-console */ // Silence until enzyme fixed to use ReactTestUtils.act() const originalError = console.error; @@ -89,10 +98,20 @@ describe('AllCases', () => { /* eslint-enable no-console */ beforeEach(() => { jest.resetAllMocks(); - useUpdateCasesMock.mockImplementation(() => defaultUpdateCases); - useGetCasesMock.mockImplementation(() => defaultGetCases); - useDeleteCasesMock.mockImplementation(() => defaultDeleteCases); - useGetCasesStatusMock.mockImplementation(() => defaultCasesStatus); + navigateToApp = jest.fn(); + const kibanaMock = createUseKibanaMock()(); + useKibanaMock.mockReturnValue({ + ...kibanaMock, + services: { + application: { + navigateToApp, + }, + }, + }); + useUpdateCasesMock.mockReturnValue(defaultUpdateCases); + useGetCasesMock.mockReturnValue(defaultGetCases); + useDeleteCasesMock.mockReturnValue(defaultDeleteCases); + useGetCasesStatusMock.mockReturnValue(defaultCasesStatus); moment.tz.setDefault('UTC'); }); it('should render AllCases', () => { @@ -125,7 +144,7 @@ describe('AllCases', () => { ); }); it('should render empty fields', () => { - useGetCasesMock.mockImplementation(() => ({ + useGetCasesMock.mockReturnValue({ ...defaultGetCases, data: { ...defaultGetCases.data, @@ -141,7 +160,7 @@ describe('AllCases', () => { }, ], }, - })); + }); const wrapper = mount( @@ -202,10 +221,10 @@ describe('AllCases', () => { }); }); it('opens case when row action icon clicked', () => { - useGetCasesMock.mockImplementation(() => ({ + useGetCasesMock.mockReturnValue({ ...defaultGetCases, filterOptions: { ...defaultGetCases.filterOptions, status: 'closed' }, - })); + }); const wrapper = mount( @@ -223,10 +242,11 @@ describe('AllCases', () => { }); }); it('Bulk delete', () => { - useGetCasesMock.mockImplementation(() => ({ + useGetCasesMock.mockReturnValue({ ...defaultGetCases, selectedCases: useGetCasesMockState.data.cases, - })); + }); + useDeleteCasesMock .mockReturnValueOnce({ ...defaultDeleteCases, @@ -257,10 +277,10 @@ describe('AllCases', () => { ); }); it('Bulk close status update', () => { - useGetCasesMock.mockImplementation(() => ({ + useGetCasesMock.mockReturnValue({ ...defaultGetCases, selectedCases: useGetCasesMockState.data.cases, - })); + }); const wrapper = mount( @@ -272,14 +292,14 @@ describe('AllCases', () => { expect(updateBulkStatus).toBeCalledWith(useGetCasesMockState.data.cases, 'closed'); }); it('Bulk open status update', () => { - useGetCasesMock.mockImplementation(() => ({ + useGetCasesMock.mockReturnValue({ ...defaultGetCases, selectedCases: useGetCasesMockState.data.cases, filterOptions: { ...defaultGetCases.filterOptions, status: 'closed', }, - })); + }); const wrapper = mount( @@ -291,10 +311,10 @@ describe('AllCases', () => { expect(updateBulkStatus).toBeCalledWith(useGetCasesMockState.data.cases, 'open'); }); it('isDeleted is true, refetch', () => { - useDeleteCasesMock.mockImplementation(() => ({ + useDeleteCasesMock.mockReturnValue({ ...defaultDeleteCases, isDeleted: true, - })); + }); mount( @@ -306,10 +326,10 @@ describe('AllCases', () => { expect(dispatchResetIsDeleted).toBeCalled(); }); it('isUpdated is true, refetch', () => { - useUpdateCasesMock.mockImplementation(() => ({ + useUpdateCasesMock.mockReturnValue({ ...defaultUpdateCases, isUpdated: true, - })); + }); mount( @@ -320,4 +340,96 @@ describe('AllCases', () => { expect(fetchCasesStatus).toBeCalled(); expect(dispatchResetIsUpdated).toBeCalled(); }); + + it('should not render header when modal=true', () => { + const wrapper = mount( + + + + ); + + expect(wrapper.find('[data-test-subj="all-cases-header"]').exists()).toBe(false); + }); + + it('should not render table utility bar when modal=true', () => { + const wrapper = mount( + + + + ); + + expect(wrapper.find('[data-test-subj="case-table-utility-bar-actions"]').exists()).toBe(false); + }); + + it('case table should not be selectable when modal=true', () => { + const wrapper = mount( + + + + ); + + expect(wrapper.find('[data-test-subj="cases-table"]').first().prop('isSelectable')).toBe(false); + }); + + it('should call onRowClick with no cases and modal=true', () => { + useGetCasesMock.mockReturnValue({ + ...defaultGetCases, + data: { + ...defaultGetCases.data, + total: 0, + cases: [], + }, + }); + + const wrapper = mount( + + + + ); + + wrapper.find('[data-test-subj="cases-table-add-case"]').first().simulate('click'); + expect(onRowClick).toHaveBeenCalled(); + }); + + it('should call navigateToApp with no cases and modal=false', () => { + useGetCasesMock.mockReturnValue({ + ...defaultGetCases, + data: { + ...defaultGetCases.data, + total: 0, + cases: [], + }, + }); + + const wrapper = mount( + + + + ); + + wrapper.find('[data-test-subj="cases-table-add-case"]').first().simulate('click'); + expect(navigateToApp).toHaveBeenCalledWith('securitySolution:case', { path: '/create' }); + }); + + it('should call onRowClick when clicking a case with modal=true', () => { + const wrapper = mount( + + + + ); + + wrapper.find('[data-test-subj="cases-table-row-1"]').first().simulate('click'); + expect(onRowClick).toHaveBeenCalledWith('1'); + }); + + it('should NOT call onRowClick when clicking a case with modal=true', () => { + const wrapper = mount( + + + + ); + + wrapper.find('[data-test-subj="cases-table-row-1"]').first().simulate('click'); + expect(onRowClick).not.toHaveBeenCalled(); + }); }); diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx index f46dd9e858c7f..42a87de2aa07b 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx @@ -3,7 +3,6 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -/* eslint-disable react-hooks/exhaustive-deps */ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { EuiBasicTable, @@ -16,7 +15,7 @@ import { EuiTableSortingType, } from '@elastic/eui'; import { EuiTableSelectionType } from '@elastic/eui/src/components/basic_table/table_types'; -import { isEmpty } from 'lodash/fp'; +import { isEmpty, memoize } from 'lodash/fp'; import styled, { css } from 'styled-components'; import * as i18n from './translations'; @@ -137,7 +136,7 @@ export const AllCases = React.memo( (refetchFilter: () => void) => { filterRefetch.current = refetchFilter; }, - [filterRefetch.current] + [filterRefetch] ); const refreshCases = useCallback( (dataRefresh = true) => { @@ -149,7 +148,7 @@ export const AllCases = React.memo( filterRefetch.current(); } }, - [filterOptions, queryParams, filterRefetch.current] + [filterRefetch, refetchCases, setSelectedCases, fetchCasesStatus] ); useEffect(() => { @@ -161,7 +160,7 @@ export const AllCases = React.memo( refreshCases(); dispatchResetIsUpdated(); } - }, [isDeleted, isUpdated]); + }, [isDeleted, isUpdated, refreshCases, dispatchResetIsDeleted, dispatchResetIsUpdated]); const confirmDeleteModal = useMemo( () => ( ( )} /> ), - [deleteBulk, deleteThisCase, isDisplayConfirmDeleteModal] + [ + deleteBulk, + deleteThisCase, + isDisplayConfirmDeleteModal, + handleToggleModal, + handleOnDeleteConfirm, + ] ); - const toggleDeleteModal = useCallback((deleteCase: Case) => { - handleToggleModal(); - setDeleteThisCase(deleteCase); - }, []); + const toggleDeleteModal = useCallback( + (deleteCase: Case) => { + handleToggleModal(); + setDeleteThisCase(deleteCase); + }, + [handleToggleModal] + ); const toggleBulkDeleteModal = useCallback( (caseIds: string[]) => { @@ -195,14 +203,14 @@ export const AllCases = React.memo( const convertToDeleteCases: DeleteCase[] = caseIds.map((id) => ({ id })); setDeleteBulk(convertToDeleteCases); }, - [selectedCases] + [selectedCases, setDeleteBulk, handleToggleModal] ); const handleUpdateCaseStatus = useCallback( (status: string) => { updateBulkStatus(selectedCases, status); }, - [selectedCases] + [selectedCases, updateBulkStatus] ); const selectedCaseIds = useMemo( @@ -223,7 +231,7 @@ export const AllCases = React.memo( })} /> ), - [selectedCaseIds, filterOptions.status, toggleBulkDeleteModal] + [selectedCaseIds, filterOptions.status, toggleBulkDeleteModal, handleUpdateCaseStatus] ); const handleDispatchUpdate = useCallback( (args: Omit) => { @@ -278,7 +286,7 @@ export const AllCases = React.memo( setQueryParams(newQueryParams); refreshCases(false); }, - [queryParams] + [queryParams, refreshCases, setQueryParams] ); const onFilterChangedCallback = useCallback( @@ -291,7 +299,7 @@ export const AllCases = React.memo( setFilters(newFilterOptions); refreshCases(false); }, - [filterOptions, queryParams] + [refreshCases, setQueryParams, setFilters] ); const memoizedGetCasesColumns = useMemo( @@ -311,9 +319,10 @@ export const AllCases = React.memo( const sorting: EuiTableSortingType = { sort: { field: queryParams.sortField, direction: queryParams.sortOrder }, }; + const euiBasicTableSelectionProps = useMemo>( () => ({ onSelectionChange: setSelectedCases }), - [selectedCases] + [setSelectedCases] ); const isCasesLoading = useMemo( () => loading.indexOf('cases') > -1 || loading.indexOf('caseUpdate') > -1, @@ -322,6 +331,35 @@ export const AllCases = React.memo( const isDataEmpty = useMemo(() => data.total === 0, [data]); const TableWrap = useMemo(() => (isModal ? 'span' : Panel), [isModal]); + + const onTableRowClick = useMemo( + () => + memoize<(id: string) => () => void>((id) => () => { + if (onRowClick) { + onRowClick(id); + } + }), + [onRowClick] + ); + + const tableRowProps = useCallback( + (item) => { + const rowProps = { + 'data-test-subj': `cases-table-row-${item.id}`, + }; + + if (isModal) { + return { + ...rowProps, + onClick: onTableRowClick(item.id), + }; + } + + return rowProps; + }, + [isModal, onTableRowClick] + ); + return ( <> {!isEmpty(actionsErrors) && ( @@ -329,7 +367,13 @@ export const AllCases = React.memo( )} {!isModal && ( - + ( {!isModal && ( - + {i18n.SHOWING_SELECTED_CASES(selectedCases.length)} @@ -441,6 +485,7 @@ export const AllCases = React.memo( onClick={goToCreateCase} href={formatUrl(getCreateCaseUrl())} iconType="plusInCircle" + data-test-subj="cases-table-add-case" > {i18n.ADD_NEW_CASE} @@ -449,17 +494,7 @@ export const AllCases = React.memo( } onChange={tableOnChangeCallback} pagination={memoizedPagination} - rowProps={(item) => - isModal - ? { - onClick: () => { - if (onRowClick != null) { - onRowClick(item.id); - } - }, - } - : {} - } + rowProps={tableRowProps} selection={userCanCrud && !isModal ? euiBasicTableSelectionProps : undefined} sorting={sorting} /> diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx index d8f2e5293ee1b..efbe3e667c27b 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx @@ -12,6 +12,7 @@ import { EuiModalHeaderTitle, EuiOverlayMask, } from '@elastic/eui'; + import { useGetUserSavedObjectPermissions } from '../../../common/lib/kibana'; import { AllCases } from '../all_cases'; import * as i18n from './translations'; diff --git a/x-pack/plugins/security_solution/public/cases/components/case_view/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/case_view/index.test.tsx index 278b972ada970..e1d7d98ba8c51 100644 --- a/x-pack/plugins/security_solution/public/cases/components/case_view/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/case_view/index.test.tsx @@ -119,10 +119,16 @@ describe('CaseView ', () => { ); expect( wrapper - .find(`[data-test-subj="case-view-tag-list"] [data-test-subj="case-tag"]`) + .find(`[data-test-subj="case-view-tag-list"] [data-test-subj="case-tag-coke"]`) .first() .text() ).toEqual(data.tags[0]); + expect( + wrapper + .find(`[data-test-subj="case-view-tag-list"] [data-test-subj="case-tag-pepsi"]`) + .first() + .text() + ).toEqual(data.tags[1]); expect(wrapper.find(`[data-test-subj="case-view-username"]`).first().text()).toEqual( data.createdBy.username ); diff --git a/x-pack/plugins/security_solution/public/cases/components/tag_list/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/tag_list/index.test.tsx index 939ddfde8b9dc..7c3fcde687033 100644 --- a/x-pack/plugins/security_solution/public/cases/components/tag_list/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/tag_list/index.test.tsx @@ -102,14 +102,14 @@ describe('TagList ', () => { ); - expect(wrapper.find(`[data-test-subj="case-tag"]`).last().exists()).toBeTruthy(); + expect(wrapper.find(`[data-test-subj="case-tag-pepsi"]`).last().exists()).toBeTruthy(); wrapper.find(`[data-test-subj="tag-list-edit-button"]`).last().simulate('click'); await act(async () => { - expect(wrapper.find(`[data-test-subj="case-tag"]`).last().exists()).toBeFalsy(); + expect(wrapper.find(`[data-test-subj="case-tag-pepsi"]`).last().exists()).toBeFalsy(); wrapper.find(`[data-test-subj="edit-tags-cancel"]`).last().simulate('click'); await waitFor(() => { wrapper.update(); - expect(wrapper.find(`[data-test-subj="case-tag"]`).last().exists()).toBeTruthy(); + expect(wrapper.find(`[data-test-subj="case-tag-pepsi"]`).last().exists()).toBeTruthy(); }); }); }); diff --git a/x-pack/plugins/security_solution/public/cases/components/tag_list/index.tsx b/x-pack/plugins/security_solution/public/cases/components/tag_list/index.tsx index 7bb10c743a418..b5af1934f379c 100644 --- a/x-pack/plugins/security_solution/public/cases/components/tag_list/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/tag_list/index.tsx @@ -10,6 +10,7 @@ import { EuiHorizontalRule, EuiFlexGroup, EuiFlexItem, + EuiBadgeGroup, EuiBadge, EuiButton, EuiButtonEmpty, @@ -98,15 +99,15 @@ export const TagList = React.memo( {tags.length === 0 && !isEditTags &&

{i18n.NO_TAGS}

} - {tags.length > 0 && - !isEditTags && - tags.map((tag, key) => ( - - + + {tags.length > 0 && + !isEditTags && + tags.map((tag, key) => ( + {tag} - - ))} + ))} + {isEditTags && ( diff --git a/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/all_cases_modal.test.tsx b/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/all_cases_modal.test.tsx new file mode 100644 index 0000000000000..6039fec2464cc --- /dev/null +++ b/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/all_cases_modal.test.tsx @@ -0,0 +1,74 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { mount } from 'enzyme'; +import React from 'react'; +import '../../../common/mock/match_media'; +import { AllCasesModal } from './all_cases_modal'; +import { TestProviders } from '../../../common/mock'; + +jest.mock('../all_cases', () => { + const AllCases = () => { + return <>; + }; + return { AllCases }; +}); + +jest.mock('../../../common/lib/kibana', () => { + const originalModule = jest.requireActual('../../../common/lib/kibana'); + return { + ...originalModule, + useGetUserSavedObjectPermissions: jest.fn(), + }; +}); + +const onCloseCaseModal = jest.fn(); +const onRowClick = jest.fn(); +const defaultProps = { + onCloseCaseModal, + onRowClick, +}; + +describe('AllCasesModal', () => { + beforeEach(() => { + jest.resetAllMocks(); + }); + + it('renders', () => { + const wrapper = mount( + + + + ); + + expect(wrapper.find(`[data-test-subj='all-cases-modal']`).exists()).toBeTruthy(); + }); + + it('Closing modal calls onCloseCaseModal', () => { + const wrapper = mount( + + + + ); + + wrapper.find('.euiModal__closeIcon').first().simulate('click'); + expect(onCloseCaseModal).toBeCalled(); + }); + + it('pass the correct props to AllCases component', () => { + const wrapper = mount( + + + + ); + + const props = wrapper.find('AllCases').props(); + expect(props).toEqual({ + userCanCrud: false, + onRowClick, + isModal: true, + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/all_cases_modal.tsx b/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/all_cases_modal.tsx new file mode 100644 index 0000000000000..7a12f9211e969 --- /dev/null +++ b/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/all_cases_modal.tsx @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { memo } from 'react'; +import { + EuiModal, + EuiModalBody, + EuiModalHeader, + EuiModalHeaderTitle, + EuiOverlayMask, +} from '@elastic/eui'; + +import { useGetUserSavedObjectPermissions } from '../../../common/lib/kibana'; +import { AllCases } from '../all_cases'; +import * as i18n from './translations'; + +export interface AllCasesModalProps { + onCloseCaseModal: () => void; + onRowClick: (id?: string) => void; +} + +const AllCasesModalComponent: React.FC = ({ + onCloseCaseModal, + onRowClick, +}: AllCasesModalProps) => { + const userPermissions = useGetUserSavedObjectPermissions(); + const userCanCrud = userPermissions?.crud ?? false; + return ( + + + + {i18n.SELECT_CASE_TITLE} + + + + + + + ); +}; + +export const AllCasesModal = memo(AllCasesModalComponent); + +AllCasesModal.displayName = 'AllCasesModal'; diff --git a/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/index.test.tsx new file mode 100644 index 0000000000000..b5bf68cbf6dc8 --- /dev/null +++ b/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/index.test.tsx @@ -0,0 +1,143 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +/* eslint-disable react/display-name */ + +import React from 'react'; +import { renderHook, act } from '@testing-library/react-hooks'; + +import { useKibana } from '../../../common/lib/kibana'; +import '../../../common/mock/match_media'; +import { TimelineId } from '../../../../common/types/timeline'; +import { useAllCasesModal, UseAllCasesModalProps, UseAllCasesModalReturnedValues } from '.'; +import { TestProviders } from '../../../common/mock'; +import { createUseKibanaMock } from '../../../common/mock/kibana_react'; + +jest.mock('../../../common/lib/kibana'); + +const useKibanaMock = useKibana as jest.Mock; + +describe('useAllCasesModal', () => { + const navigateToApp = jest.fn(() => Promise.resolve()); + + beforeEach(() => { + jest.clearAllMocks(); + const kibanaMock = createUseKibanaMock()(); + useKibanaMock.mockImplementation(() => ({ + ...kibanaMock, + services: { + application: { + navigateToApp, + }, + }, + })); + }); + + it('init', async () => { + const { result } = renderHook( + () => useAllCasesModal({ timelineId: TimelineId.test }), + { + wrapper: ({ children }) => {children}, + } + ); + + expect(result.current.showModal).toBe(false); + }); + + it('opens the modal', async () => { + const { result } = renderHook( + () => useAllCasesModal({ timelineId: TimelineId.test }), + { + wrapper: ({ children }) => {children}, + } + ); + + act(() => { + result.current.onOpenModal(); + }); + + expect(result.current.showModal).toBe(true); + }); + + it('closes the modal', async () => { + const { result } = renderHook( + () => useAllCasesModal({ timelineId: TimelineId.test }), + { + wrapper: ({ children }) => {children}, + } + ); + + act(() => { + result.current.onOpenModal(); + result.current.onCloseModal(); + }); + + expect(result.current.showModal).toBe(false); + }); + + it('returns a memoized value', async () => { + const { result, rerender } = renderHook( + () => useAllCasesModal({ timelineId: TimelineId.test }), + { + wrapper: ({ children }) => {children}, + } + ); + + const result1 = result.current; + act(() => rerender()); + const result2 = result.current; + + expect(result1).toBe(result2); + }); + + it('closes the modal when clicking a row', async () => { + const { result } = renderHook( + () => useAllCasesModal({ timelineId: TimelineId.test }), + { + wrapper: ({ children }) => {children}, + } + ); + + act(() => { + result.current.onOpenModal(); + result.current.onRowClick(); + }); + + expect(result.current.showModal).toBe(false); + }); + + it('navigates to the correct path without id', async () => { + const { result } = renderHook( + () => useAllCasesModal({ timelineId: TimelineId.test }), + { + wrapper: ({ children }) => {children}, + } + ); + + act(() => { + result.current.onOpenModal(); + result.current.onRowClick(); + }); + + expect(navigateToApp).toHaveBeenCalledWith('securitySolution:case', { path: '/create' }); + }); + + it('navigates to the correct path with id', async () => { + const { result } = renderHook( + () => useAllCasesModal({ timelineId: TimelineId.test }), + { + wrapper: ({ children }) => {children}, + } + ); + + act(() => { + result.current.onOpenModal(); + result.current.onRowClick('case-id'); + }); + + expect(navigateToApp).toHaveBeenCalledWith('securitySolution:case', { path: '/case-id' }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/index.tsx b/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/index.tsx new file mode 100644 index 0000000000000..f7fc7963b3844 --- /dev/null +++ b/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/index.tsx @@ -0,0 +1,85 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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, useCallback, useMemo } from 'react'; + +import { useDispatch, useSelector } from 'react-redux'; +import { APP_ID } from '../../../../common/constants'; +import { SecurityPageName } from '../../../app/types'; +import { useKibana } from '../../../common/lib/kibana'; +import { getCaseDetailsUrl, getCreateCaseUrl } from '../../../common/components/link_to'; +import { State } from '../../../common/store'; +import { setInsertTimeline } from '../../../timelines/store/timeline/actions'; +import { timelineSelectors } from '../../../timelines/store/timeline'; + +import { AllCasesModal } from './all_cases_modal'; + +export interface UseAllCasesModalProps { + timelineId: string; +} + +export interface UseAllCasesModalReturnedValues { + Modal: React.FC; + showModal: boolean; + onCloseModal: () => void; + onOpenModal: () => void; + onRowClick: (id?: string) => void; +} + +export const useAllCasesModal = ({ + timelineId, +}: UseAllCasesModalProps): UseAllCasesModalReturnedValues => { + const dispatch = useDispatch(); + const { navigateToApp } = useKibana().services.application; + const timeline = useSelector((state: State) => + timelineSelectors.selectTimeline(state, timelineId) + ); + + const [showModal, setShowModal] = useState(false); + const onCloseModal = useCallback(() => setShowModal(false), []); + const onOpenModal = useCallback(() => setShowModal(true), []); + + const onRowClick = useCallback( + async (id?: string) => { + onCloseModal(); + + await navigateToApp(`${APP_ID}:${SecurityPageName.case}`, { + path: id != null ? getCaseDetailsUrl({ id }) : getCreateCaseUrl(), + }); + + dispatch( + setInsertTimeline({ + graphEventId: timeline.graphEventId ?? '', + timelineId, + timelineSavedObjectId: timeline.savedObjectId ?? '', + timelineTitle: timeline.title, + }) + ); + }, + // dispatch causes unnecessary rerenders + // eslint-disable-next-line react-hooks/exhaustive-deps + [timeline, navigateToApp, onCloseModal, timelineId] + ); + + const Modal: React.FC = useCallback( + () => + showModal ? : null, + [onCloseModal, onRowClick, showModal] + ); + + const state = useMemo( + () => ({ + Modal, + showModal, + onCloseModal, + onOpenModal, + onRowClick, + }), + [showModal, onCloseModal, onOpenModal, onRowClick, Modal] + ); + + return state; +}; diff --git a/x-pack/plugins/canvas/public/components/border_connection/index.js b/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/translations.ts similarity index 56% rename from x-pack/plugins/canvas/public/components/border_connection/index.js rename to x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/translations.ts index b99ab923d52d4..e0f84d8541424 100644 --- a/x-pack/plugins/canvas/public/components/border_connection/index.js +++ b/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/translations.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; -import { BorderConnection as Component } from './border_connection'; - -export const BorderConnection = pure(Component); +import { i18n } from '@kbn/i18n'; +export const SELECT_CASE_TITLE = i18n.translate('xpack.securitySolution.case.caseModal.title', { + defaultMessage: 'Select case to attach timeline', +}); diff --git a/x-pack/plugins/security_solution/public/cases/components/user_action_tree/helpers.tsx b/x-pack/plugins/security_solution/public/cases/components/user_action_tree/helpers.tsx index a6286693423c8..1401ac2c46528 100644 --- a/x-pack/plugins/security_solution/public/cases/components/user_action_tree/helpers.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/user_action_tree/helpers.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiFlexGroup, EuiFlexItem, EuiBadge, EuiLink } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiBadgeGroup, EuiBadge, EuiLink } from '@elastic/eui'; import React from 'react'; import { CaseFullExternalService, Connector } from '../../../../../case/common/api'; @@ -50,14 +50,14 @@ const getTagsLabelTitle = (action: CaseUserActions) => ( {action.action === 'add' && i18n.ADDED_FIELD} {action.action === 'delete' && i18n.REMOVED_FIELD} {i18n.TAGS.toLowerCase()} - {action.newValue != null && - action.newValue.split(',').map((tag) => ( - + + {action.newValue != null && + action.newValue.split(',').map((tag) => ( {tag} - - ))} + ))} + ); diff --git a/x-pack/plugins/security_solution/public/cases/pages/saved_object_no_permissions.tsx b/x-pack/plugins/security_solution/public/cases/pages/saved_object_no_permissions.tsx index 7129aa04bdf69..c61ff6d18caab 100644 --- a/x-pack/plugins/security_solution/public/cases/pages/saved_object_no_permissions.tsx +++ b/x-pack/plugins/security_solution/public/cases/pages/saved_object_no_permissions.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { useMemo } from 'react'; import { EmptyPage } from '../../common/components/empty_page'; import * as i18n from './translations'; @@ -12,13 +12,21 @@ import { useKibana } from '../../common/lib/kibana'; export const CaseSavedObjectNoPermissions = React.memo(() => { const docLinks = useKibana().services.docLinks; + const actions = useMemo( + () => ({ + savedObject: { + icon: 'documents', + label: i18n.GO_TO_DOCUMENTATION, + url: `${docLinks.ELASTIC_WEBSITE_URL}guide/en/security/${docLinks.DOC_LINK_VERSION}s`, + target: '_blank', + }, + }), + [docLinks] + ); return ( { ); beforeEach(() => { + jest.useFakeTimers(); store = createStore( state, SUB_PLUGINS_REDUCER, @@ -159,6 +160,8 @@ describe('AddFilterToGlobalSearchBar Component', () => { wrapper.find('[data-test-subj="withHoverActionsButton"]').simulate('mouseenter'); wrapper.update(); + jest.runAllTimers(); + wrapper.update(); wrapper .find('[data-test-subj="hover-actions-container"] [data-euiicon-type]') diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_lists.test.tsx b/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_lists.test.tsx index 90e195b6e95a0..eca38b9effe1b 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_lists.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_lists.test.tsx @@ -52,20 +52,18 @@ describe('AutocompleteFieldListsComponent', () => { selectedField={getField('ip')} selectedValue="some-list-id" isLoading={false} - isClearable={false} - isDisabled={true} + isClearable={true} + isDisabled onChange={jest.fn()} />
); - await waitFor(() => { - expect( - wrapper - .find(`[data-test-subj="valuesAutocompleteComboBox listsComboxBox"] input`) - .prop('disabled') - ).toBeTruthy(); - }); + expect( + wrapper + .find(`[data-test-subj="valuesAutocompleteComboBox listsComboxBox"] input`) + .prop('disabled') + ).toBeTruthy(); }); test('it renders loading if "isLoading" is true', async () => { @@ -73,9 +71,9 @@ describe('AutocompleteFieldListsComponent', () => { ({ eui: euiLightVars, darkMode: false })}> { ); - await waitFor(() => { + wrapper + .find(`[data-test-subj="valuesAutocompleteComboBox listsComboxBox"] button`) + .at(0) + .simulate('click'); + expect( wrapper - .find(`[data-test-subj="valuesAutocompleteComboBox listsComboxBox"] button`) - .at(0) - .simulate('click'); - expect( - wrapper - .find( - `EuiComboBoxOptionsList[data-test-subj="valuesAutocompleteComboBox listsComboxBox-optionsList"]` - ) - .prop('isLoading') - ).toBeTruthy(); - }); + .find( + `EuiComboBoxOptionsList[data-test-subj="valuesAutocompleteComboBox listsComboxBox-optionsList"]` + ) + .prop('isLoading') + ).toBeTruthy(); }); test('it allows user to clear values if "isClearable" is true', async () => { @@ -104,9 +100,9 @@ describe('AutocompleteFieldListsComponent', () => { @@ -114,9 +110,9 @@ describe('AutocompleteFieldListsComponent', () => { ); expect( wrapper - .find(`[data-test-subj="comboBoxInput"]`) - .hasClass('euiComboBox__inputWrap-isClearable') - ).toBeTruthy(); + .find('EuiComboBox[data-test-subj="valuesAutocompleteComboBox listsComboxBox"]') + .prop('options') + ).toEqual([{ label: 'some name' }]); }); test('it correctly displays lists that match the selected "keyword" field esType', () => { @@ -210,19 +206,24 @@ describe('AutocompleteFieldListsComponent', () => { onChange: (a: EuiComboBoxOptionOption[]) => void; }).onChange([{ label: 'some name' }]); - expect(mockOnChange).toHaveBeenCalledWith({ - created_at: DATE_NOW, - created_by: 'some user', - description: 'some description', - id: 'some-list-id', - meta: {}, - name: 'some name', - tie_breaker_id: '6a76b69d-80df-4ab2-8c3e-85f466b06a0e', - type: 'ip', - updated_at: DATE_NOW, - updated_by: 'some user', - version: VERSION, - immutable: IMMUTABLE, + await waitFor(() => { + expect(mockOnChange).toHaveBeenCalledWith({ + created_at: DATE_NOW, + created_by: 'some user', + description: 'some description', + id: 'some-list-id', + meta: {}, + name: 'some name', + tie_breaker_id: '6a76b69d-80df-4ab2-8c3e-85f466b06a0e', + type: 'ip', + updated_at: DATE_NOW, + updated_by: 'some user', + _version: undefined, + version: VERSION, + deserializer: undefined, + serializer: undefined, + immutable: IMMUTABLE, + }); }); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_lists.tsx b/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_lists.tsx index cd90d6eb85623..4349e70594ecb 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_lists.tsx +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_lists.tsx @@ -9,7 +9,7 @@ import { EuiComboBoxOptionOption, EuiComboBox } from '@elastic/eui'; import { IFieldType } from '../../../../../../../src/plugins/data/common'; import { useFindLists, ListSchema } from '../../../lists_plugin_deps'; import { useKibana } from '../../../common/lib/kibana'; -import { getGenericComboBoxProps } from './helpers'; +import { getGenericComboBoxProps, paramIsValid } from './helpers'; interface AutocompleteFieldListsProps { placeholder: string; @@ -75,6 +75,8 @@ export const AutocompleteFieldListsComponent: React.FC setIsTouched(true), [setIsTouched]); + useEffect(() => { if (result != null) { setLists(result.data); @@ -91,17 +93,24 @@ export const AutocompleteFieldListsComponent: React.FC paramIsValid(selectedValue, selectedField, isRequired, touched), + [selectedField, selectedValue, isRequired, touched] + ); + + const isLoadingState = useMemo((): boolean => isLoading || loading, [isLoading, loading]); + return ( setIsTouched(true)} + isInvalid={!isValid} + onFocus={setIsTouchedValue} singleSelection={{ asPlainText: true }} sortMatchesBy="startsWith" data-test-subj="valuesAutocompleteComboBox listsComboxBox" diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_match.tsx b/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_match.tsx index 992005b3be8bc..137f6803dc54e 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_match.tsx +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_match.tsx @@ -9,7 +9,7 @@ import { uniq } from 'lodash'; import { IFieldType, IIndexPattern } from '../../../../../../../src/plugins/data/common'; import { useFieldValueAutocomplete } from './hooks/use_field_value_autocomplete'; -import { validateParams, getGenericComboBoxProps } from './helpers'; +import { paramIsValid, getGenericComboBoxProps } from './helpers'; import { OperatorTypeEnum } from '../../../lists_plugin_deps'; import { GetGenericComboBoxPropsReturn } from './types'; import * as i18n from './translations'; @@ -82,16 +82,28 @@ export const AutocompleteFieldMatchComponent: React.FC validateParams(selectedValue, selectedField), [ - selectedField, - selectedValue, + const isValid = useMemo( + (): boolean => paramIsValid(selectedValue, selectedField, isRequired, touched), + [selectedField, selectedValue, isRequired, touched] + ); + + const setIsTouchedValue = useCallback((): void => setIsTouched(true), [setIsTouched]); + + const inputPlaceholder = useMemo( + (): string => (isLoading || isLoadingSuggestions ? i18n.LOADING : placeholder), + [isLoading, isLoadingSuggestions, placeholder] + ); + + const isLoadingState = useMemo((): boolean => isLoading || isLoadingSuggestions, [ + isLoading, + isLoadingSuggestions, ]); return ( setIsTouched(true)} + isInvalid={!isValid} + onFocus={setIsTouchedValue} sortMatchesBy="startsWith" data-test-subj="valuesAutocompleteComboBox matchComboxBox" style={fieldInputWidth ? { width: `${fieldInputWidth}px` } : {}} diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_match_any.tsx b/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_match_any.tsx index 27807a752c141..5a15c1f7238de 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_match_any.tsx +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_match_any.tsx @@ -9,7 +9,7 @@ import { uniq } from 'lodash'; import { IFieldType, IIndexPattern } from '../../../../../../../src/plugins/data/common'; import { useFieldValueAutocomplete } from './hooks/use_field_value_autocomplete'; -import { getGenericComboBoxProps, validateParams } from './helpers'; +import { getGenericComboBoxProps, paramIsValid } from './helpers'; import { OperatorTypeEnum } from '../../../lists_plugin_deps'; import { GetGenericComboBoxPropsReturn } from './types'; import * as i18n from './translations'; @@ -78,16 +78,29 @@ export const AutocompleteFieldMatchAnyComponent: React.FC onChange([...(selectedValue || []), option]); const isValid = useMemo((): boolean => { - const areAnyInvalid = selectedComboOptions.filter( - ({ label }) => !validateParams(label, selectedField) - ); - return areAnyInvalid.length === 0; - }, [selectedComboOptions, selectedField]); + const areAnyInvalid = + selectedComboOptions.filter( + ({ label }) => !paramIsValid(label, selectedField, isRequired, touched) + ).length > 0; + return !areAnyInvalid; + }, [selectedComboOptions, selectedField, isRequired, touched]); + + const setIsTouchedValue = useCallback((): void => setIsTouched(true), [setIsTouched]); + + const inputPlaceholder = useMemo( + (): string => (isLoading || isLoadingSuggestions ? i18n.LOADING : placeholder), + [isLoading, isLoadingSuggestions, placeholder] + ); + + const isLoadingState = useMemo((): boolean => isLoading || isLoadingSuggestions, [ + isLoading, + isLoadingSuggestions, + ]); return ( setIsTouched(true)} + isInvalid={!isValid} + onFocus={setIsTouchedValue} delimiter=", " data-test-subj="valuesAutocompleteComboBox matchAnyComboxBox" fullWidth diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.test.ts b/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.test.ts index b25bb245c6792..289cdd5e87c00 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.test.ts @@ -14,7 +14,7 @@ import { existsOperator, doesNotExistOperator, } from './operators'; -import { getOperators, validateParams, getGenericComboBoxProps } from './helpers'; +import { getOperators, paramIsValid, getGenericComboBoxProps } from './helpers'; describe('helpers', () => { describe('#getOperators', () => { @@ -53,27 +53,67 @@ describe('helpers', () => { }); }); - describe('#validateParams', () => { - test('returns false if value is undefined', () => { - const isValid = validateParams(undefined, getField('@timestamp')); + describe('#paramIsValid', () => { + test('returns false if value is undefined and "isRequired" nad "touched" are true', () => { + const isValid = paramIsValid(undefined, getField('@timestamp'), true, true); expect(isValid).toBeFalsy(); }); - test('returns false if value is empty string', () => { - const isValid = validateParams('', getField('@timestamp')); + test('returns true if value is undefined and "isRequired" is true but "touched" is false', () => { + const isValid = paramIsValid(undefined, getField('@timestamp'), true, false); - expect(isValid).toBeFalsy(); + expect(isValid).toBeTruthy(); + }); + + test('returns true if value is undefined and "isRequired" is false', () => { + const isValid = paramIsValid(undefined, getField('@timestamp'), false, false); + + expect(isValid).toBeTruthy(); + }); + + test('returns false if value is empty string when "isRequired" is true and "touched" is false', () => { + const isValid = paramIsValid('', getField('@timestamp'), true, false); + + expect(isValid).toBeTruthy(); + }); + + test('returns true if value is empty string and "isRequired" is false', () => { + const isValid = paramIsValid('', getField('@timestamp'), false, false); + + expect(isValid).toBeTruthy(); }); - test('returns true if type is "date" and value is valid', () => { - const isValid = validateParams('1994-11-05T08:15:30-05:00', getField('@timestamp')); + test('returns true if type is "date" and value is valid and "isRequired" is false', () => { + const isValid = paramIsValid( + '1994-11-05T08:15:30-05:00', + getField('@timestamp'), + false, + false + ); expect(isValid).toBeTruthy(); }); - test('returns false if type is "date" and value is not valid', () => { - const isValid = validateParams('1593478826', getField('@timestamp')); + test('returns true if type is "date" and value is valid and "isRequired" is true', () => { + const isValid = paramIsValid( + '1994-11-05T08:15:30-05:00', + getField('@timestamp'), + true, + false + ); + + expect(isValid).toBeTruthy(); + }); + + test('returns false if type is "date" and value is not valid and "isRequired" is false', () => { + const isValid = paramIsValid('1593478826', getField('@timestamp'), false, false); + + expect(isValid).toBeFalsy(); + }); + + test('returns false if type is "date" and value is not valid and "isRequired" is true', () => { + const isValid = paramIsValid('1593478826', getField('@timestamp'), true, true); expect(isValid).toBeFalsy(); }); diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.ts b/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.ts index a65f1fa35d3c2..3dcaf612da649 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.ts +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.ts @@ -30,21 +30,26 @@ export const getOperators = (field: IFieldType | undefined): OperatorOption[] => } }; -export const validateParams = ( +export const paramIsValid = ( params: string | undefined, - field: IFieldType | undefined + field: IFieldType | undefined, + isRequired: boolean, + touched: boolean ): boolean => { - // Box would show error state if empty otherwise - if (params == null || params === '') { + if (isRequired && touched && (params == null || params === '')) { return false; } + if ((isRequired && !touched) || (!isRequired && (params == null || params === ''))) { + return true; + } + const types = field != null && field.esTypes != null ? field.esTypes : []; return types.reduce((acc, type) => { switch (type) { case 'date': - const moment = dateMath.parse(params); + const moment = dateMath.parse(params ?? ''); return Boolean(moment && moment.isValid()); default: return acc; diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/operator.test.tsx b/x-pack/plugins/security_solution/public/common/components/autocomplete/operator.test.tsx index 45fe6be78ace6..737be199e2481 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/operator.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/operator.test.tsx @@ -74,7 +74,7 @@ describe('OperatorComponent', () => { expect(wrapper.find(`button[data-test-subj="comboBoxClearButton"]`).exists()).toBeTruthy(); }); - test('it displays "operatorOptions" if param is passed in', () => { + test('it displays "operatorOptions" if param is passed in with items', () => { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { ).toEqual([{ label: 'is not' }]); }); + test('it does not display "operatorOptions" if param is passed in with no items', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find(`[data-test-subj="operatorAutocompleteComboBox"]`).at(0).prop('options') + ).toEqual([ + { + label: 'is', + }, + { + label: 'is not', + }, + { + label: 'is one of', + }, + { + label: 'is not one of', + }, + { + label: 'exists', + }, + { + label: 'does not exist', + }, + { + label: 'is in list', + }, + { + label: 'is not in list', + }, + ]); + }); + test('it correctly displays selected operator', () => { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/operator.tsx b/x-pack/plugins/security_solution/public/common/components/autocomplete/operator.tsx index 6d9a684aab2de..cec7d575fc78e 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/operator.tsx +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/operator.tsx @@ -35,7 +35,10 @@ export const OperatorComponent: React.FC = ({ }): JSX.Element => { const getLabel = useCallback(({ message }): string => message, []); const optionsMemo = useMemo( - (): OperatorOption[] => (operatorOptions ? operatorOptions : getOperators(selectedField)), + (): OperatorOption[] => + operatorOptions != null && operatorOptions.length > 0 + ? operatorOptions + : getOperators(selectedField), [operatorOptions, selectedField] ); const selectedOptionsMemo = useMemo((): OperatorOption[] => (operator ? [operator] : []), [ diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/operators.ts b/x-pack/plugins/security_solution/public/common/components/autocomplete/operators.ts index a81d8cde94e34..c54f58a3fd4b3 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/operators.ts +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/operators.ts @@ -90,3 +90,17 @@ export const EXCEPTION_OPERATORS: OperatorOption[] = [ isInListOperator, isNotInListOperator, ]; + +export const EXCEPTION_OPERATORS_SANS_LISTS: OperatorOption[] = [ + isOperator, + isNotOperator, + isOneOfOperator, + isNotOneOfOperator, + existsOperator, + doesNotExistOperator, +]; + +export const EXCEPTION_OPERATORS_ONLY_LISTS: OperatorOption[] = [ + isInListOperator, + isNotInListOperator, +]; diff --git a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.test.tsx b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.test.tsx index e17fc7b9ef9bd..ebfa9ac22bdc7 100644 --- a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.test.tsx @@ -22,6 +22,10 @@ describe('DraggableWrapper', () => { const message = 'draggable wrapper content'; const mount = useMountAppended(); + beforeEach(() => { + jest.useFakeTimers(); + }); + describe('rendering', () => { test('it renders against the snapshot', () => { const wrapper = shallow( @@ -78,6 +82,8 @@ describe('DraggableWrapper', () => { wrapper.find('[data-test-subj="withHoverActionsButton"]').simulate('mouseenter'); wrapper.update(); + jest.runAllTimers(); + wrapper.update(); expect(wrapper.find('[data-test-subj="copy-to-clipboard"]').exists()).toBe(true); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/provider_container.tsx b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/provider_container.tsx index 06cb8ee2e1a46..8db6d073f9687 100644 --- a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/provider_container.tsx +++ b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/provider_container.tsx @@ -13,13 +13,6 @@ interface ProviderContainerProps { } const ProviderContainerComponent = styled.div` - &, - &::before, - &::after { - transition: background ${({ theme }) => theme.eui.euiAnimSpeedFast} ease, - color ${({ theme }) => theme.eui.euiAnimSpeedFast} ease; - } - ${({ isDragging }) => !isDragging && css` diff --git a/x-pack/plugins/security_solution/public/common/components/empty_page/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/empty_page/__snapshots__/index.test.tsx.snap index 623b15aa76d12..9bf3be7b5dfa4 100644 --- a/x-pack/plugins/security_solution/public/common/components/empty_page/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/common/components/empty_page/__snapshots__/index.test.tsx.snap @@ -1,6 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`renders correctly 1`] = ` +exports[`EmptyPage component renders actions with descriptions 1`] = ` + + Do Something + + } + title={false} + /> + + + } + iconType="logoSecurity" + title={ +

+ My Super Title +

+ } +/> +`; + +exports[`EmptyPage component renders actions without descriptions 1`] = ` + + Do Something diff --git a/x-pack/plugins/security_solution/public/common/components/empty_page/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/empty_page/index.test.tsx index 6a14c12cee0f8..28e01eaa3eead 100644 --- a/x-pack/plugins/security_solution/public/common/components/empty_page/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/empty_page/index.test.tsx @@ -9,13 +9,27 @@ import React from 'react'; import { EmptyPage } from './index'; -test('renders correctly', () => { - const EmptyComponent = shallow( - - ); - expect(EmptyComponent).toMatchSnapshot(); +describe('EmptyPage component', () => { + it('renders actions without descriptions', () => { + const actions = { + actions: { + label: 'Do Something', + url: 'my/url/from/nowwhere', + }, + }; + const EmptyComponent = shallow(); + expect(EmptyComponent).toMatchSnapshot(); + }); + + it('renders actions with descriptions', () => { + const actions = { + actions: { + description: 'My Description', + label: 'Do Something', + url: 'my/url/from/nowwhere', + }, + }; + const EmptyComponent = shallow(); + expect(EmptyComponent).toMatchSnapshot(); + }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/empty_page/index.tsx b/x-pack/plugins/security_solution/public/common/components/empty_page/index.tsx index f6d6752729b6d..e0db1e90374ad 100644 --- a/x-pack/plugins/security_solution/public/common/components/empty_page/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/empty_page/index.tsx @@ -4,84 +4,114 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiButton, EuiEmptyPrompt, EuiFlexGroup, EuiFlexItem, IconType } from '@elastic/eui'; -import React, { MouseEventHandler, ReactNode } from 'react'; +import { + EuiButton, + EuiEmptyPrompt, + EuiFlexGroup, + EuiFlexItem, + IconType, + EuiCard, +} from '@elastic/eui'; +import React, { MouseEventHandler, ReactNode, useMemo } from 'react'; import styled from 'styled-components'; const EmptyPrompt = styled(EuiEmptyPrompt)` align-self: center; /* Corrects horizontal centering in IE11 */ + max-width: 60em; `; EmptyPrompt.displayName = 'EmptyPrompt'; +interface EmptyPageActions { + icon?: IconType; + label: string; + target?: string; + url: string; + descriptionTitle?: string; + description?: string; + fill?: boolean; + onClick?: MouseEventHandler; +} + +export type EmptyPageActionsProps = Record; + interface EmptyPageProps { - actionPrimaryIcon?: IconType; - actionPrimaryLabel: string; - actionPrimaryTarget?: string; - actionPrimaryUrl: string; - actionPrimaryFill?: boolean; - actionSecondaryIcon?: IconType; - actionSecondaryLabel?: string; - actionSecondaryTarget?: string; - actionSecondaryUrl?: string; - actionSecondaryOnClick?: MouseEventHandler; + actions: EmptyPageActionsProps; 'data-test-subj'?: string; message?: ReactNode; title: string; } -export const EmptyPage = React.memo( - ({ - actionPrimaryIcon, - actionPrimaryLabel, - actionPrimaryTarget, - actionPrimaryUrl, - actionPrimaryFill = true, - actionSecondaryIcon, - actionSecondaryLabel, - actionSecondaryTarget, - actionSecondaryUrl, - actionSecondaryOnClick, - message, - title, - ...rest - }) => ( +const EmptyPageComponent = React.memo(({ actions, message, title, ...rest }) => { + const titles = Object.keys(actions); + const maxItemWidth = 283; + const renderActions = useMemo( + () => + Object.values(actions) + .filter((a) => a.label && a.url) + .map( + ( + { icon, label, target, url, descriptionTitle, description, onClick, fill = true }, + idx + ) => + descriptionTitle != null || description != null ? ( + + + {label} + + } + /> + + ) : ( + + {/* eslint-disable-next-line @elastic/eui/href-or-on-click */} + + {label} + + + ) + ), + [actions, titles] + ); + + return ( {title}} body={message &&

{message}

} - actions={ - - - - {actionPrimaryLabel} - - - - {actionSecondaryLabel && actionSecondaryUrl && ( - - {/* eslint-disable-next-line @elastic/eui/href-or-on-click */} - - {actionSecondaryLabel} - - - )} - - } + actions={{renderActions}} {...rest} /> - ) -); + ); +}); + +EmptyPageComponent.displayName = 'EmptyPageComponent'; +export const EmptyPage = React.memo(EmptyPageComponent); EmptyPage.displayName = 'EmptyPage'; diff --git a/x-pack/plugins/security_solution/public/common/components/event_details/__snapshots__/event_details.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/event_details/__snapshots__/event_details.test.tsx.snap index ebaf60e7078f0..2ae621e71a725 100644 --- a/x-pack/plugins/security_solution/public/common/components/event_details/__snapshots__/event_details.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/common/components/event_details/__snapshots__/event_details.test.tsx.snap @@ -4,33 +4,6 @@ exports[`EventDetails rendering should match snapshot 1`] = `
- - - - - } - closePopover={[Function]} - display="inlineBlock" - hasArrow={true} - isOpen={false} - ownFocus={false} - panelPaddingSize="m" - repositionOnScroll={true} - /> - + + Collapse event +
`; diff --git a/x-pack/plugins/security_solution/public/common/components/event_details/event_details.test.tsx b/x-pack/plugins/security_solution/public/common/components/event_details/event_details.test.tsx index a5b44fd540c4b..01b0810830dd8 100644 --- a/x-pack/plugins/security_solution/public/common/components/event_details/event_details.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/event_details/event_details.test.tsx @@ -11,7 +11,7 @@ import '../../mock/match_media'; import { mockDetailItemData, mockDetailItemDataId } from '../../mock/mock_detail_item'; import { TestProviders } from '../../mock/test_providers'; -import { EventDetails } from './event_details'; +import { EventDetails, View } from './event_details'; import { mockBrowserFields } from '../../containers/source/mock'; import { defaultHeaders } from '../../mock/header'; import { useMountAppended } from '../../utils/use_mount_appended'; @@ -20,47 +20,35 @@ jest.mock('../link_to'); describe('EventDetails', () => { const mount = useMountAppended(); + const onEventToggled = jest.fn(); + const defaultProps = { + browserFields: mockBrowserFields, + columnHeaders: defaultHeaders, + data: mockDetailItemData, + id: mockDetailItemDataId, + view: 'table-view' as View, + onEventToggled, + onUpdateColumns: jest.fn(), + onViewSelected: jest.fn(), + timelineId: 'test', + toggleColumn: jest.fn(), + }; + const wrapper = mount( + + + + ); describe('rendering', () => { test('should match snapshot', () => { - const wrapper = shallow( - - ); - expect(wrapper).toMatchSnapshot(); + const shallowWrap = shallow(); + expect(shallowWrap).toMatchSnapshot(); }); }); describe('tabs', () => { ['Table', 'JSON View'].forEach((tab) => { test(`it renders the ${tab} tab`, () => { - const wrapper = mount( - - - - ); - expect( wrapper .find('[data-test-subj="eventDetails"]') @@ -71,48 +59,12 @@ describe('EventDetails', () => { }); test('the Table tab is selected by default', () => { - const wrapper = mount( - - - - ); - expect( wrapper.find('[data-test-subj="eventDetails"]').find('.euiTab-isSelected').first().text() ).toEqual('Table'); }); test('it invokes `onEventToggled` when the collapse button is clicked', () => { - const onEventToggled = jest.fn(); - - const wrapper = mount( - - - - ); - wrapper.find('[data-test-subj="collapse"]').first().simulate('click'); wrapper.update(); diff --git a/x-pack/plugins/security_solution/public/common/components/event_details/event_details.tsx b/x-pack/plugins/security_solution/public/common/components/event_details/event_details.tsx index 53ec14380d5bc..1cc50b7d951a2 100644 --- a/x-pack/plugins/security_solution/public/common/components/event_details/event_details.tsx +++ b/x-pack/plugins/security_solution/public/common/components/event_details/event_details.tsx @@ -4,14 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { noop } from 'lodash/fp'; -import { - EuiButtonIcon, - EuiPopover, - EuiTabbedContent, - EuiTabbedContentTab, - EuiToolTip, -} from '@elastic/eui'; +import { EuiLink, EuiTabbedContent, EuiTabbedContentTab } from '@elastic/eui'; import React, { useMemo } from 'react'; import styled from 'styled-components'; @@ -26,22 +19,11 @@ import { COLLAPSE, COLLAPSE_EVENT } from '../../../timelines/components/timeline export type View = 'table-view' | 'json-view'; -const PopoverContainer = styled.div` - left: -40px; - position: relative; - top: 10px; - - .euiPopover { - position: fixed; - z-index: 10; - } +const CollapseLink = styled(EuiLink)` + margin: 20px 0; `; -const CollapseButton = styled(EuiButtonIcon)` - border: 1px solid; -`; - -CollapseButton.displayName = 'CollapseButton'; +CollapseLink.displayName = 'CollapseLink'; interface Props { browserFields: BrowserFields; @@ -75,59 +57,42 @@ export const EventDetails = React.memo( timelineId, toggleColumn, }) => { - const button = useMemo( - () => ( - - - - ), - [onEventToggled] + const tabs: EuiTabbedContentTab[] = useMemo( + () => [ + { + id: 'table-view', + name: i18n.TABLE, + content: ( + + ), + }, + { + id: 'json-view', + name: i18n.JSON_VIEW, + content: , + }, + ], + [browserFields, columnHeaders, data, id, onUpdateColumns, timelineId, toggleColumn] ); - const tabs: EuiTabbedContentTab[] = [ - { - id: 'table-view', - name: i18n.TABLE, - content: ( - - ), - }, - { - id: 'json-view', - name: i18n.JSON_VIEW, - content: , - }, - ]; - return (
- - - onViewSelected(e.id as View)} /> + + {COLLAPSE_EVENT} +
); } diff --git a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx index bc036b38524ba..e836e2e20432a 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx +++ b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx @@ -222,6 +222,7 @@ const EventsViewerComponent: React.FC = ({ sourceId="default" startDate={start} endDate={end} + queryDeduplication="events_viewer" > {({ events, diff --git a/x-pack/plugins/security_solution/public/common/components/events_viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/events_viewer/index.tsx index 80831b4022ace..c402116ee2714 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/events_viewer/index.tsx @@ -69,7 +69,10 @@ const StatefulEventsViewerComponent: React.FC = ({ }) => { const [ { docValueFields, browserFields, indexPatterns, isLoading: isLoadingIndexPattern }, - ] = useFetchIndexPatterns(defaultIndices ?? useUiSetting(DEFAULT_INDEX_KEY)); + ] = useFetchIndexPatterns( + defaultIndices ?? useUiSetting(DEFAULT_INDEX_KEY), + 'events_viewer' + ); useEffect(() => { if (createTimeline != null) { diff --git a/x-pack/plugins/security_solution/public/common/components/events_viewer/mock.ts b/x-pack/plugins/security_solution/public/common/components/events_viewer/mock.ts index ea2e60ebc82b8..6266e84051901 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_viewer/mock.ts +++ b/x-pack/plugins/security_solution/public/common/components/events_viewer/mock.ts @@ -40,6 +40,7 @@ export const mockEventViewerResponse = [ { field: 'event.end', format: 'date_time' }, ], inspect: false, + queryDeduplication: 'events_viewer', }, }, result: { diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_comments.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_comments.tsx index db2d0540971de..22d14ec6bedb1 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_comments.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_comments.tsx @@ -16,13 +16,13 @@ import { EuiCommentProps, EuiText, } from '@elastic/eui'; -import { Comments } from '../../../lists_plugin_deps'; +import { Comment } from '../../../shared_imports'; import * as i18n from './translations'; import { useCurrentUser } from '../../lib/kibana'; import { getFormattedComments } from './helpers'; interface AddExceptionCommentsProps { - exceptionItemComments?: Comments[]; + exceptionItemComments?: Comment[]; newCommentValue: string; newCommentOnChange: (value: string) => void; } diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.tsx index 6e77cd7082d56..bb547f05090b7 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.tsx @@ -38,7 +38,7 @@ import { useSignalIndex } from '../../../../detections/containers/detection_engi import { useFetchOrCreateRuleExceptionList } from '../use_fetch_or_create_rule_exception_list'; import { AddExceptionComments } from '../add_exception_comments'; import { - enrichExceptionItemsWithComments, + enrichNewExceptionItemsWithComments, enrichExceptionItemsWithOS, defaultEndpointExceptionItems, entryHasListType, @@ -61,12 +61,14 @@ export interface AddExceptionModalBaseProps { export interface AddExceptionModalProps extends AddExceptionModalBaseProps { onCancel: () => void; onConfirm: (didCloseAlert: boolean) => void; + onRuleChange?: () => void; alertStatus?: Status; } const Modal = styled(EuiModal)` ${({ theme }) => css` - width: ${theme.eui.euiBreakpoints.m}; + width: ${theme.eui.euiBreakpoints.l}; + max-width: ${theme.eui.euiBreakpoints.l}; `} `; @@ -99,6 +101,7 @@ export const AddExceptionModal = memo(function AddExceptionModal({ alertData, onCancel, onConfirm, + onRuleChange, alertStatus, }: AddExceptionModalProps) { const { http } = useKibana().services; @@ -152,6 +155,14 @@ export const AddExceptionModal = memo(function AddExceptionModal({ [setExceptionItemsToAdd] ); + const handleRuleChange = useCallback( + (ruleChanged: boolean): void => { + if (ruleChanged && onRuleChange) { + onRuleChange(); + } + }, + [onRuleChange] + ); const onFetchOrCreateExceptionListError = useCallback( (error: Error) => { setFetchOrCreateListError(true); @@ -163,6 +174,7 @@ export const AddExceptionModal = memo(function AddExceptionModal({ ruleId, exceptionListType, onError: onFetchOrCreateExceptionListError, + onSuccess: handleRuleChange, }); const initialExceptionItems = useMemo(() => { @@ -222,7 +234,7 @@ export const AddExceptionModal = memo(function AddExceptionModal({ ); const retrieveAlertOsTypes = useCallback(() => { - const osDefaults = ['windows', 'macos', 'linux']; + const osDefaults = ['windows', 'macos']; if (alertData) { const osTypes = getMappedNonEcsValue({ data: alertData.nonEcsData, @@ -240,7 +252,7 @@ export const AddExceptionModal = memo(function AddExceptionModal({ let enriched: Array = []; enriched = comment !== '' - ? enrichExceptionItemsWithComments(exceptionItemsToAdd, [{ comment }]) + ? enrichNewExceptionItemsWithComments(exceptionItemsToAdd, [{ comment }]) : exceptionItemsToAdd; if (exceptionListType === 'endpoint') { const osTypes = retrieveAlertOsTypes(); @@ -265,8 +277,8 @@ export const AddExceptionModal = memo(function AddExceptionModal({ signalIndexName, ]); - const isSubmitButtonDisabled = useCallback( - () => fetchOrCreateListError || exceptionItemsToAdd.length === 0, + const isSubmitButtonDisabled = useMemo( + () => fetchOrCreateListError || exceptionItemsToAdd.every((item) => item.entries.length === 0), [fetchOrCreateListError, exceptionItemsToAdd] ); @@ -274,7 +286,9 @@ export const AddExceptionModal = memo(function AddExceptionModal({ - {i18n.ADD_EXCEPTION} + + {exceptionListType === 'endpoint' ? i18n.ADD_ENDPOINT_EXCEPTION : i18n.ADD_EXCEPTION} + {ruleName} @@ -285,9 +299,13 @@ export const AddExceptionModal = memo(function AddExceptionModal({

{i18n.ADD_EXCEPTION_FETCH_ERROR}

)} - {fetchOrCreateListError === false && isLoadingExceptionList === true && ( - - )} + {fetchOrCreateListError === false && + (isLoadingExceptionList || + isIndexPatternLoading || + isSignalIndexLoading || + isSignalIndexPatternLoading) && ( + + )} {fetchOrCreateListError === false && !isSignalIndexLoading && !isSignalIndexPatternLoading && @@ -307,6 +325,7 @@ export const AddExceptionModal = memo(function AddExceptionModal({ indexPatterns={indexPatterns} isOrDisabled={false} isAndDisabled={false} + isNestedDisabled={false} data-test-subj="alert-exception-builder" id-aria="alert-exception-builder" onChange={handleBuilderOnChange} @@ -314,13 +333,6 @@ export const AddExceptionModal = memo(function AddExceptionModal({ - {exceptionListType === 'endpoint' && ( - <> - {i18n.ENDPOINT_QUARANTINE_TEXT} - - - )} - + {exceptionListType === 'endpoint' && ( + <> + + + {i18n.ENDPOINT_QUARANTINE_TEXT} + + + )} )} @@ -361,7 +381,7 @@ export const AddExceptionModal = memo(function AddExceptionModal({ {i18n.ADD_EXCEPTION} diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/translations.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/translations.ts index 81db1b10f7021..abc296e9c0e1a 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/translations.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/translations.ts @@ -17,6 +17,13 @@ export const ADD_EXCEPTION = i18n.translate( } ); +export const ADD_ENDPOINT_EXCEPTION = i18n.translate( + 'xpack.securitySolution.exceptions.addException.addEndpointException', + { + defaultMessage: 'Add Endpoint Exception', + } +); + export const ADD_EXCEPTION_ERROR = i18n.translate( 'xpack.securitySolution.exceptions.addException.error', { @@ -49,14 +56,15 @@ export const ENDPOINT_QUARANTINE_TEXT = i18n.translate( 'xpack.securitySolution.exceptions.addException.endpointQuarantineText', { defaultMessage: - 'Any file in quarantine on any endpoint that matches the attribute(s) selected will automatically be restored to its original location', + 'Any file in quarantine on any endpoint that matches the attribute(s) selected will automatically be restored to its original location. This exception will apply to any rule that is linked to the Global Endpoint Exception List.', } ); export const BULK_CLOSE_LABEL = i18n.translate( 'xpack.securitySolution.exceptions.addException.bulkCloseLabel', { - defaultMessage: 'Close all alerts that match attributes in this exception', + defaultMessage: + 'Close all alerts that match this exception, including alerts generated by other rules', } ); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_button_options.stories.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_button_options.stories.tsx index 9486008e708ea..5ca2d2b86a527 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_button_options.stories.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_button_options.stories.tsx @@ -21,22 +21,43 @@ storiesOf('Components|Exceptions|BuilderButtonOptions', module) ); }) - .add('nested button', () => { + .add('nested button - isNested false', () => { return ( + ); + }) + .add('nested button - isNested true', () => { + return ( + ); }) @@ -45,10 +66,13 @@ storiesOf('Components|Exceptions|BuilderButtonOptions', module) ); }) @@ -57,10 +81,28 @@ storiesOf('Components|Exceptions|BuilderButtonOptions', module) + ); + }) + .add('nested disabled', () => { + return ( + ); }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_button_options.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_button_options.test.tsx index 66968ee95d3fa..6564770196b89 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_button_options.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_button_options.test.tsx @@ -15,10 +15,13 @@ describe('BuilderButtonOptions', () => { ); @@ -37,10 +40,13 @@ describe('BuilderButtonOptions', () => { ); @@ -49,17 +55,20 @@ describe('BuilderButtonOptions', () => { expect(onOrClicked).toHaveBeenCalledTimes(1); }); - test('it invokes "onAndClicked" when "and" button is clicked', () => { + test('it invokes "onAndClicked" when "and" button is clicked and "isNested" is "false"', () => { const onAndClicked = jest.fn(); const wrapper = mount( ); @@ -68,15 +77,40 @@ describe('BuilderButtonOptions', () => { expect(onAndClicked).toHaveBeenCalledTimes(1); }); + test('it invokes "onAddClickWhenNested" when "and" button is clicked and "isNested" is "true"', () => { + const onAddClickWhenNested = jest.fn(); + + const wrapper = mount( + + ); + + wrapper.find('[data-test-subj="exceptionsAndButton"] button').simulate('click'); + + expect(onAddClickWhenNested).toHaveBeenCalledTimes(1); + }); + test('it disables "and" button if "isAndDisabled" is true', () => { const wrapper = mount( ); @@ -85,15 +119,18 @@ describe('BuilderButtonOptions', () => { expect(andButton.prop('disabled')).toBeTruthy(); }); - test('it disables "or" button if "isOrDisabled" is true', () => { + test('it disables "or" button if "isOrDisabled" is "true"', () => { const wrapper = mount( ); @@ -102,17 +139,40 @@ describe('BuilderButtonOptions', () => { expect(orButton.prop('disabled')).toBeTruthy(); }); - test('it invokes "onNestedClicked" when "and" button is clicked', () => { + test('it disables "add nested" button if "isNestedDisabled" is "true"', () => { + const wrapper = mount( + + ); + + const nestedButton = wrapper.find('[data-test-subj="exceptionsNestedButton"] button').at(0); + + expect(nestedButton.prop('disabled')).toBeTruthy(); + }); + + test('it invokes "onNestedClicked" when "isNested" is "false" and "nested" button is clicked', () => { const onNestedClicked = jest.fn(); const wrapper = mount( ); @@ -120,4 +180,26 @@ describe('BuilderButtonOptions', () => { expect(onNestedClicked).toHaveBeenCalledTimes(1); }); + + test('it invokes "onAndClicked" when "isNested" is "true" and "nested" button is clicked', () => { + const onAndClicked = jest.fn(); + + const wrapper = mount( + + ); + + wrapper.find('[data-test-subj="exceptionsNestedButton"] button').simulate('click'); + + expect(onAndClicked).toHaveBeenCalledTimes(1); + }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_button_options.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_button_options.tsx index eb224b82d756f..bef47ce877b93 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_button_options.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_button_options.tsx @@ -7,7 +7,8 @@ import React from 'react'; import { EuiFlexGroup, EuiFlexItem, EuiButton } from '@elastic/eui'; import styled from 'styled-components'; -import * as i18n from '../translations'; +import * as i18n from './translations'; +import * as i18nShared from '../translations'; const MyEuiButton = styled(EuiButton)` min-width: 95px; @@ -16,19 +17,25 @@ const MyEuiButton = styled(EuiButton)` interface BuilderButtonOptionsProps { isOrDisabled: boolean; isAndDisabled: boolean; + isNestedDisabled: boolean; + isNested: boolean; showNestedButton: boolean; onAndClicked: () => void; onOrClicked: () => void; onNestedClicked: () => void; + onAddClickWhenNested: () => void; } export const BuilderButtonOptions: React.FC = ({ isOrDisabled = false, isAndDisabled = false, showNestedButton = false, + isNestedDisabled = true, + isNested, onAndClicked, onOrClicked, onNestedClicked, + onAddClickWhenNested, }) => ( @@ -36,11 +43,11 @@ export const BuilderButtonOptions: React.FC = ({ fill size="s" iconType="plusInCircle" - onClick={onAndClicked} + onClick={isNested ? onAddClickWhenNested : onAndClicked} data-test-subj="exceptionsAndButton" isDisabled={isAndDisabled} > - {i18n.AND} + {i18nShared.AND} @@ -52,7 +59,7 @@ export const BuilderButtonOptions: React.FC = ({ isDisabled={isOrDisabled} data-test-subj="exceptionsOrButton" > - {i18n.OR} + {i18nShared.OR} {showNestedButton && ( @@ -60,10 +67,11 @@ export const BuilderButtonOptions: React.FC = ({ - {i18n.ADD_NESTED_DESCRIPTION} + {isNested ? i18n.ADD_NON_NESTED_DESCRIPTION : i18n.ADD_NESTED_DESCRIPTION} )} diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/entry_item.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_entry_item.test.tsx similarity index 70% rename from x-pack/plugins/security_solution/public/common/components/exceptions/builder/entry_item.test.tsx rename to x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_entry_item.test.tsx index 791782b0f0152..3dcc3eb5a8329 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/entry_item.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_entry_item.test.tsx @@ -8,7 +8,7 @@ import { mount } from 'enzyme'; import React from 'react'; import { EuiComboBox, EuiComboBoxOptionOption } from '@elastic/eui'; -import { EntryItemComponent } from './entry_item'; +import { BuilderEntryItem } from './builder_entry_item'; import { isOperator, isNotOperator, @@ -44,47 +44,26 @@ jest.mock('../../../../lists_plugin_deps', () => { }; }); -describe('EntryItemComponent', () => { - test('it renders fields disabled if "isLoading" is "true"', () => { - const wrapper = mount( - - ); - - expect( - wrapper.find('[data-test-subj="exceptionBuilderEntryField"] input').props().disabled - ).toBeTruthy(); - expect( - wrapper.find('[data-test-subj="exceptionBuilderEntryOperator"] input').props().disabled - ).toBeTruthy(); - expect( - wrapper.find('[data-test-subj="exceptionBuilderEntryFieldMatch"] input').props().disabled - ).toBeTruthy(); - expect(wrapper.find('[data-test-subj="exceptionBuilderEntryFieldFormRow"]')).toHaveLength(0); - }); - +describe('BuilderEntryItem', () => { test('it renders field labels if "showLabel" is "true"', () => { const wrapper = mount( - ); @@ -94,16 +73,23 @@ describe('EntryItemComponent', () => { test('it renders field values correctly when operator is "isOperator"', () => { const wrapper = mount( - ); @@ -117,16 +103,23 @@ describe('EntryItemComponent', () => { test('it renders field values correctly when operator is "isNotOperator"', () => { const wrapper = mount( - ); @@ -142,16 +135,23 @@ describe('EntryItemComponent', () => { test('it renders field values correctly when operator is "isOneOfOperator"', () => { const wrapper = mount( - ); @@ -167,16 +167,23 @@ describe('EntryItemComponent', () => { test('it renders field values correctly when operator is "isNotOneOfOperator"', () => { const wrapper = mount( - ); @@ -192,16 +199,23 @@ describe('EntryItemComponent', () => { test('it renders field values correctly when operator is "isInListOperator"', () => { const wrapper = mount( - ); @@ -217,16 +231,23 @@ describe('EntryItemComponent', () => { test('it renders field values correctly when operator is "isNotInListOperator"', () => { const wrapper = mount( - ); @@ -242,16 +263,23 @@ describe('EntryItemComponent', () => { test('it renders field values correctly when operator is "existsOperator"', () => { const wrapper = mount( - ); @@ -270,16 +298,23 @@ describe('EntryItemComponent', () => { test('it renders field values correctly when operator is "doesNotExistOperator"', () => { const wrapper = mount( - ); @@ -299,16 +334,23 @@ describe('EntryItemComponent', () => { test('it invokes "onChange" when new field is selected and resets operator and value fields', () => { const mockOnChange = jest.fn(); const wrapper = mount( - ); @@ -318,24 +360,31 @@ describe('EntryItemComponent', () => { }).onChange([{ label: 'machine.os' }]); expect(mockOnChange).toHaveBeenCalledWith( - { field: 'machine.os', operator: 'included', type: 'match', value: undefined }, + { field: 'machine.os', operator: 'included', type: 'match', value: '' }, 0 ); }); - test('it invokes "onChange" when new operator is selected and resets value field', () => { + test('it invokes "onChange" when new operator is selected', () => { const mockOnChange = jest.fn(); const wrapper = mount( - ); @@ -345,7 +394,7 @@ describe('EntryItemComponent', () => { }).onChange([{ label: 'is not' }]); expect(mockOnChange).toHaveBeenCalledWith( - { field: 'ip', operator: 'excluded', type: 'match', value: '' }, + { field: 'ip', operator: 'excluded', type: 'match', value: '1234' }, 0 ); }); @@ -353,16 +402,23 @@ describe('EntryItemComponent', () => { test('it invokes "onChange" when new value field is entered for match operator', () => { const mockOnChange = jest.fn(); const wrapper = mount( - ); @@ -380,16 +436,23 @@ describe('EntryItemComponent', () => { test('it invokes "onChange" when new value field is entered for match_any operator', () => { const mockOnChange = jest.fn(); const wrapper = mount( - ); @@ -407,16 +470,23 @@ describe('EntryItemComponent', () => { test('it invokes "onChange" when new value field is entered for list operator', () => { const mockOnChange = jest.fn(); const wrapper = mount( - ); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/entry_item.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_entry_item.tsx similarity index 60% rename from x-pack/plugins/security_solution/public/common/components/exceptions/builder/entry_item.tsx rename to x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_entry_item.tsx index 7bf279168a9a0..5939a5a1b576e 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/entry_item.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_entry_item.tsx @@ -9,136 +9,142 @@ import { EuiFormRow, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { IFieldType, IIndexPattern } from '../../../../../../../../src/plugins/data/common'; import { FieldComponent } from '../../autocomplete/field'; import { OperatorComponent } from '../../autocomplete/operator'; -import { isOperator } from '../../autocomplete/operators'; import { OperatorOption } from '../../autocomplete/types'; import { AutocompleteFieldMatchComponent } from '../../autocomplete/field_value_match'; import { AutocompleteFieldMatchAnyComponent } from '../../autocomplete/field_value_match_any'; import { AutocompleteFieldExistsComponent } from '../../autocomplete/field_value_exists'; import { FormattedBuilderEntry, BuilderEntry } from '../types'; import { AutocompleteFieldListsComponent } from '../../autocomplete/field_value_lists'; -import { ListSchema, OperatorTypeEnum } from '../../../../lists_plugin_deps'; -import { getValueFromOperator } from '../helpers'; +import { ListSchema, OperatorTypeEnum, ExceptionListType } from '../../../../lists_plugin_deps'; import { getEmptyValue } from '../../empty_value'; -import * as i18n from '../translations'; +import * as i18n from './translations'; +import { + getFilteredIndexPatterns, + getOperatorOptions, + getEntryOnFieldChange, + getEntryOnOperatorChange, + getEntryOnMatchChange, + getEntryOnMatchAnyChange, + getEntryOnListChange, +} from './helpers'; +import { EXCEPTION_OPERATORS_ONLY_LISTS } from '../../autocomplete/operators'; interface EntryItemProps { entry: FormattedBuilderEntry; - entryIndex: number; indexPattern: IIndexPattern; - isLoading: boolean; showLabel: boolean; + listType: ExceptionListType; + addNested: boolean; onChange: (arg: BuilderEntry, i: number) => void; + onlyShowListOperators?: boolean; } -export const EntryItemComponent: React.FC = ({ +export const BuilderEntryItem: React.FC = ({ entry, - entryIndex, indexPattern, - isLoading, + listType, + addNested, showLabel, onChange, + onlyShowListOperators = false, }): JSX.Element => { const handleFieldChange = useCallback( ([newField]: IFieldType[]): void => { - onChange( - { - field: newField.name, - type: OperatorTypeEnum.MATCH, - operator: isOperator.operator, - value: undefined, - }, - entryIndex - ); + const { updatedEntry, index } = getEntryOnFieldChange(entry, newField); + + onChange(updatedEntry, index); }, - [onChange, entryIndex] + [onChange, entry] ); const handleOperatorChange = useCallback( ([newOperator]: OperatorOption[]): void => { - const newEntry = getValueFromOperator(entry.field, newOperator); - onChange(newEntry, entryIndex); + const { updatedEntry, index } = getEntryOnOperatorChange(entry, newOperator); + + onChange(updatedEntry, index); }, - [onChange, entryIndex, entry.field] + [onChange, entry] ); const handleFieldMatchValueChange = useCallback( (newField: string): void => { - onChange( - { - field: entry.field != null ? entry.field.name : undefined, - type: OperatorTypeEnum.MATCH, - operator: entry.operator.operator, - value: newField, - }, - entryIndex - ); + const { updatedEntry, index } = getEntryOnMatchChange(entry, newField); + + onChange(updatedEntry, index); }, - [onChange, entryIndex, entry.field, entry.operator.operator] + [onChange, entry] ); const handleFieldMatchAnyValueChange = useCallback( (newField: string[]): void => { - onChange( - { - field: entry.field != null ? entry.field.name : undefined, - type: OperatorTypeEnum.MATCH_ANY, - operator: entry.operator.operator, - value: newField, - }, - entryIndex - ); + const { updatedEntry, index } = getEntryOnMatchAnyChange(entry, newField); + + onChange(updatedEntry, index); }, - [onChange, entryIndex, entry.field, entry.operator.operator] + [onChange, entry] ); const handleFieldListValueChange = useCallback( (newField: ListSchema): void => { - onChange( - { - field: entry.field != null ? entry.field.name : undefined, - type: OperatorTypeEnum.LIST, - operator: entry.operator.operator, - list: { id: newField.id, type: newField.type }, - }, - entryIndex - ); + const { updatedEntry, index } = getEntryOnListChange(entry, newField); + + onChange(updatedEntry, index); }, - [onChange, entryIndex, entry.field, entry.operator.operator] + [onChange, entry] ); - const renderFieldInput = (isFirst: boolean): JSX.Element => { - const comboBox = ( - - ); - - if (isFirst) { - return ( - - {comboBox} - + const renderFieldInput = useCallback( + (isFirst: boolean): JSX.Element => { + const filteredIndexPatterns = getFilteredIndexPatterns(indexPattern, entry); + const comboBox = ( + ); - } else { - return comboBox; - } - }; + + if (isFirst) { + return ( + + {comboBox} + + ); + } else { + return comboBox; + } + }, + [handleFieldChange, indexPattern, entry] + ); const renderOperatorInput = (isFirst: boolean): JSX.Element => { + const operatorOptions = onlyShowListOperators + ? EXCEPTION_OPERATORS_ONLY_LISTS + : getOperatorOptions( + entry, + listType, + entry.field != null && entry.field.type === 'boolean', + isFirst + ); const comboBox = ( = ({ placeholder={i18n.EXCEPTION_FIELD_VALUE_PLACEHOLDER} selectedField={entry.field} selectedValue={value} - isDisabled={isLoading} - isLoading={isLoading} + isDisabled={ + indexPattern == null || (indexPattern != null && indexPattern.fields.length === 0) + } + isLoading={false} isClearable={false} indexPattern={indexPattern} onChange={handleFieldMatchValueChange} @@ -182,8 +190,10 @@ export const EntryItemComponent: React.FC = ({ placeholder={i18n.EXCEPTION_FIELD_VALUE_PLACEHOLDER} selectedField={entry.field} selectedValue={values} - isDisabled={isLoading} - isLoading={isLoading} + isDisabled={ + indexPattern == null || (indexPattern != null && indexPattern.fields.length === 0) + } + isLoading={false} isClearable={false} indexPattern={indexPattern} onChange={handleFieldMatchAnyValueChange} @@ -198,8 +208,10 @@ export const EntryItemComponent: React.FC = ({ selectedField={entry.field} placeholder={i18n.EXCEPTION_FIELD_LISTS_PLACEHOLDER} selectedValue={id} - isLoading={isLoading} - isDisabled={isLoading} + isLoading={false} + isDisabled={ + indexPattern == null || (indexPattern != null && indexPattern.fields.length === 0) + } isClearable={false} onChange={handleFieldListValueChange} isRequired @@ -240,9 +252,14 @@ export const EntryItemComponent: React.FC = ({ > {renderFieldInput(showLabel)} {renderOperatorInput(showLabel)} - {renderFieldValueInput(showLabel, entry.operator.type)} + + {renderFieldValueInput( + showLabel, + entry.nested === 'parent' ? OperatorTypeEnum.EXISTS : entry.operator.type + )} + ); }; -EntryItemComponent.displayName = 'EntryItem'; +BuilderEntryItem.displayName = 'BuilderEntryItem'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_exception_item.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_exception_item.test.tsx index 0f3b6ec2e94e4..584f0971a4193 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_exception_item.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_exception_item.test.tsx @@ -18,8 +18,10 @@ import { getEntryMatchAnyMock } from '../../../../../../lists/common/schemas/typ describe('ExceptionListItemComponent', () => { describe('and badge logic', () => { test('it renders "and" badge with extra top padding for the first exception item when "andLogicIncluded" is "true"', () => { - const exceptionItem = getExceptionListItemSchemaMock(); - exceptionItem.entries = [getEntryMatchMock(), getEntryMatchMock()]; + const exceptionItem = { + ...getExceptionListItemSchemaMock(), + entries: [getEntryMatchMock(), getEntryMatchMock()], + }; const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { title: 'logstash-*', fields, }} - isLoading={false} andLogicIncluded={true} isOnlyItem={false} + listType="detection" + addNested={false} onDeleteExceptionItem={jest.fn()} onChangeExceptionItem={jest.fn()} /> @@ -46,7 +49,7 @@ describe('ExceptionListItemComponent', () => { }); test('it renders "and" badge when more than one exception item entry exists and it is not the first exception item', () => { - const exceptionItem = getExceptionListItemSchemaMock(); + const exceptionItem = { ...getExceptionListItemSchemaMock() }; exceptionItem.entries = [getEntryMatchMock(), getEntryMatchMock()]; const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> @@ -59,9 +62,10 @@ describe('ExceptionListItemComponent', () => { title: 'logstash-*', fields, }} - isLoading={false} andLogicIncluded={true} isOnlyItem={false} + listType="detection" + addNested={false} onDeleteExceptionItem={jest.fn()} onChangeExceptionItem={jest.fn()} /> @@ -72,7 +76,7 @@ describe('ExceptionListItemComponent', () => { }); test('it renders indented "and" badge when "andLogicIncluded" is "true" and only one entry exists', () => { - const exceptionItem = getExceptionListItemSchemaMock(); + const exceptionItem = { ...getExceptionListItemSchemaMock() }; exceptionItem.entries = [getEntryMatchMock()]; const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> @@ -85,9 +89,10 @@ describe('ExceptionListItemComponent', () => { title: 'logstash-*', fields, }} - isLoading={false} andLogicIncluded={true} isOnlyItem={false} + listType="detection" + addNested={false} onDeleteExceptionItem={jest.fn()} onChangeExceptionItem={jest.fn()} /> @@ -100,7 +105,7 @@ describe('ExceptionListItemComponent', () => { }); test('it renders no "and" badge when "andLogicIncluded" is "false"', () => { - const exceptionItem = getExceptionListItemSchemaMock(); + const exceptionItem = { ...getExceptionListItemSchemaMock() }; exceptionItem.entries = [getEntryMatchMock()]; const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> @@ -113,9 +118,10 @@ describe('ExceptionListItemComponent', () => { title: 'logstash-*', fields, }} - isLoading={false} andLogicIncluded={false} isOnlyItem={false} + listType="detection" + addNested={false} onDeleteExceptionItem={jest.fn()} onChangeExceptionItem={jest.fn()} /> @@ -134,8 +140,10 @@ describe('ExceptionListItemComponent', () => { describe('delete button logic', () => { test('it renders delete button disabled when it is only entry left in builder', () => { - const exceptionItem = getExceptionListItemSchemaMock(); - exceptionItem.entries = [getEntryMatchMock()]; + const exceptionItem = { + ...getExceptionListItemSchemaMock(), + entries: [{ ...getEntryMatchMock(), field: '' }], + }; const wrapper = mount( { title: 'logstash-*', fields, }} - isLoading={false} andLogicIncluded={false} isOnlyItem={true} + listType="detection" + addNested={false} onDeleteExceptionItem={jest.fn()} onChangeExceptionItem={jest.fn()} /> @@ -160,7 +169,7 @@ describe('ExceptionListItemComponent', () => { }); test('it does not render delete button disabled when it is not the only entry left in builder', () => { - const exceptionItem = getExceptionListItemSchemaMock(); + const exceptionItem = { ...getExceptionListItemSchemaMock() }; exceptionItem.entries = [getEntryMatchMock()]; const wrapper = mount( @@ -173,9 +182,10 @@ describe('ExceptionListItemComponent', () => { title: 'logstash-*', fields, }} - isLoading={false} andLogicIncluded={false} isOnlyItem={false} + listType="detection" + addNested={false} onDeleteExceptionItem={jest.fn()} onChangeExceptionItem={jest.fn()} /> @@ -187,7 +197,7 @@ describe('ExceptionListItemComponent', () => { }); test('it does not render delete button disabled when "exceptionItemIndex" is not "0"', () => { - const exceptionItem = getExceptionListItemSchemaMock(); + const exceptionItem = { ...getExceptionListItemSchemaMock() }; exceptionItem.entries = [getEntryMatchMock()]; const wrapper = mount( { title: 'logstash-*', fields, }} - isLoading={false} andLogicIncluded={false} // if exceptionItemIndex is not 0, wouldn't make sense for // this to be true, but done for testing purposes isOnlyItem={true} + listType="detection" + addNested={false} onDeleteExceptionItem={jest.fn()} onChangeExceptionItem={jest.fn()} /> @@ -215,7 +226,7 @@ describe('ExceptionListItemComponent', () => { }); test('it does not render delete button disabled when more than one entry exists', () => { - const exceptionItem = getExceptionListItemSchemaMock(); + const exceptionItem = { ...getExceptionListItemSchemaMock() }; exceptionItem.entries = [getEntryMatchMock(), getEntryMatchMock()]; const wrapper = mount( { title: 'logstash-*', fields, }} - isLoading={false} andLogicIncluded={false} isOnlyItem={true} + listType="detection" + addNested={false} onDeleteExceptionItem={jest.fn()} onChangeExceptionItem={jest.fn()} /> @@ -243,7 +255,7 @@ describe('ExceptionListItemComponent', () => { test('it invokes "onChangeExceptionItem" when delete button clicked', () => { const mockOnDeleteExceptionItem = jest.fn(); - const exceptionItem = getExceptionListItemSchemaMock(); + const exceptionItem = { ...getExceptionListItemSchemaMock() }; exceptionItem.entries = [getEntryMatchMock(), getEntryMatchAnyMock()]; const wrapper = mount( { title: 'logstash-*', fields, }} - isLoading={false} andLogicIncluded={false} isOnlyItem={true} + listType="detection" + addNested={false} onDeleteExceptionItem={mockOnDeleteExceptionItem} onChangeExceptionItem={jest.fn()} /> diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_exception_item.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_exception_item.tsx index 8e57e83d0e7e4..50a6150833796 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_exception_item.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/builder_exception_item.tsx @@ -10,9 +10,10 @@ import styled from 'styled-components'; import { IIndexPattern } from '../../../../../../../../src/plugins/data/common'; import { AndOrBadge } from '../../and_or_badge'; -import { EntryItemComponent } from './entry_item'; -import { getFormattedBuilderEntries } from '../helpers'; +import { BuilderEntryItem } from './builder_entry_item'; +import { getFormattedBuilderEntries, getUpdatedEntriesOnDelete } from './helpers'; import { FormattedBuilderEntry, ExceptionsBuilderExceptionItem, BuilderEntry } from '../types'; +import { ExceptionListType } from '../../../../../public/lists_plugin_deps'; const MyInvisibleAndBadge = styled(EuiFlexItem)` visibility: hidden; @@ -22,16 +23,28 @@ const MyFirstRowContainer = styled(EuiFlexItem)` padding-top: 20px; `; +const MyBeautifulLine = styled(EuiFlexItem)` + &:after { + background: ${({ theme }) => theme.eui.euiColorLightShade}; + content: ''; + width: 2px; + height: 40px; + margin: 0 15px; + } +`; + interface ExceptionListItemProps { exceptionItem: ExceptionsBuilderExceptionItem; exceptionId: string; exceptionItemIndex: number; - isLoading: boolean; indexPattern: IIndexPattern; andLogicIncluded: boolean; isOnlyItem: boolean; + listType: ExceptionListType; + addNested: boolean; onDeleteExceptionItem: (item: ExceptionsBuilderExceptionItem, index: number) => void; onChangeExceptionItem: (item: ExceptionsBuilderExceptionItem, index: number) => void; + onlyShowListOperators?: boolean; } export const ExceptionListItemComponent = React.memo( @@ -40,11 +53,13 @@ export const ExceptionListItemComponent = React.memo( exceptionId, exceptionItemIndex, indexPattern, - isLoading, isOnlyItem, + listType, + addNested, andLogicIncluded, onDeleteExceptionItem, onChangeExceptionItem, + onlyShowListOperators = false, }) => { const handleEntryChange = useCallback( (entry: BuilderEntry, entryIndex: number): void => { @@ -63,15 +78,12 @@ export const ExceptionListItemComponent = React.memo( ); const handleDeleteEntry = useCallback( - (entryIndex: number): void => { - const updatedEntries: BuilderEntry[] = [ - ...exceptionItem.entries.slice(0, entryIndex), - ...exceptionItem.entries.slice(entryIndex + 1), - ]; - const updatedExceptionItem: ExceptionsBuilderExceptionItem = { - ...exceptionItem, - entries: updatedEntries, - }; + (entryIndex: number, parentIndex: number | null): void => { + const updatedExceptionItem = getUpdatedEntriesOnDelete( + exceptionItem, + parentIndex ? parentIndex : entryIndex, + parentIndex ? entryIndex : null + ); onDeleteExceptionItem(updatedExceptionItem, exceptionItemIndex); }, @@ -80,80 +92,99 @@ export const ExceptionListItemComponent = React.memo( const entries = useMemo( (): FormattedBuilderEntry[] => - indexPattern != null ? getFormattedBuilderEntries(indexPattern, exceptionItem.entries) : [], - [indexPattern, exceptionItem] + indexPattern != null && exceptionItem.entries.length > 0 + ? getFormattedBuilderEntries(indexPattern, exceptionItem.entries) + : [], + [exceptionItem.entries, indexPattern] ); - const andBadge = useMemo((): JSX.Element => { + const getAndBadge = useCallback((): JSX.Element => { const badge = ; - if (entries.length > 1 && exceptionItemIndex === 0) { + + if (andLogicIncluded && exceptionItem.entries.length > 1 && exceptionItemIndex === 0) { return ( {badge} ); - } else if (entries.length > 1) { + } else if (andLogicIncluded && exceptionItem.entries.length <= 1) { return ( - + {badge} - + ); - } else { + } else if (andLogicIncluded && exceptionItem.entries.length > 1) { return ( - + {badge} - + ); + } else { + return <>; } - }, [entries.length, exceptionItemIndex]); + }, [exceptionItem.entries.length, exceptionItemIndex, andLogicIncluded]); const getDeleteButton = useCallback( - (index: number): JSX.Element => { + (entryIndex: number, parentIndex: number | null): JSX.Element => { const button = ( handleDeleteEntry(index)} - isDisabled={isOnlyItem && entries.length === 1 && exceptionItemIndex === 0} + onClick={() => handleDeleteEntry(entryIndex, parentIndex)} + isDisabled={ + isOnlyItem && + exceptionItem.entries.length === 1 && + exceptionItemIndex === 0 && + (exceptionItem.entries[0].field == null || exceptionItem.entries[0].field === '') + } aria-label="entryDeleteButton" className="exceptionItemEntryDeleteButton" data-test-subj="exceptionItemEntryDeleteButton" /> ); - if (index === 0 && exceptionItemIndex === 0) { + if (entryIndex === 0 && exceptionItemIndex === 0 && parentIndex == null) { return {button}; } else { return {button}; } }, - [entries.length, exceptionItemIndex, handleDeleteEntry, isOnlyItem] + [exceptionItemIndex, exceptionItem.entries, handleDeleteEntry, isOnlyItem] ); return ( - - {andLogicIncluded && andBadge} - - - {entries.map((item, index) => ( - - - - - - {getDeleteButton(index)} - - - ))} - - - + + + {getAndBadge()} + + + {entries.map((item, index) => ( + + + {item.nested === 'child' && } + + + + {getDeleteButton( + item.entryIndex, + item.parent != null ? item.parent.parentIndex : null + )} + + + ))} + + + + ); } ); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/helpers.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/helpers.test.tsx new file mode 100644 index 0000000000000..17c94adf42648 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/helpers.test.tsx @@ -0,0 +1,1027 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { + fields, + getField, +} from '../../../../../../../../src/plugins/data/common/index_patterns/fields/fields.mocks.ts'; +import { getEntryNestedMock } from '../../../../../../lists/common/schemas/types/entry_nested.mock'; +import { getEntryMatchMock } from '../../../../../../lists/common/schemas/types/entry_match.mock'; +import { getEntryMatchAnyMock } from '../../../../../../lists/common/schemas/types/entry_match_any.mock'; +import { getEntryExistsMock } from '../../../../../../lists/common/schemas/types/entry_exists.mock'; +import { getExceptionListItemSchemaMock } from '../../../../../../lists/common/schemas/response/exception_list_item_schema.mock'; +import { getListResponseMock } from '../../../../../../lists/common/schemas/response/list_schema.mock'; +import { + doesNotExistOperator, + EXCEPTION_OPERATORS, + EXCEPTION_OPERATORS_SANS_LISTS, + existsOperator, + isInListOperator, + isNotOneOfOperator, + isNotOperator, + isOneOfOperator, + isOperator, +} from '../../autocomplete/operators'; +import { BuilderEntry, ExceptionsBuilderExceptionItem, FormattedBuilderEntry } from '../types'; +import { IFieldType, IIndexPattern } from '../../../../../../../../src/plugins/data/common'; +import { Entry, EntryNested } from '../../../../lists_plugin_deps'; + +import { + getEntryFromOperator, + getEntryOnFieldChange, + getEntryOnListChange, + getEntryOnMatchAnyChange, + getEntryOnMatchChange, + getEntryOnOperatorChange, + getFilteredIndexPatterns, + getFormattedBuilderEntries, + getFormattedBuilderEntry, + getOperatorOptions, + getUpdatedEntriesOnDelete, + isEntryNested, +} from './helpers'; +import { OperatorOption } from '../../autocomplete/types'; + +const getMockIndexPattern = (): IIndexPattern => ({ + id: '1234', + title: 'logstash-*', + fields, +}); + +const getMockBuilderEntry = (): FormattedBuilderEntry => ({ + field: getField('ip'), + operator: isOperator, + value: 'some value', + nested: undefined, + parent: undefined, + entryIndex: 0, +}); + +const getMockNestedBuilderEntry = (): FormattedBuilderEntry => ({ + field: getField('nestedField.child'), + operator: isOperator, + value: 'some value', + nested: 'child', + parent: { + parent: { + ...getEntryNestedMock(), + field: 'nestedField', + entries: [{ ...getEntryMatchMock(), field: 'child' }], + }, + parentIndex: 0, + }, + entryIndex: 0, +}); + +const getMockNestedParentBuilderEntry = (): FormattedBuilderEntry => ({ + field: { ...getField('nestedField.child'), name: 'nestedField', esTypes: ['nested'] }, + operator: isOperator, + value: undefined, + nested: 'parent', + parent: undefined, + entryIndex: 0, +}); + +describe('Exception builder helpers', () => { + describe('#getFilteredIndexPatterns', () => { + test('it returns nested fields that match parent value when "item.nested" is "child"', () => { + const payloadIndexPattern: IIndexPattern = getMockIndexPattern(); + const payloadItem: FormattedBuilderEntry = getMockNestedBuilderEntry(); + const output = getFilteredIndexPatterns(payloadIndexPattern, payloadItem); + const expected: IIndexPattern = { + fields: [ + { ...getField('nestedField.child') }, + { ...getField('nestedField.nestedChild.doublyNestedChild') }, + ], + id: '1234', + title: 'logstash-*', + }; + expect(output).toEqual(expected); + }); + + test('it returns only parent nested field when "item.nested" is "parent" and nested parent field is not undefined', () => { + const payloadIndexPattern: IIndexPattern = getMockIndexPattern(); + const payloadItem: FormattedBuilderEntry = getMockNestedParentBuilderEntry(); + const output = getFilteredIndexPatterns(payloadIndexPattern, payloadItem); + const expected: IIndexPattern = { + fields: [{ ...getField('nestedField.child'), name: 'nestedField', esTypes: ['nested'] }], + id: '1234', + title: 'logstash-*', + }; + expect(output).toEqual(expected); + }); + + test('it returns only nested fields when "item.nested" is "parent" and nested parent field is undefined', () => { + const payloadIndexPattern: IIndexPattern = getMockIndexPattern(); + const payloadItem: FormattedBuilderEntry = { + ...getMockNestedParentBuilderEntry(), + field: undefined, + }; + const output = getFilteredIndexPatterns(payloadIndexPattern, payloadItem); + const expected: IIndexPattern = { + fields: [ + { ...getField('nestedField.child') }, + { ...getField('nestedField.nestedChild.doublyNestedChild') }, + ], + id: '1234', + title: 'logstash-*', + }; + expect(output).toEqual(expected); + }); + + test('it returns all fields unfiletered if "item.nested" is not "child" or "parent"', () => { + const payloadIndexPattern: IIndexPattern = getMockIndexPattern(); + const payloadItem: FormattedBuilderEntry = getMockBuilderEntry(); + const output = getFilteredIndexPatterns(payloadIndexPattern, payloadItem); + const expected: IIndexPattern = { + fields: [...fields], + id: '1234', + title: 'logstash-*', + }; + expect(output).toEqual(expected); + }); + }); + + describe('#getFormattedBuilderEntry', () => { + test('it returns "FormattedBuilderEntry" with value "nested" of "child" when "parent" and "parentIndex" are defined', () => { + const payloadIndexPattern: IIndexPattern = getMockIndexPattern(); + const payloadItem: BuilderEntry = { ...getEntryMatchMock(), field: 'child' }; + const payloadParent: EntryNested = { + ...getEntryNestedMock(), + field: 'nestedField', + entries: [{ ...getEntryMatchMock(), field: 'child' }], + }; + const output = getFormattedBuilderEntry( + payloadIndexPattern, + payloadItem, + 0, + payloadParent, + 1 + ); + const expected: FormattedBuilderEntry = { + entryIndex: 0, + field: { + aggregatable: false, + count: 0, + esTypes: ['text'], + name: 'nestedField.child', + readFromDocValues: false, + scripted: false, + searchable: true, + subType: { + nested: { + path: 'nestedField', + }, + }, + type: 'string', + }, + nested: 'child', + operator: isOperator, + parent: { + parent: { + entries: [{ ...payloadItem }], + field: 'nestedField', + type: 'nested', + }, + parentIndex: 1, + }, + value: 'some host name', + }; + expect(output).toEqual(expected); + }); + + test('it returns non nested "FormattedBuilderEntry" when "parent" and "parentIndex" are not defined', () => { + const payloadIndexPattern: IIndexPattern = getMockIndexPattern(); + const payloadItem: BuilderEntry = { ...getEntryMatchMock(), field: 'ip', value: 'some ip' }; + const output = getFormattedBuilderEntry( + payloadIndexPattern, + payloadItem, + 0, + undefined, + undefined + ); + const expected: FormattedBuilderEntry = { + entryIndex: 0, + field: { + aggregatable: true, + count: 0, + esTypes: ['ip'], + name: 'ip', + readFromDocValues: true, + scripted: false, + searchable: true, + type: 'ip', + }, + nested: undefined, + operator: isOperator, + parent: undefined, + value: 'some ip', + }; + expect(output).toEqual(expected); + }); + }); + + describe('#isEntryNested', () => { + test('it returns "false" if payload is not of type EntryNested', () => { + const payload: BuilderEntry = { ...getEntryMatchMock() }; + const output = isEntryNested(payload); + const expected = false; + expect(output).toEqual(expected); + }); + + test('it returns "true if payload is of type EntryNested', () => { + const payload: EntryNested = getEntryNestedMock(); + const output = isEntryNested(payload); + const expected = true; + expect(output).toEqual(expected); + }); + }); + + describe('#getFormattedBuilderEntries', () => { + test('it returns formatted entry with field undefined if it unable to find a matching index pattern field', () => { + const payloadIndexPattern: IIndexPattern = getMockIndexPattern(); + const payloadItems: BuilderEntry[] = [{ ...getEntryMatchMock() }]; + const output = getFormattedBuilderEntries(payloadIndexPattern, payloadItems); + const expected: FormattedBuilderEntry[] = [ + { + entryIndex: 0, + field: undefined, + nested: undefined, + operator: isOperator, + parent: undefined, + value: 'some host name', + }, + ]; + expect(output).toEqual(expected); + }); + + test('it returns formatted entries when no nested entries exist', () => { + const payloadIndexPattern: IIndexPattern = getMockIndexPattern(); + const payloadItems: BuilderEntry[] = [ + { ...getEntryMatchMock(), field: 'ip', value: 'some ip' }, + { ...getEntryMatchAnyMock(), field: 'extension', value: ['some extension'] }, + ]; + const output = getFormattedBuilderEntries(payloadIndexPattern, payloadItems); + const expected: FormattedBuilderEntry[] = [ + { + entryIndex: 0, + field: { + aggregatable: true, + count: 0, + esTypes: ['ip'], + name: 'ip', + readFromDocValues: true, + scripted: false, + searchable: true, + type: 'ip', + }, + nested: undefined, + operator: isOperator, + parent: undefined, + value: 'some ip', + }, + { + entryIndex: 1, + field: { + aggregatable: true, + count: 0, + esTypes: ['keyword'], + name: 'extension', + readFromDocValues: true, + scripted: false, + searchable: true, + type: 'string', + }, + nested: undefined, + operator: isOneOfOperator, + parent: undefined, + value: ['some extension'], + }, + ]; + expect(output).toEqual(expected); + }); + + test('it returns formatted entries when nested entries exist', () => { + const payloadIndexPattern: IIndexPattern = getMockIndexPattern(); + const payloadParent: EntryNested = { + ...getEntryNestedMock(), + field: 'nestedField', + entries: [{ ...getEntryMatchMock(), field: 'child' }], + }; + const payloadItems: BuilderEntry[] = [ + { ...getEntryMatchMock(), field: 'ip', value: 'some ip' }, + { ...payloadParent }, + ]; + + const output = getFormattedBuilderEntries(payloadIndexPattern, payloadItems); + const expected: FormattedBuilderEntry[] = [ + { + entryIndex: 0, + field: { + aggregatable: true, + count: 0, + esTypes: ['ip'], + name: 'ip', + readFromDocValues: true, + scripted: false, + searchable: true, + type: 'ip', + }, + nested: undefined, + operator: isOperator, + parent: undefined, + value: 'some ip', + }, + { + entryIndex: 1, + field: { + aggregatable: false, + esTypes: ['nested'], + name: 'nestedField', + searchable: false, + type: 'string', + }, + nested: 'parent', + operator: isOperator, + parent: undefined, + value: undefined, + }, + { + entryIndex: 0, + field: { + aggregatable: false, + count: 0, + esTypes: ['text'], + name: 'nestedField.child', + readFromDocValues: false, + scripted: false, + searchable: true, + subType: { + nested: { + path: 'nestedField', + }, + }, + type: 'string', + }, + nested: 'child', + operator: isOperator, + parent: { + parent: { + entries: [ + { + field: 'child', + operator: 'included', + type: 'match', + value: 'some host name', + }, + ], + field: 'nestedField', + type: 'nested', + }, + parentIndex: 1, + }, + value: 'some host name', + }, + ]; + expect(output).toEqual(expected); + }); + }); + + describe('#getUpdatedEntriesOnDelete', () => { + test('it removes entry corresponding to "entryIndex"', () => { + const payloadItem: ExceptionsBuilderExceptionItem = { ...getExceptionListItemSchemaMock() }; + const output = getUpdatedEntriesOnDelete(payloadItem, 0, null); + const expected: ExceptionsBuilderExceptionItem = { + ...getExceptionListItemSchemaMock(), + entries: [ + { + field: 'some.not.nested.field', + operator: 'included', + type: 'match', + value: 'some value', + }, + ], + }; + expect(output).toEqual(expected); + }); + + test('it removes entry corresponding to "nestedEntryIndex"', () => { + const payloadItem: ExceptionsBuilderExceptionItem = { + ...getExceptionListItemSchemaMock(), + entries: [ + { + ...getEntryNestedMock(), + entries: [{ ...getEntryExistsMock() }, { ...getEntryMatchAnyMock() }], + }, + ], + }; + const output = getUpdatedEntriesOnDelete(payloadItem, 0, 1); + const expected: ExceptionsBuilderExceptionItem = { + ...getExceptionListItemSchemaMock(), + entries: [{ ...getEntryNestedMock(), entries: [{ ...getEntryExistsMock() }] }], + }; + expect(output).toEqual(expected); + }); + + test('it removes entire nested entry if after deleting specified nested entry, there are no more nested entries left', () => { + const payloadItem: ExceptionsBuilderExceptionItem = { + ...getExceptionListItemSchemaMock(), + entries: [ + { + ...getEntryNestedMock(), + entries: [{ ...getEntryExistsMock() }], + }, + ], + }; + const output = getUpdatedEntriesOnDelete(payloadItem, 0, 0); + const expected: ExceptionsBuilderExceptionItem = { + ...getExceptionListItemSchemaMock(), + entries: [], + }; + expect(output).toEqual(expected); + }); + }); + + describe('#getEntryFromOperator', () => { + test('it returns current value when switching from "is" to "is not"', () => { + const payloadOperator: OperatorOption = isNotOperator; + const payloadEntry: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + value: 'I should stay the same', + }; + const output = getEntryFromOperator(payloadOperator, payloadEntry); + const expected: Entry = { + field: 'ip', + operator: 'excluded', + type: 'match', + value: 'I should stay the same', + }; + expect(output).toEqual(expected); + }); + + test('it returns current value when switching from "is not" to "is"', () => { + const payloadOperator: OperatorOption = isOperator; + const payloadEntry: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: isNotOperator, + value: 'I should stay the same', + }; + const output = getEntryFromOperator(payloadOperator, payloadEntry); + const expected: Entry = { + field: 'ip', + operator: 'included', + type: 'match', + value: 'I should stay the same', + }; + expect(output).toEqual(expected); + }); + + test('it returns empty value when switching operator types to "match"', () => { + const payloadOperator: OperatorOption = isOperator; + const payloadEntry: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: isNotOneOfOperator, + value: ['I should stay the same'], + }; + const output = getEntryFromOperator(payloadOperator, payloadEntry); + const expected: Entry = { + field: 'ip', + operator: 'included', + type: 'match', + value: '', + }; + expect(output).toEqual(expected); + }); + + test('it returns current value when switching from "is one of" to "is not one of"', () => { + const payloadOperator: OperatorOption = isNotOneOfOperator; + const payloadEntry: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: isOneOfOperator, + value: ['I should stay the same'], + }; + const output = getEntryFromOperator(payloadOperator, payloadEntry); + const expected: Entry = { + field: 'ip', + operator: 'excluded', + type: 'match_any', + value: ['I should stay the same'], + }; + expect(output).toEqual(expected); + }); + + test('it returns current value when switching from "is not one of" to "is one of"', () => { + const payloadOperator: OperatorOption = isOneOfOperator; + const payloadEntry: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: isNotOneOfOperator, + value: ['I should stay the same'], + }; + const output = getEntryFromOperator(payloadOperator, payloadEntry); + const expected: Entry = { + field: 'ip', + operator: 'included', + type: 'match_any', + value: ['I should stay the same'], + }; + expect(output).toEqual(expected); + }); + + test('it returns empty value when switching operator types to "match_any"', () => { + const payloadOperator: OperatorOption = isOneOfOperator; + const payloadEntry: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: isOperator, + value: 'I should stay the same', + }; + const output = getEntryFromOperator(payloadOperator, payloadEntry); + const expected: Entry = { + field: 'ip', + operator: 'included', + type: 'match_any', + value: [], + }; + expect(output).toEqual(expected); + }); + + test('it returns current value when switching from "exists" to "does not exist"', () => { + const payloadOperator: OperatorOption = doesNotExistOperator; + const payloadEntry: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: existsOperator, + }; + const output = getEntryFromOperator(payloadOperator, payloadEntry); + const expected: Entry = { + field: 'ip', + operator: 'excluded', + type: 'exists', + }; + expect(output).toEqual(expected); + }); + + test('it returns current value when switching from "does not exist" to "exists"', () => { + const payloadOperator: OperatorOption = existsOperator; + const payloadEntry: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: doesNotExistOperator, + }; + const output = getEntryFromOperator(payloadOperator, payloadEntry); + const expected: Entry = { + field: 'ip', + operator: 'included', + type: 'exists', + }; + expect(output).toEqual(expected); + }); + + test('it returns empty value when switching operator types to "exists"', () => { + const payloadOperator: OperatorOption = existsOperator; + const payloadEntry: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: isOperator, + value: 'I should stay the same', + }; + const output = getEntryFromOperator(payloadOperator, payloadEntry); + const expected: Entry = { + field: 'ip', + operator: 'included', + type: 'exists', + }; + expect(output).toEqual(expected); + }); + + test('it returns empty value when switching operator types to "list"', () => { + const payloadOperator: OperatorOption = isInListOperator; + const payloadEntry: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: isOperator, + value: 'I should stay the same', + }; + const output = getEntryFromOperator(payloadOperator, payloadEntry); + const expected: Entry = { + field: 'ip', + operator: 'included', + type: 'list', + list: { id: '', type: 'ip' }, + }; + expect(output).toEqual(expected); + }); + }); + + describe('#getOperatorOptions', () => { + test('it returns "isOperator" if "item.nested" is "parent"', () => { + const payloadItem: FormattedBuilderEntry = getMockNestedParentBuilderEntry(); + const output = getOperatorOptions(payloadItem, 'endpoint', false); + const expected: OperatorOption[] = [isOperator]; + expect(output).toEqual(expected); + }); + + test('it returns "isOperator" if no field selected', () => { + const payloadItem: FormattedBuilderEntry = { ...getMockBuilderEntry(), field: undefined }; + const output = getOperatorOptions(payloadItem, 'endpoint', false); + const expected: OperatorOption[] = [isOperator]; + expect(output).toEqual(expected); + }); + + test('it returns "isOperator" and "isOneOfOperator" if item is nested and "listType" is "endpoint"', () => { + const payloadItem: FormattedBuilderEntry = getMockNestedBuilderEntry(); + const output = getOperatorOptions(payloadItem, 'endpoint', false); + const expected: OperatorOption[] = [isOperator, isOneOfOperator]; + expect(output).toEqual(expected); + }); + + test('it returns "isOperator" and "isOneOfOperator" if "listType" is "endpoint"', () => { + const payloadItem: FormattedBuilderEntry = getMockBuilderEntry(); + const output = getOperatorOptions(payloadItem, 'endpoint', false); + const expected: OperatorOption[] = [isOperator, isOneOfOperator]; + expect(output).toEqual(expected); + }); + + test('it returns "isOperator" if "listType" is "endpoint" and field type is boolean', () => { + const payloadItem: FormattedBuilderEntry = getMockBuilderEntry(); + const output = getOperatorOptions(payloadItem, 'endpoint', true); + const expected: OperatorOption[] = [isOperator]; + expect(output).toEqual(expected); + }); + + test('it returns "isOperator", "isOneOfOperator", and "existsOperator" if item is nested and "listType" is "detection"', () => { + const payloadItem: FormattedBuilderEntry = getMockNestedBuilderEntry(); + const output = getOperatorOptions(payloadItem, 'detection', false); + const expected: OperatorOption[] = [isOperator, isOneOfOperator, existsOperator]; + expect(output).toEqual(expected); + }); + + test('it returns "isOperator" and "existsOperator" if item is nested, "listType" is "detection", and field type is boolean', () => { + const payloadItem: FormattedBuilderEntry = getMockNestedBuilderEntry(); + const output = getOperatorOptions(payloadItem, 'detection', true); + const expected: OperatorOption[] = [isOperator, existsOperator]; + expect(output).toEqual(expected); + }); + + test('it returns all operator options if "listType" is "detection"', () => { + const payloadItem: FormattedBuilderEntry = getMockBuilderEntry(); + const output = getOperatorOptions(payloadItem, 'detection', false); + const expected: OperatorOption[] = EXCEPTION_OPERATORS; + expect(output).toEqual(expected); + }); + + test('it returns "isOperator" and "existsOperator" if field type is boolean', () => { + const payloadItem: FormattedBuilderEntry = getMockBuilderEntry(); + const output = getOperatorOptions(payloadItem, 'detection', true); + const expected: OperatorOption[] = [isOperator, existsOperator]; + expect(output).toEqual(expected); + }); + + test('it returns list operators if specified to', () => { + const payloadItem: FormattedBuilderEntry = getMockBuilderEntry(); + const output = getOperatorOptions(payloadItem, 'detection', false, true); + expect(output).toEqual(EXCEPTION_OPERATORS); + }); + + test('it does not return list operators if specified not to', () => { + const payloadItem: FormattedBuilderEntry = getMockBuilderEntry(); + const output = getOperatorOptions(payloadItem, 'detection', false, false); + expect(output).toEqual(EXCEPTION_OPERATORS_SANS_LISTS); + }); + }); + + describe('#getEntryOnFieldChange', () => { + test('it returns nested entry with single new subentry when "item.nested" is "parent"', () => { + const payloadItem: FormattedBuilderEntry = getMockNestedParentBuilderEntry(); + const payloadIFieldType: IFieldType = getField('nestedField.child'); + const output = getEntryOnFieldChange(payloadItem, payloadIFieldType); + const expected: { updatedEntry: BuilderEntry; index: number } = { + index: 0, + updatedEntry: { + entries: [{ field: 'child', operator: 'included', type: 'match', value: '' }], + field: 'nestedField', + type: 'nested', + }, + }; + expect(output).toEqual(expected); + }); + + test('it returns nested entry with newly selected field value when "item.nested" is "child"', () => { + const payloadItem: FormattedBuilderEntry = { + ...getMockNestedBuilderEntry(), + parent: { + parent: { + ...getEntryNestedMock(), + field: 'nestedField', + entries: [{ ...getEntryMatchMock(), field: 'child' }, getEntryMatchAnyMock()], + }, + parentIndex: 0, + }, + }; + const payloadIFieldType: IFieldType = getField('nestedField.child'); + const output = getEntryOnFieldChange(payloadItem, payloadIFieldType); + const expected: { updatedEntry: BuilderEntry; index: number } = { + index: 0, + updatedEntry: { + entries: [ + { field: 'child', operator: 'included', type: 'match', value: '' }, + getEntryMatchAnyMock(), + ], + field: 'nestedField', + type: 'nested', + }, + }; + expect(output).toEqual(expected); + }); + + test('it returns field of type "match" with updated field if not a nested entry', () => { + const payloadItem: FormattedBuilderEntry = getMockBuilderEntry(); + const payloadIFieldType: IFieldType = getField('ip'); + const output = getEntryOnFieldChange(payloadItem, payloadIFieldType); + const expected: { updatedEntry: BuilderEntry; index: number } = { + index: 0, + updatedEntry: { + field: 'ip', + operator: 'included', + type: 'match', + value: '', + }, + }; + expect(output).toEqual(expected); + }); + }); + + describe('#getEntryOnOperatorChange', () => { + test('it returns updated subentry preserving its value when entry is not switching operator types', () => { + const payloadItem: FormattedBuilderEntry = getMockBuilderEntry(); + const payloadOperator: OperatorOption = isNotOperator; + const output = getEntryOnOperatorChange(payloadItem, payloadOperator); + const expected: { updatedEntry: BuilderEntry; index: number } = { + updatedEntry: { field: 'ip', type: 'match', value: 'some value', operator: 'excluded' }, + index: 0, + }; + expect(output).toEqual(expected); + }); + + test('it returns updated subentry resetting its value when entry is switching operator types', () => { + const payloadItem: FormattedBuilderEntry = getMockBuilderEntry(); + const payloadOperator: OperatorOption = isOneOfOperator; + const output = getEntryOnOperatorChange(payloadItem, payloadOperator); + const expected: { updatedEntry: BuilderEntry; index: number } = { + updatedEntry: { field: 'ip', type: 'match_any', value: [], operator: 'included' }, + index: 0, + }; + expect(output).toEqual(expected); + }); + + test('it returns updated subentry preserving its value when entry is nested and not switching operator types', () => { + const payloadItem: FormattedBuilderEntry = getMockNestedBuilderEntry(); + const payloadOperator: OperatorOption = isNotOperator; + const output = getEntryOnOperatorChange(payloadItem, payloadOperator); + const expected: { updatedEntry: BuilderEntry; index: number } = { + index: 0, + updatedEntry: { + entries: [ + { + field: 'child', + operator: 'excluded', + type: 'match', + value: 'some value', + }, + ], + field: 'nestedField', + type: 'nested', + }, + }; + expect(output).toEqual(expected); + }); + + test('it returns updated subentry resetting its value when entry is nested and switching operator types', () => { + const payloadItem: FormattedBuilderEntry = getMockNestedBuilderEntry(); + const payloadOperator: OperatorOption = isOneOfOperator; + const output = getEntryOnOperatorChange(payloadItem, payloadOperator); + const expected: { updatedEntry: BuilderEntry; index: number } = { + index: 0, + updatedEntry: { + entries: [ + { + field: 'child', + operator: 'included', + type: 'match_any', + value: [], + }, + ], + field: 'nestedField', + type: 'nested', + }, + }; + expect(output).toEqual(expected); + }); + }); + + describe('#getEntryOnMatchChange', () => { + test('it returns entry with updated value', () => { + const payload: FormattedBuilderEntry = getMockBuilderEntry(); + const output = getEntryOnMatchChange(payload, 'jibber jabber'); + const expected: { updatedEntry: BuilderEntry; index: number } = { + updatedEntry: { field: 'ip', type: 'match', value: 'jibber jabber', operator: 'included' }, + index: 0, + }; + expect(output).toEqual(expected); + }); + + test('it returns entry with updated value and "field" of empty string if entry does not have a "field" defined', () => { + const payload: FormattedBuilderEntry = { ...getMockBuilderEntry(), field: undefined }; + const output = getEntryOnMatchChange(payload, 'jibber jabber'); + const expected: { updatedEntry: BuilderEntry; index: number } = { + updatedEntry: { field: '', type: 'match', value: 'jibber jabber', operator: 'included' }, + index: 0, + }; + expect(output).toEqual(expected); + }); + + test('it returns nested entry with updated value', () => { + const payload: FormattedBuilderEntry = getMockNestedBuilderEntry(); + const output = getEntryOnMatchChange(payload, 'jibber jabber'); + const expected: { updatedEntry: BuilderEntry; index: number } = { + index: 0, + updatedEntry: { + entries: [ + { + field: 'child', + operator: 'included', + type: 'match', + value: 'jibber jabber', + }, + ], + field: 'nestedField', + type: 'nested', + }, + }; + expect(output).toEqual(expected); + }); + + test('it returns nested entry with updated value and "field" of empty string if entry does not have a "field" defined', () => { + const payload: FormattedBuilderEntry = { ...getMockNestedBuilderEntry(), field: undefined }; + const output = getEntryOnMatchChange(payload, 'jibber jabber'); + const expected: { updatedEntry: BuilderEntry; index: number } = { + index: 0, + updatedEntry: { + entries: [ + { + field: '', + operator: 'included', + type: 'match', + value: 'jibber jabber', + }, + ], + field: 'nestedField', + type: 'nested', + }, + }; + expect(output).toEqual(expected); + }); + }); + + describe('#getEntryOnMatchAnyChange', () => { + test('it returns entry with updated value', () => { + const payload: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: isOneOfOperator, + value: ['some value'], + }; + const output = getEntryOnMatchAnyChange(payload, ['jibber jabber']); + const expected: { updatedEntry: BuilderEntry; index: number } = { + updatedEntry: { + field: 'ip', + type: 'match_any', + value: ['jibber jabber'], + operator: 'included', + }, + index: 0, + }; + expect(output).toEqual(expected); + }); + + test('it returns entry with updated value and "field" of empty string if entry does not have a "field" defined', () => { + const payload: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: isOneOfOperator, + value: ['some value'], + field: undefined, + }; + const output = getEntryOnMatchAnyChange(payload, ['jibber jabber']); + const expected: { updatedEntry: BuilderEntry; index: number } = { + updatedEntry: { + field: '', + type: 'match_any', + value: ['jibber jabber'], + operator: 'included', + }, + index: 0, + }; + expect(output).toEqual(expected); + }); + + test('it returns nested entry with updated value', () => { + const payload: FormattedBuilderEntry = { + ...getMockNestedBuilderEntry(), + parent: { + parent: { + ...getEntryNestedMock(), + field: 'nestedField', + entries: [{ ...getEntryMatchAnyMock(), field: 'child' }], + }, + parentIndex: 0, + }, + }; + const output = getEntryOnMatchAnyChange(payload, ['jibber jabber']); + const expected: { updatedEntry: BuilderEntry; index: number } = { + index: 0, + updatedEntry: { + entries: [ + { + field: 'child', + operator: 'included', + type: 'match_any', + value: ['jibber jabber'], + }, + ], + field: 'nestedField', + type: 'nested', + }, + }; + expect(output).toEqual(expected); + }); + + test('it returns nested entry with updated value and "field" of empty string if entry does not have a "field" defined', () => { + const payload: FormattedBuilderEntry = { + ...getMockNestedBuilderEntry(), + field: undefined, + parent: { + parent: { + ...getEntryNestedMock(), + field: 'nestedField', + entries: [{ ...getEntryMatchAnyMock(), field: 'child' }], + }, + parentIndex: 0, + }, + }; + const output = getEntryOnMatchAnyChange(payload, ['jibber jabber']); + const expected: { updatedEntry: BuilderEntry; index: number } = { + index: 0, + updatedEntry: { + entries: [ + { + field: '', + operator: 'included', + type: 'match_any', + value: ['jibber jabber'], + }, + ], + field: 'nestedField', + type: 'nested', + }, + }; + expect(output).toEqual(expected); + }); + }); + + describe('#getEntryOnListChange', () => { + test('it returns entry with updated value', () => { + const payload: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: isOneOfOperator, + value: '1234', + }; + const output = getEntryOnListChange(payload, getListResponseMock()); + const expected: { updatedEntry: BuilderEntry; index: number } = { + updatedEntry: { + field: 'ip', + type: 'list', + list: { id: 'some-list-id', type: 'ip' }, + operator: 'included', + }, + index: 0, + }; + expect(output).toEqual(expected); + }); + + test('it returns entry with updated value and "field" of empty string if entry does not have a "field" defined', () => { + const payload: FormattedBuilderEntry = { + ...getMockBuilderEntry(), + operator: isOneOfOperator, + value: '1234', + field: undefined, + }; + const output = getEntryOnListChange(payload, getListResponseMock()); + const expected: { updatedEntry: BuilderEntry; index: number } = { + updatedEntry: { + field: '', + type: 'list', + list: { id: 'some-list-id', type: 'ip' }, + operator: 'included', + }, + index: 0, + }; + expect(output).toEqual(expected); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/helpers.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/helpers.tsx new file mode 100644 index 0000000000000..93bae091885c1 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/helpers.tsx @@ -0,0 +1,558 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { IIndexPattern, IFieldType } from '../../../../../../../../src/plugins/data/common'; +import { + Entry, + OperatorTypeEnum, + EntryNested, + ExceptionListType, + EntryMatch, + EntryMatchAny, + EntryExists, + entriesList, + ListSchema, + OperatorEnum, +} from '../../../../lists_plugin_deps'; +import { + isOperator, + existsOperator, + isOneOfOperator, + EXCEPTION_OPERATORS, + EXCEPTION_OPERATORS_SANS_LISTS, +} from '../../autocomplete/operators'; +import { OperatorOption } from '../../autocomplete/types'; +import { + BuilderEntry, + FormattedBuilderEntry, + ExceptionsBuilderExceptionItem, + EmptyEntry, + EmptyNestedEntry, +} from '../types'; +import { getEntryValue, getExceptionOperatorSelect } from '../helpers'; + +/** + * Returns filtered index patterns based on the field - if a user selects to + * add nested entry, should only show nested fields, if item is the parent + * field of a nested entry, we only display the parent field + * + * @param patterns IIndexPattern containing available fields on rule index + * @param item exception item entry + * set to add a nested field + */ +export const getFilteredIndexPatterns = ( + patterns: IIndexPattern, + item: FormattedBuilderEntry +): IIndexPattern => { + if (item.nested === 'child' && item.parent != null) { + // when user has selected a nested entry, only fields with the common parent are shown + return { + ...patterns, + fields: patterns.fields.filter( + (field) => + field.subType != null && + field.subType.nested != null && + item.parent != null && + field.subType.nested.path.startsWith(item.parent.parent.field) + ), + }; + } else if (item.nested === 'parent' && item.field != null) { + // when user has selected a nested entry, right above it we show the common parent + return { ...patterns, fields: [item.field] }; + } else if (item.nested === 'parent' && item.field == null) { + // when user selects to add a nested entry, only nested fields are shown as options + return { + ...patterns, + fields: patterns.fields.filter( + (field) => field.subType != null && field.subType.nested != null + ), + }; + } else { + return patterns; + } +}; + +/** + * Formats the entry into one that is easily usable for the UI, most of the + * complexity was introduced with nested fields + * + * @param patterns IIndexPattern containing available fields on rule index + * @param item exception item entry + * @param itemIndex entry index + * @param parent nested entries hold copy of their parent for use in various logic + * @param parentIndex corresponds to the entry index, this might seem obvious, but + * was added to ensure that nested items could be identified with their parent entry + */ +export const getFormattedBuilderEntry = ( + indexPattern: IIndexPattern, + item: BuilderEntry, + itemIndex: number, + parent: EntryNested | undefined, + parentIndex: number | undefined +): FormattedBuilderEntry => { + const { fields } = indexPattern; + const field = parent != null ? `${parent.field}.${item.field}` : item.field; + const [selectedField] = fields.filter(({ name }) => field != null && field === name); + + if (parent != null && parentIndex != null) { + return { + field: selectedField, + operator: getExceptionOperatorSelect(item), + value: getEntryValue(item), + nested: 'child', + parent: { parent, parentIndex }, + entryIndex: itemIndex, + }; + } else { + return { + field: selectedField, + operator: getExceptionOperatorSelect(item), + value: getEntryValue(item), + nested: undefined, + parent: undefined, + entryIndex: itemIndex, + }; + } +}; + +export const isEntryNested = (item: BuilderEntry): item is EntryNested => { + return (item as EntryNested).entries != null; +}; + +/** + * Formats the entries to be easily usable for the UI, most of the + * complexity was introduced with nested fields + * + * @param patterns IIndexPattern containing available fields on rule index + * @param entries exception item entries + * @param addNested boolean noting whether or not UI is currently + * set to add a nested field + * @param parent nested entries hold copy of their parent for use in various logic + * @param parentIndex corresponds to the entry index, this might seem obvious, but + * was added to ensure that nested items could be identified with their parent entry + */ +export const getFormattedBuilderEntries = ( + indexPattern: IIndexPattern, + entries: BuilderEntry[], + parent?: EntryNested, + parentIndex?: number +): FormattedBuilderEntry[] => { + return entries.reduce((acc, item, index) => { + const isNewNestedEntry = item.type === 'nested' && item.entries.length === 0; + if (item.type !== 'nested' && !isNewNestedEntry) { + const newItemEntry: FormattedBuilderEntry = getFormattedBuilderEntry( + indexPattern, + item, + index, + parent, + parentIndex + ); + return [...acc, newItemEntry]; + } else { + const parentEntry: FormattedBuilderEntry = { + operator: isOperator, + nested: 'parent', + field: isNewNestedEntry + ? undefined + : { + name: item.field ?? '', + aggregatable: false, + searchable: false, + type: 'string', + esTypes: ['nested'], + }, + value: undefined, + entryIndex: index, + parent: undefined, + }; + + // User has selected to add a nested field, but not yet selected the field + if (isNewNestedEntry) { + return [...acc, parentEntry]; + } + + if (isEntryNested(item)) { + const nestedItems = getFormattedBuilderEntries(indexPattern, item.entries, item, index); + + return [...acc, parentEntry, ...nestedItems]; + } + + return [...acc]; + } + }, []); +}; + +/** + * Determines whether an entire entry, exception item, or entry within a nested + * entry needs to be removed + * + * @param exceptionItem + * @param entryIndex index of given entry, for nested entries, this will correspond + * to their parent index + * @param nestedEntryIndex index of nested entry + * + */ +export const getUpdatedEntriesOnDelete = ( + exceptionItem: ExceptionsBuilderExceptionItem, + entryIndex: number, + nestedEntryIndex: number | null +): ExceptionsBuilderExceptionItem => { + const itemOfInterest: BuilderEntry = exceptionItem.entries[entryIndex]; + + if (nestedEntryIndex != null && itemOfInterest.type === OperatorTypeEnum.NESTED) { + const updatedEntryEntries: Array = [ + ...itemOfInterest.entries.slice(0, nestedEntryIndex), + ...itemOfInterest.entries.slice(nestedEntryIndex + 1), + ]; + + if (updatedEntryEntries.length === 0) { + return { + ...exceptionItem, + entries: [ + ...exceptionItem.entries.slice(0, entryIndex), + ...exceptionItem.entries.slice(entryIndex + 1), + ], + }; + } else { + const { field } = itemOfInterest; + const updatedItemOfInterest: EntryNested | EmptyNestedEntry = { + field, + type: OperatorTypeEnum.NESTED, + entries: updatedEntryEntries, + }; + + return { + ...exceptionItem, + entries: [ + ...exceptionItem.entries.slice(0, entryIndex), + updatedItemOfInterest, + ...exceptionItem.entries.slice(entryIndex + 1), + ], + }; + } + } else { + return { + ...exceptionItem, + entries: [ + ...exceptionItem.entries.slice(0, entryIndex), + ...exceptionItem.entries.slice(entryIndex + 1), + ], + }; + } +}; + +/** + * On operator change, determines whether value needs to be cleared or not + * + * @param field + * @param selectedOperator + * @param currentEntry + * + */ +export const getEntryFromOperator = ( + selectedOperator: OperatorOption, + currentEntry: FormattedBuilderEntry +): Entry => { + const isSameOperatorType = currentEntry.operator.type === selectedOperator.type; + const fieldValue = currentEntry.field != null ? currentEntry.field.name : ''; + switch (selectedOperator.type) { + case 'match': + return { + field: fieldValue, + type: OperatorTypeEnum.MATCH, + operator: selectedOperator.operator, + value: + isSameOperatorType && typeof currentEntry.value === 'string' ? currentEntry.value : '', + }; + case 'match_any': + return { + field: fieldValue, + type: OperatorTypeEnum.MATCH_ANY, + operator: selectedOperator.operator, + value: isSameOperatorType && Array.isArray(currentEntry.value) ? currentEntry.value : [], + }; + case 'list': + return { + field: fieldValue, + type: OperatorTypeEnum.LIST, + operator: selectedOperator.operator, + list: { id: '', type: 'ip' }, + }; + default: + return { + field: fieldValue, + type: OperatorTypeEnum.EXISTS, + operator: selectedOperator.operator, + }; + } +}; + +/** + * Determines which operators to make available + * + * @param item + * @param listType + * @param isBoolean + * @param includeValueListOperators whether or not to include the 'is in list' and 'is not in list' operators + */ +export const getOperatorOptions = ( + item: FormattedBuilderEntry, + listType: ExceptionListType, + isBoolean: boolean, + includeValueListOperators = true +): OperatorOption[] => { + if (item.nested === 'parent' || item.field == null) { + return [isOperator]; + } else if ((item.nested != null && listType === 'endpoint') || listType === 'endpoint') { + return isBoolean ? [isOperator] : [isOperator, isOneOfOperator]; + } else if (item.nested != null && listType === 'detection') { + return isBoolean ? [isOperator, existsOperator] : [isOperator, isOneOfOperator, existsOperator]; + } else { + return isBoolean + ? [isOperator, existsOperator] + : includeValueListOperators + ? EXCEPTION_OPERATORS + : EXCEPTION_OPERATORS_SANS_LISTS; + } +}; + +/** + * Determines proper entry update when user selects new field + * + * @param item - current exception item entry values + * @param newField - newly selected field + * + */ +export const getEntryOnFieldChange = ( + item: FormattedBuilderEntry, + newField: IFieldType +): { updatedEntry: BuilderEntry; index: number } => { + const { parent, entryIndex, nested } = item; + const newChildFieldValue = newField != null ? newField.name.split('.').slice(-1)[0] : ''; + + if (nested === 'parent') { + // For nested entries, when user first selects to add a nested + // entry, they first see a row similiar to what is shown for when + // a user selects "exists", as soon as they make a selection + // we can now identify the 'parent' and 'child' this is where + // we first convert the entry into type "nested" + const newParentFieldValue = + newField.subType != null && newField.subType.nested != null + ? newField.subType.nested.path + : ''; + + return { + updatedEntry: { + field: newParentFieldValue, + type: OperatorTypeEnum.NESTED, + entries: [ + { + field: newChildFieldValue ?? '', + type: OperatorTypeEnum.MATCH, + operator: isOperator.operator, + value: '', + }, + ], + }, + index: entryIndex, + }; + } else if (nested === 'child' && parent != null) { + return { + updatedEntry: { + ...parent.parent, + entries: [ + ...parent.parent.entries.slice(0, entryIndex), + { + field: newChildFieldValue ?? '', + type: OperatorTypeEnum.MATCH, + operator: isOperator.operator, + value: '', + }, + ...parent.parent.entries.slice(entryIndex + 1), + ], + }, + index: parent.parentIndex, + }; + } else { + return { + updatedEntry: { + field: newField != null ? newField.name : '', + type: OperatorTypeEnum.MATCH, + operator: isOperator.operator, + value: '', + }, + index: entryIndex, + }; + } +}; + +/** + * Determines proper entry update when user selects new operator + * + * @param item - current exception item entry values + * @param newOperator - newly selected operator + * + */ +export const getEntryOnOperatorChange = ( + item: FormattedBuilderEntry, + newOperator: OperatorOption +): { updatedEntry: BuilderEntry; index: number } => { + const { parent, entryIndex, field, nested } = item; + const newEntry = getEntryFromOperator(newOperator, item); + + if (!entriesList.is(newEntry) && nested != null && parent != null) { + return { + updatedEntry: { + ...parent.parent, + entries: [ + ...parent.parent.entries.slice(0, entryIndex), + { + ...newEntry, + field: field != null ? field.name.split('.').slice(-1)[0] : '', + }, + ...parent.parent.entries.slice(entryIndex + 1), + ], + }, + index: parent.parentIndex, + }; + } else { + return { updatedEntry: newEntry, index: entryIndex }; + } +}; + +/** + * Determines proper entry update when user updates value + * when operator is of type "match" + * + * @param item - current exception item entry values + * @param newField - newly entered value + * + */ +export const getEntryOnMatchChange = ( + item: FormattedBuilderEntry, + newField: string +): { updatedEntry: BuilderEntry; index: number } => { + const { nested, parent, entryIndex, field, operator } = item; + + if (nested != null && parent != null) { + const fieldName = field != null ? field.name.split('.').slice(-1)[0] : ''; + + return { + updatedEntry: { + ...parent.parent, + entries: [ + ...parent.parent.entries.slice(0, entryIndex), + { + field: fieldName, + type: OperatorTypeEnum.MATCH, + operator: operator.operator, + value: newField, + }, + ...parent.parent.entries.slice(entryIndex + 1), + ], + }, + index: parent.parentIndex, + }; + } else { + return { + updatedEntry: { + field: field != null ? field.name : '', + type: OperatorTypeEnum.MATCH, + operator: operator.operator, + value: newField, + }, + index: entryIndex, + }; + } +}; + +/** + * Determines proper entry update when user updates value + * when operator is of type "match_any" + * + * @param item - current exception item entry values + * @param newField - newly entered value + * + */ +export const getEntryOnMatchAnyChange = ( + item: FormattedBuilderEntry, + newField: string[] +): { updatedEntry: BuilderEntry; index: number } => { + const { nested, parent, entryIndex, field, operator } = item; + + if (nested != null && parent != null) { + const fieldName = field != null ? field.name.split('.').slice(-1)[0] : ''; + + return { + updatedEntry: { + ...parent.parent, + entries: [ + ...parent.parent.entries.slice(0, entryIndex), + { + field: fieldName, + type: OperatorTypeEnum.MATCH_ANY, + operator: operator.operator, + value: newField, + }, + ...parent.parent.entries.slice(entryIndex + 1), + ], + }, + index: parent.parentIndex, + }; + } else { + return { + updatedEntry: { + field: field != null ? field.name : '', + type: OperatorTypeEnum.MATCH_ANY, + operator: operator.operator, + value: newField, + }, + index: entryIndex, + }; + } +}; + +/** + * Determines proper entry update when user updates value + * when operator is of type "list" + * + * @param item - current exception item entry values + * @param newField - newly selected list + * + */ +export const getEntryOnListChange = ( + item: FormattedBuilderEntry, + newField: ListSchema +): { updatedEntry: BuilderEntry; index: number } => { + const { entryIndex, field, operator } = item; + const { id, type } = newField; + + return { + updatedEntry: { + field: field != null ? field.name : '', + type: OperatorTypeEnum.LIST, + operator: operator.operator, + list: { id, type }, + }, + index: entryIndex, + }; +}; + +export const getDefaultEmptyEntry = (): EmptyEntry => ({ + field: '', + type: OperatorTypeEnum.MATCH, + operator: OperatorEnum.INCLUDED, + value: '', +}); + +export const getDefaultNestedEmptyEntry = (): EmptyNestedEntry => ({ + field: '', + type: OperatorTypeEnum.NESTED, + entries: [], +}); + +export const containsValueListEntry = (items: ExceptionsBuilderExceptionItem[]): boolean => + items.some((item) => item.entries.some((entry) => entry.type === OperatorTypeEnum.LIST)); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/index.tsx index f6feca591dc6d..734434484fb4c 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/index.tsx @@ -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, { useCallback, useEffect, useState, useMemo } from 'react'; +import React, { useCallback, useEffect, useMemo, useReducer } from 'react'; import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import styled from 'styled-components'; @@ -17,11 +17,18 @@ import { OperatorEnum, CreateExceptionListItemSchema, ExceptionListType, + entriesNested, } from '../../../../../public/lists_plugin_deps'; import { AndOrBadge } from '../../and_or_badge'; import { BuilderButtonOptions } from './builder_button_options'; import { getNewExceptionItem, filterExceptionItems } from '../helpers'; import { ExceptionsBuilderExceptionItem, CreateExceptionListItemBuilderSchema } from '../types'; +import { State, exceptionsBuilderReducer } from './reducer'; +import { + containsValueListEntry, + getDefaultEmptyEntry, + getDefaultNestedEmptyEntry, +} from './helpers'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import exceptionableFields from '../exceptionable_fields.json'; @@ -39,6 +46,16 @@ const MyButtonsContainer = styled(EuiFlexItem)` margin: 16px 0; `; +const initialState: State = { + disableAnd: false, + disableNested: false, + disableOr: false, + andLogicIncluded: false, + addNested: false, + exceptions: [], + exceptionsToDelete: [], +}; + interface OnChangeProps { exceptionItems: Array; exceptionsToDelete: ExceptionListItemSchema[]; @@ -53,6 +70,7 @@ interface ExceptionBuilderProps { indexPatterns: IIndexPattern; isOrDisabled: boolean; isAndDisabled: boolean; + isNestedDisabled: boolean; onChange: (arg: OnChangeProps) => void; } @@ -65,74 +83,153 @@ export const ExceptionBuilder = ({ indexPatterns, isOrDisabled, isAndDisabled, + isNestedDisabled, onChange, }: ExceptionBuilderProps) => { - const [andLogicIncluded, setAndLogicIncluded] = useState(false); - const [exceptions, setExceptions] = useState( - exceptionListItems + const [ + { + exceptions, + exceptionsToDelete, + andLogicIncluded, + disableAnd, + disableNested, + disableOr, + addNested, + }, + dispatch, + ] = useReducer(exceptionsBuilderReducer(), { + ...initialState, + disableAnd: isAndDisabled, + disableOr: isOrDisabled, + disableNested: isNestedDisabled, + }); + + const setUpdateExceptions = useCallback( + (items: ExceptionsBuilderExceptionItem[]): void => { + dispatch({ + type: 'setExceptions', + exceptions: items, + }); + }, + [dispatch] ); - const [exceptionsToDelete, setExceptionsToDelete] = useState([]); - const handleCheckAndLogic = (items: ExceptionsBuilderExceptionItem[]): void => { - setAndLogicIncluded(items.filter(({ entries }) => entries.length > 1).length > 0); - }; + const setDefaultExceptions = useCallback( + (item: ExceptionsBuilderExceptionItem): void => { + dispatch({ + type: 'setDefault', + initialState, + lastException: item, + }); + }, + [dispatch] + ); - const handleDeleteExceptionItem = ( - item: ExceptionsBuilderExceptionItem, - itemIndex: number - ): void => { - if (item.entries.length === 0) { - if (exceptionListItemSchema.is(item)) { - setExceptionsToDelete((items) => [...items, item]); - } + const setUpdateExceptionsToDelete = useCallback( + (items: ExceptionListItemSchema[]): void => { + dispatch({ + type: 'setExceptionsToDelete', + exceptions: items, + }); + }, + [dispatch] + ); - setExceptions((existingExceptions) => { - const updatedExceptions = [ - ...existingExceptions.slice(0, itemIndex), - ...existingExceptions.slice(itemIndex + 1), - ]; - handleCheckAndLogic(updatedExceptions); + const setUpdateAndDisabled = useCallback( + (shouldDisable: boolean): void => { + dispatch({ + type: 'setDisableAnd', + shouldDisable, + }); + }, + [dispatch] + ); - return updatedExceptions; + const setUpdateOrDisabled = useCallback( + (shouldDisable: boolean): void => { + dispatch({ + type: 'setDisableOr', + shouldDisable, }); - } else { - handleExceptionItemChange(item, itemIndex); - } - }; + }, + [dispatch] + ); - const handleExceptionItemChange = (item: ExceptionsBuilderExceptionItem, index: number): void => { - const updatedExceptions = [ - ...exceptions.slice(0, index), - { - ...item, - }, - ...exceptions.slice(index + 1), - ]; - - handleCheckAndLogic(updatedExceptions); - setExceptions(updatedExceptions); - }; + const setUpdateAddNested = useCallback( + (shouldAddNested: boolean): void => { + dispatch({ + type: 'setAddNested', + addNested: shouldAddNested, + }); + }, + [dispatch] + ); + + const handleExceptionItemChange = useCallback( + (item: ExceptionsBuilderExceptionItem, index: number): void => { + const updatedExceptions = [ + ...exceptions.slice(0, index), + { + ...item, + }, + ...exceptions.slice(index + 1), + ]; - const handleAddNewExceptionItemEntry = useCallback((): void => { - setExceptions((existingExceptions): ExceptionsBuilderExceptionItem[] => { - const lastException = existingExceptions[existingExceptions.length - 1]; + setUpdateExceptions(updatedExceptions); + }, + [setUpdateExceptions, exceptions] + ); + + const handleDeleteExceptionItem = useCallback( + (item: ExceptionsBuilderExceptionItem, itemIndex: number): void => { + if (item.entries.length === 0) { + const updatedExceptions = [ + ...exceptions.slice(0, itemIndex), + ...exceptions.slice(itemIndex + 1), + ]; + + // if it's the only exception item left, don't delete it + // just add a default entry to it + if (updatedExceptions.length === 0) { + setDefaultExceptions(item); + } else if (updatedExceptions.length > 0 && exceptionListItemSchema.is(item)) { + setUpdateExceptionsToDelete([...exceptionsToDelete, item]); + } else { + setUpdateExceptions([ + ...exceptions.slice(0, itemIndex), + ...exceptions.slice(itemIndex + 1), + ]); + } + } else { + handleExceptionItemChange(item, itemIndex); + } + }, + [ + handleExceptionItemChange, + setUpdateExceptions, + setUpdateExceptionsToDelete, + exceptions, + exceptionsToDelete, + setDefaultExceptions, + ] + ); + + const handleAddNewExceptionItemEntry = useCallback( + (isNested = false): void => { + const lastException = exceptions[exceptions.length - 1]; const { entries } = lastException; + const updatedException: ExceptionsBuilderExceptionItem = { ...lastException, - entries: [ - ...entries, - { field: '', type: OperatorTypeEnum.MATCH, operator: OperatorEnum.INCLUDED, value: '' }, - ], + entries: [...entries, isNested ? getDefaultNestedEmptyEntry() : getDefaultEmptyEntry()], }; - setAndLogicIncluded(updatedException.entries.length > 1); + // setAndLogicIncluded(updatedException.entries.length > 1); - return [ - ...existingExceptions.slice(0, existingExceptions.length - 1), - { ...updatedException }, - ]; - }); - }, [setExceptions, setAndLogicIncluded]); + setUpdateExceptions([...exceptions.slice(0, exceptions.length - 1), { ...updatedException }]); + }, + [setUpdateExceptions, exceptions] + ); const handleAddNewExceptionItem = useCallback((): void => { // There is a case where there are numerous exception list items, all with @@ -144,8 +241,8 @@ export const ExceptionBuilder = ({ namespaceType: listNamespaceType, ruleName, }); - setExceptions((existingExceptions) => [...existingExceptions, { ...newException }]); - }, [setExceptions, listType, listId, listNamespaceType, ruleName]); + setUpdateExceptions([...exceptions, { ...newException }]); + }, [setUpdateExceptions, exceptions, listType, listId, listNamespaceType, ruleName]); // Filters index pattern fields by exceptionable fields if list type is endpoint const filterIndexPatterns = useMemo((): IIndexPattern => { @@ -172,6 +269,55 @@ export const ExceptionBuilder = ({ } }; + const handleAddNestedExceptionItemEntry = useCallback((): void => { + const lastException = exceptions[exceptions.length - 1]; + const { entries } = lastException; + const lastEntry = entries[entries.length - 1]; + + if (entriesNested.is(lastEntry)) { + const updatedException: ExceptionsBuilderExceptionItem = { + ...lastException, + entries: [ + ...entries.slice(0, entries.length - 1), + { + ...lastEntry, + entries: [ + ...lastEntry.entries, + { + field: '', + type: OperatorTypeEnum.MATCH, + operator: OperatorEnum.INCLUDED, + value: '', + }, + ], + }, + ], + }; + + setUpdateExceptions([...exceptions.slice(0, exceptions.length - 1), { ...updatedException }]); + } else { + setUpdateExceptions(exceptions); + } + }, [setUpdateExceptions, exceptions]); + + const handleAddNestedClick = useCallback((): void => { + setUpdateAddNested(true); + setUpdateOrDisabled(true); + setUpdateAndDisabled(true); + handleAddNewExceptionItemEntry(true); + }, [ + handleAddNewExceptionItemEntry, + setUpdateAndDisabled, + setUpdateOrDisabled, + setUpdateAddNested, + ]); + + const handleAddClick = useCallback((): void => { + setUpdateAddNested(false); + setUpdateOrDisabled(false); + handleAddNewExceptionItemEntry(); + }, [handleAddNewExceptionItemEntry, setUpdateOrDisabled, setUpdateAddNested]); + // Bubble up changes to parent useEffect(() => { onChange({ exceptionItems: filterExceptionItems(exceptions), exceptionsToDelete }); @@ -188,6 +334,13 @@ export const ExceptionBuilder = ({ } }, [exceptions, handleAddNewExceptionItem]); + useEffect(() => { + if (exceptionListItems.length > 0) { + setUpdateExceptions(exceptionListItems); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + return ( {exceptions.map((exceptionListItem, index) => ( @@ -216,12 +369,14 @@ export const ExceptionBuilder = ({ exceptionItem={exceptionListItem} exceptionId={getExceptionListItemId(exceptionListItem, index)} indexPattern={filterIndexPatterns} - isLoading={indexPatterns.fields.length === 0} + listType={listType} + addNested={addNested} exceptionItemIndex={index} andLogicIncluded={andLogicIncluded} isOnlyItem={exceptions.length === 1} onDeleteExceptionItem={handleDeleteExceptionItem} onChangeExceptionItem={handleExceptionItemChange} + onlyShowListOperators={containsValueListEntry(exceptions)} /> @@ -237,12 +392,15 @@ export const ExceptionBuilder = ({ )} {}} + onAndClicked={handleAddClick} + onNestedClicked={handleAddNestedClick} + onAddClickWhenNested={handleAddNestedExceptionItemEntry} /> diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/reducer.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/reducer.ts new file mode 100644 index 0000000000000..431e91b917bef --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/reducer.ts @@ -0,0 +1,111 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { ExceptionsBuilderExceptionItem } from '../types'; +import { ExceptionListItemSchema, OperatorTypeEnum } from '../../../../../public/lists_plugin_deps'; +import { getDefaultEmptyEntry } from './helpers'; + +export type ViewerModalName = 'addModal' | 'editModal' | null; + +export interface State { + disableAnd: boolean; + disableNested: boolean; + disableOr: boolean; + andLogicIncluded: boolean; + addNested: boolean; + exceptions: ExceptionsBuilderExceptionItem[]; + exceptionsToDelete: ExceptionListItemSchema[]; +} + +export type Action = + | { + type: 'setExceptions'; + exceptions: ExceptionsBuilderExceptionItem[]; + } + | { + type: 'setExceptionsToDelete'; + exceptions: ExceptionListItemSchema[]; + } + | { + type: 'setDefault'; + initialState: State; + lastException: ExceptionsBuilderExceptionItem; + } + | { + type: 'setDisableAnd'; + shouldDisable: boolean; + } + | { + type: 'setDisableOr'; + shouldDisable: boolean; + } + | { + type: 'setAddNested'; + addNested: boolean; + }; + +export const exceptionsBuilderReducer = () => (state: State, action: Action): State => { + switch (action.type) { + case 'setExceptions': { + const isAndLogicIncluded = + action.exceptions.filter(({ entries }) => entries.length > 1).length > 0; + const lastExceptionItem = action.exceptions.slice(-1)[0]; + const isAddNested = + lastExceptionItem != null + ? lastExceptionItem.entries.slice(-1).filter(({ type }) => type === 'nested').length > 0 + : false; + const lastEntry = lastExceptionItem != null ? lastExceptionItem.entries.slice(-1)[0] : null; + const isAndDisabled = + lastEntry != null && lastEntry.type === 'nested' && lastEntry.entries.length === 0; + const isOrDisabled = lastEntry != null && lastEntry.type === 'nested'; + const containsValueList = action.exceptions.some( + ({ entries }) => entries.filter(({ type }) => type === OperatorTypeEnum.LIST).length > 0 + ); + + return { + ...state, + andLogicIncluded: isAndLogicIncluded, + exceptions: action.exceptions, + addNested: isAddNested, + disableAnd: isAndDisabled, + disableOr: isOrDisabled, + disableNested: containsValueList, + }; + } + case 'setDefault': { + return { + ...state, + ...action.initialState, + exceptions: [{ ...action.lastException, entries: [getDefaultEmptyEntry()] }], + }; + } + case 'setExceptionsToDelete': { + return { + ...state, + exceptionsToDelete: action.exceptions, + }; + } + case 'setDisableAnd': { + return { + ...state, + disableAnd: action.shouldDisable, + }; + } + case 'setDisableOr': { + return { + ...state, + disableOr: action.shouldDisable, + }; + } + case 'setAddNested': { + return { + ...state, + addNested: action.addNested, + }; + } + default: + return state; + } +}; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/translations.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/translations.ts new file mode 100644 index 0000000000000..82cca2596da61 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/translations.ts @@ -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 { i18n } from '@kbn/i18n'; + +export const FIELD = i18n.translate('xpack.securitySolution.exceptions.builder.fieldDescription', { + defaultMessage: 'Field', +}); + +export const OPERATOR = i18n.translate( + 'xpack.securitySolution.exceptions.builder.operatorDescription', + { + defaultMessage: 'Operator', + } +); + +export const VALUE = i18n.translate('xpack.securitySolution.exceptions.builder.valueDescription', { + defaultMessage: 'Value', +}); + +export const EXCEPTION_FIELD_PLACEHOLDER = i18n.translate( + 'xpack.securitySolution.exceptions.builder.exceptionFieldPlaceholderDescription', + { + defaultMessage: 'Search', + } +); + +export const EXCEPTION_FIELD_NESTED_PLACEHOLDER = i18n.translate( + 'xpack.securitySolution.exceptions.builder.exceptionFieldNestedPlaceholderDescription', + { + defaultMessage: 'Search nested field', + } +); + +export const EXCEPTION_OPERATOR_PLACEHOLDER = i18n.translate( + 'xpack.securitySolution.exceptions.builder.exceptionOperatorPlaceholderDescription', + { + defaultMessage: 'Operator', + } +); + +export const EXCEPTION_FIELD_VALUE_PLACEHOLDER = i18n.translate( + 'xpack.securitySolution.exceptions.builder.exceptionFieldValuePlaceholderDescription', + { + defaultMessage: 'Search field value...', + } +); + +export const EXCEPTION_FIELD_LISTS_PLACEHOLDER = i18n.translate( + 'xpack.securitySolution.exceptions.builder.exceptionListsPlaceholderDescription', + { + defaultMessage: 'Search for list...', + } +); + +export const ADD_NESTED_DESCRIPTION = i18n.translate( + 'xpack.securitySolution.exceptions.builder.addNestedDescription', + { + defaultMessage: 'Add nested condition', + } +); + +export const ADD_NON_NESTED_DESCRIPTION = i18n.translate( + 'xpack.securitySolution.exceptions.builder.addNonNestedDescription', + { + defaultMessage: 'Add non-nested condition', + } +); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.tsx index 2d12cfbec160a..341d2f2bab37a 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { memo, useState, useCallback, useEffect } from 'react'; +import React, { memo, useState, useCallback, useEffect, useMemo } from 'react'; import styled, { css } from 'styled-components'; import { EuiModal, @@ -19,6 +19,7 @@ import { EuiSpacer, EuiFormRow, EuiText, + EuiCallOut, } from '@elastic/eui'; import { useFetchIndexPatterns } from '../../../../detections/containers/detection_engine/rules'; import { useSignalIndex } from '../../../../detections/containers/detection_engine/alerts/use_signal_index'; @@ -34,7 +35,7 @@ import { ExceptionBuilder } from '../builder'; import { useAddOrUpdateException } from '../use_add_exception'; import { AddExceptionComments } from '../add_exception_comments'; import { - enrichExceptionItemsWithComments, + enrichExistingExceptionItemWithComments, enrichExceptionItemsWithOS, getOperatingSystems, entryHasListType, @@ -53,7 +54,8 @@ interface EditExceptionModalProps { const Modal = styled(EuiModal)` ${({ theme }) => css` - width: ${theme.eui.euiBreakpoints.m}; + width: ${theme.eui.euiBreakpoints.l}; + max-width: ${theme.eui.euiBreakpoints.l}; `} `; @@ -88,6 +90,7 @@ export const EditExceptionModal = memo(function EditExceptionModal({ }: EditExceptionModalProps) { const { http } = useKibana().services; const [comment, setComment] = useState(''); + const [hasVersionConflict, setHasVersionConflict] = useState(false); const [shouldBulkCloseAlert, setShouldBulkCloseAlert] = useState(false); const [shouldDisableBulkClose, setShouldDisableBulkClose] = useState(false); const [exceptionItemsToAdd, setExceptionItemsToAdd] = useState< @@ -106,8 +109,12 @@ export const EditExceptionModal = memo(function EditExceptionModal({ const onError = useCallback( (error) => { - addError(error, { title: i18n.EDIT_EXCEPTION_ERROR }); - onCancel(); + if (error.message.includes('Conflict')) { + setHasVersionConflict(true); + } else { + addError(error, { title: i18n.EDIT_EXCEPTION_ERROR }); + onCancel(); + } }, [addError, onCancel] ); @@ -146,6 +153,11 @@ export const EditExceptionModal = memo(function EditExceptionModal({ } }, [shouldDisableBulkClose]); + const isSubmitButtonDisabled = useMemo( + () => exceptionItemsToAdd.every((item) => item.entries.length === 0) || hasVersionConflict, + [exceptionItemsToAdd, hasVersionConflict] + ); + const handleBuilderOnChange = useCallback( ({ exceptionItems, @@ -172,11 +184,15 @@ export const EditExceptionModal = memo(function EditExceptionModal({ ); const enrichExceptionItems = useCallback(() => { - let enriched: Array = []; - enriched = enrichExceptionItemsWithComments(exceptionItemsToAdd, [ - ...(exceptionItem.comments ? exceptionItem.comments : []), - ...(comment !== '' ? [{ comment }] : []), - ]); + const [exceptionItemToEdit] = exceptionItemsToAdd; + let enriched: Array = [ + { + ...enrichExistingExceptionItemWithComments(exceptionItemToEdit, [ + ...exceptionItem.comments, + ...(comment.trim() !== '' ? [{ comment }] : []), + ]), + }, + ]; if (exceptionListType === 'endpoint') { const osTypes = exceptionItem._tags ? getOperatingSystems(exceptionItem._tags) : []; enriched = enrichExceptionItemsWithOS(enriched, osTypes); @@ -196,7 +212,11 @@ export const EditExceptionModal = memo(function EditExceptionModal({ - {i18n.EDIT_EXCEPTION_TITLE} + + {exceptionListType === 'endpoint' + ? i18n.EDIT_ENDPOINT_EXCEPTION_TITLE + : i18n.EDIT_EXCEPTION_TITLE} + {ruleName} @@ -217,8 +237,9 @@ export const EditExceptionModal = memo(function EditExceptionModal({ listId={exceptionItem.list_id} listNamespaceType={exceptionItem.namespace_type} ruleName={ruleName} - isOrDisabled={false} + isOrDisabled isAndDisabled={false} + isNestedDisabled={false} data-test-subj="edit-exception-modal-builder" id-aria="edit-exception-modal-builder" onChange={handleBuilderOnChange} @@ -227,13 +248,6 @@ export const EditExceptionModal = memo(function EditExceptionModal({ - {exceptionListType === 'endpoint' && ( - <> - {i18n.ENDPOINT_QUARANTINE_TEXT} - - - )} - + {exceptionListType === 'endpoint' && ( + <> + + + {i18n.ENDPOINT_QUARANTINE_TEXT} + + + )} )} + {hasVersionConflict && ( + + +

{i18n.VERSION_CONFLICT_ERROR_DESCRIPTION}

+
+
+ )} + {i18n.CANCEL} - + {i18n.EDIT_EXCEPTION_SAVE_BUTTON} diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/translations.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/translations.ts index 6c5cb733b7a73..c5b6fc8a6a9ae 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/translations.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/translations.ts @@ -24,6 +24,13 @@ export const EDIT_EXCEPTION_TITLE = i18n.translate( } ); +export const EDIT_ENDPOINT_EXCEPTION_TITLE = i18n.translate( + 'xpack.securitySolution.exceptions.editException.editEndpointExceptionTitle', + { + defaultMessage: 'Edit Endpoint Exception', + } +); + export const EDIT_EXCEPTION_ERROR = i18n.translate( 'xpack.securitySolution.exceptions.editException.error', { @@ -41,7 +48,8 @@ export const EDIT_EXCEPTION_SUCCESS = i18n.translate( export const BULK_CLOSE_LABEL = i18n.translate( 'xpack.securitySolution.exceptions.editException.bulkCloseLabel', { - defaultMessage: 'Close all alerts that match attributes in this exception', + defaultMessage: + 'Close all alerts that match this exception, including alerts generated by other rules', } ); @@ -57,7 +65,7 @@ export const ENDPOINT_QUARANTINE_TEXT = i18n.translate( 'xpack.securitySolution.exceptions.editException.endpointQuarantineText', { defaultMessage: - 'Any file in quarantine on any endpoint that matches the attribute(s) selected will automatically be restored to its original location', + 'Any file in quarantine on any endpoint that matches the attribute(s) selected will automatically be restored to its original location. This exception will apply to any rule that is linked to the Global Endpoint Exception List.', } ); @@ -67,3 +75,18 @@ export const EXCEPTION_BUILDER_INFO = i18n.translate( defaultMessage: "Alerts are generated when the rule's conditions are met, except when:", } ); + +export const VERSION_CONFLICT_ERROR_TITLE = i18n.translate( + 'xpack.securitySolution.exceptions.editException.versionConflictTitle', + { + defaultMessage: 'Sorry, there was an error', + } +); + +export const VERSION_CONFLICT_ERROR_DESCRIPTION = i18n.translate( + 'xpack.securitySolution.exceptions.editException.versionConflictDescription', + { + defaultMessage: + "It appears this exception was updated since you first selected to edit it. Try clicking 'Cancel' and editing the exception again.", + } +); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/exceptionable_fields.json b/x-pack/plugins/security_solution/public/common/components/exceptions/exceptionable_fields.json index 18257b0de0a17..fdf0ea60ecf6a 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/exceptionable_fields.json +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/exceptionable_fields.json @@ -7,25 +7,32 @@ "Target.process.Ext.services", "Target.process.Ext.user", "Target.process.command_line", + "Target.process.command_line.text", "Target.process.executable", + "Target.process.executable.text", "Target.process.hash.md5", "Target.process.hash.sha1", "Target.process.hash.sha256", "Target.process.hash.sha512", "Target.process.name", + "Target.process.name.text", "Target.process.parent.Ext.code_signature.status", "Target.process.parent.Ext.code_signature.subject_name", "Target.process.parent.Ext.code_signature.trusted", "Target.process.parent.Ext.code_signature.valid", "Target.process.parent.command_line", + "Target.process.parent.command_line.text", "Target.process.parent.executable", + "Target.process.parent.executable.text", "Target.process.parent.hash.md5", "Target.process.parent.hash.sha1", "Target.process.parent.hash.sha256", "Target.process.parent.hash.sha512", "Target.process.parent.name", + "Target.process.parent.name.text", "Target.process.parent.pgid", "Target.process.parent.working_directory", + "Target.process.parent.working_directory.text", "Target.process.pe.company", "Target.process.pe.description", "Target.process.pe.file_version", @@ -33,6 +40,7 @@ "Target.process.pe.product", "Target.process.pgid", "Target.process.working_directory", + "Target.process.working_directory.text", "agent.id", "agent.type", "agent.version", @@ -67,6 +75,7 @@ "file.name", "file.owner", "file.path", + "file.path.text", "file.pe.company", "file.pe.description", "file.pe.file_version", @@ -74,6 +83,7 @@ "file.pe.product", "file.size", "file.target_path", + "file.target_path.text", "file.type", "file.uid", "group.Ext.real.id", @@ -85,8 +95,10 @@ "host.os.Ext.variant", "host.os.family", "host.os.full", + "host.os.full.text", "host.os.kernel", "host.os.name", + "host.os.name.text", "host.os.platform", "host.os.version", "host.type", @@ -97,25 +109,32 @@ "process.Ext.services", "process.Ext.user", "process.command_line", + "process.command_line.text", "process.executable", + "process.executable.text", "process.hash.md5", "process.hash.sha1", "process.hash.sha256", "process.hash.sha512", "process.name", + "process.name.text", "process.parent.Ext.code_signature.status", "process.parent.Ext.code_signature.subject_name", "process.parent.Ext.code_signature.trusted", "process.parent.Ext.code_signature.valid", "process.parent.command_line", + "process.parent.command_line.text", "process.parent.executable", + "process.parent.executable.text", "process.parent.hash.md5", "process.parent.hash.sha1", "process.parent.hash.sha256", "process.parent.hash.sha512", "process.parent.name", + "process.parent.name.text", "process.parent.pgid", "process.parent.working_directory", + "process.parent.working_directory.text", "process.pe.company", "process.pe.description", "process.pe.file_version", @@ -123,5 +142,6 @@ "process.pe.product", "process.pgid", "process.working_directory", + "process.working_directory.text", "rule.uuid" ] \ No newline at end of file diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.test.tsx index dace2eb5f0672..5cb65ee6db8ff 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.test.tsx @@ -10,24 +10,22 @@ import moment from 'moment-timezone'; import { getOperatorType, getExceptionOperatorSelect, - getFormattedEntries, - formatEntry, getOperatingSystems, getTagsInclude, - getDescriptionListContent, getFormattedComments, filterExceptionItems, getNewExceptionItem, formatOperatingSystems, getEntryValue, formatExceptionItemForUpdate, - enrichExceptionItemsWithComments, + enrichNewExceptionItemsWithComments, + enrichExistingExceptionItemWithComments, enrichExceptionItemsWithOS, entryHasListType, entryHasNonEcsType, prepareExceptionItemsForBulkClose, } from './helpers'; -import { FormattedEntry, DescriptionListItem, EmptyEntry } from './types'; +import { EmptyEntry } from './types'; import { isOperator, isNotOperator, @@ -38,15 +36,14 @@ import { existsOperator, doesNotExistOperator, } from '../autocomplete/operators'; -import { OperatorTypeEnum, OperatorEnum, EntryNested } from '../../../lists_plugin_deps'; +import { OperatorTypeEnum, OperatorEnum, EntryNested } from '../../../shared_imports'; import { getExceptionListItemSchemaMock } from '../../../../../lists/common/schemas/response/exception_list_item_schema.mock'; import { getEntryMatchMock } from '../../../../../lists/common/schemas/types/entry_match.mock'; import { getEntryMatchAnyMock } from '../../../../../lists/common/schemas/types/entry_match_any.mock'; import { getEntryExistsMock } from '../../../../../lists/common/schemas/types/entry_exists.mock'; import { getEntryListMock } from '../../../../../lists/common/schemas/types/entry_list.mock'; -import { getCommentsArrayMock } from '../../../../../lists/common/schemas/types/comments.mock'; -import { getEntriesArrayMock } from '../../../../../lists/common/schemas/types/entries.mock'; -import { ENTRIES } from '../../../../../lists/common/constants.mock'; +import { getCommentsArrayMock } from '../../../../../lists/common/schemas/types/comment.mock'; +import { ENTRIES, OLD_DATE_RELATIVE_TO_DATE_NOW } from '../../../../../lists/common/constants.mock'; import { CreateExceptionListItemSchema, ExceptionListItemSchema, @@ -155,112 +152,6 @@ describe('Exception helpers', () => { }); }); - describe('#getFormattedEntries', () => { - test('it returns empty array if no entries passed', () => { - const result = getFormattedEntries([]); - - expect(result).toEqual([]); - }); - - test('it formats nested entries as expected', () => { - const payload = [getEntryMatchMock()]; - const result = getFormattedEntries(payload); - const expected: FormattedEntry[] = [ - { - fieldName: 'host.name', - isNested: false, - operator: 'is', - value: 'some host name', - }, - ]; - expect(result).toEqual(expected); - }); - - test('it formats "exists" entries as expected', () => { - const payload = [getEntryExistsMock()]; - const result = getFormattedEntries(payload); - const expected: FormattedEntry[] = [ - { - fieldName: 'host.name', - isNested: false, - operator: 'exists', - value: undefined, - }, - ]; - expect(result).toEqual(expected); - }); - - test('it formats non-nested entries as expected', () => { - const payload = [getEntryMatchAnyMock(), getEntryMatchMock()]; - const result = getFormattedEntries(payload); - const expected: FormattedEntry[] = [ - { - fieldName: 'host.name', - isNested: false, - operator: 'is one of', - value: ['some host name'], - }, - { - fieldName: 'host.name', - isNested: false, - operator: 'is', - value: 'some host name', - }, - ]; - expect(result).toEqual(expected); - }); - - test('it formats a mix of nested and non-nested entries as expected', () => { - const payload = getEntriesArrayMock(); - const result = getFormattedEntries(payload); - const expected: FormattedEntry[] = [ - { - fieldName: 'host.name', - isNested: false, - operator: 'is', - value: 'some host name', - }, - { - fieldName: 'host.name', - isNested: false, - operator: 'is one of', - value: ['some host name'], - }, - { - fieldName: 'host.name', - isNested: false, - operator: 'is in list', - value: 'some-list-id', - }, - { - fieldName: 'host.name', - isNested: false, - operator: 'exists', - value: undefined, - }, - { - fieldName: 'host.name', - isNested: false, - operator: undefined, - value: undefined, - }, - { - fieldName: 'host.name.host.name', - isNested: true, - operator: 'is', - value: 'some host name', - }, - { - fieldName: 'host.name.host.name', - isNested: true, - operator: 'is one of', - value: ['some host name'], - }, - ]; - expect(result).toEqual(expected); - }); - }); - describe('#getEntryValue', () => { it('returns "match" entry value', () => { const payload = getEntryMatchMock(); @@ -291,34 +182,6 @@ describe('Exception helpers', () => { }); }); - describe('#formatEntry', () => { - test('it formats an entry', () => { - const payload = getEntryMatchMock(); - const formattedEntry = formatEntry({ isNested: false, item: payload }); - const expected: FormattedEntry = { - fieldName: 'host.name', - isNested: false, - operator: 'is', - value: 'some host name', - }; - - expect(formattedEntry).toEqual(expected); - }); - - test('it formats as expected when "isNested" is "true"', () => { - const payload = getEntryMatchMock(); - const formattedEntry = formatEntry({ isNested: true, parent: 'parent', item: payload }); - const expected: FormattedEntry = { - fieldName: 'parent.host.name', - isNested: true, - operator: 'is', - value: 'some host name', - }; - - expect(formattedEntry).toEqual(expected); - }); - }); - describe('#getOperatingSystems', () => { test('it returns null if no operating system tag specified', () => { const result = getOperatingSystems(['some tag', 'some other tag']); @@ -389,72 +252,6 @@ describe('Exception helpers', () => { }); }); - describe('#getDescriptionListContent', () => { - test('it returns formatted description list with os if one is specified', () => { - const payload = getExceptionListItemSchemaMock(); - payload.description = ''; - const result = getDescriptionListContent(payload); - const expected: DescriptionListItem[] = [ - { - description: 'Linux', - title: 'OS', - }, - { - description: 'April 20th 2020 @ 15:25:31', - title: 'Date created', - }, - { - description: 'some user', - title: 'Created by', - }, - ]; - - expect(result).toEqual(expected); - }); - - test('it returns formatted description list with a description if one specified', () => { - const payload = getExceptionListItemSchemaMock(); - payload._tags = []; - payload.description = 'Im a description'; - const result = getDescriptionListContent(payload); - const expected: DescriptionListItem[] = [ - { - description: 'April 20th 2020 @ 15:25:31', - title: 'Date created', - }, - { - description: 'some user', - title: 'Created by', - }, - { - description: 'Im a description', - title: 'Comment', - }, - ]; - - expect(result).toEqual(expected); - }); - - test('it returns just user and date created if no other fields specified', () => { - const payload = getExceptionListItemSchemaMock(); - payload._tags = []; - payload.description = ''; - const result = getDescriptionListContent(payload); - const expected: DescriptionListItem[] = [ - { - description: 'April 20th 2020 @ 15:25:31', - title: 'Date created', - }, - { - description: 'some user', - title: 'Created by', - }, - ]; - - expect(result).toEqual(expected); - }); - }); - describe('#getFormattedComments', () => { test('it returns formatted comment object with username and timestamp', () => { const payload = getCommentsArrayMock(); @@ -614,12 +411,52 @@ describe('Exception helpers', () => { expect(result).toEqual(expected); }); }); + describe('#enrichExistingExceptionItemWithComments', () => { + test('it should return exception item with comments stripped of "created_by", "created_at", "updated_by", "updated_at" fields', () => { + const payload = getExceptionListItemSchemaMock(); + const comments = [ + { + comment: 'Im an existing comment', + created_at: OLD_DATE_RELATIVE_TO_DATE_NOW, + created_by: 'lily', + id: '1', + }, + { + comment: 'Im another existing comment', + created_at: OLD_DATE_RELATIVE_TO_DATE_NOW, + created_by: 'lily', + id: '2', + }, + { + comment: 'Im a new comment', + }, + ]; + const result = enrichExistingExceptionItemWithComments(payload, comments); + const expected = { + ...getExceptionListItemSchemaMock(), + comments: [ + { + comment: 'Im an existing comment', + id: '1', + }, + { + comment: 'Im another existing comment', + id: '2', + }, + { + comment: 'Im a new comment', + }, + ], + }; + expect(result).toEqual(expected); + }); + }); - describe('#enrichExceptionItemsWithComments', () => { + describe('#enrichNewExceptionItemsWithComments', () => { test('it should add comments to an exception item', () => { const payload = [getExceptionListItemSchemaMock()]; const comments = getCommentsArrayMock(); - const result = enrichExceptionItemsWithComments(payload, comments); + const result = enrichNewExceptionItemsWithComments(payload, comments); const expected = [ { ...getExceptionListItemSchemaMock(), @@ -632,7 +469,7 @@ describe('Exception helpers', () => { test('it should add comments to multiple exception items', () => { const payload = [getExceptionListItemSchemaMock(), getExceptionListItemSchemaMock()]; const comments = getCommentsArrayMock(); - const result = enrichExceptionItemsWithComments(payload, comments); + const result = enrichNewExceptionItemsWithComments(payload, comments); const expected = [ { ...getExceptionListItemSchemaMock(), diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.tsx index 4d8fc5f68870b..3abb788312ff4 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.tsx @@ -12,10 +12,7 @@ import uuid from 'uuid'; import * as i18n from './translations'; import { - FormattedEntry, BuilderEntry, - DescriptionListItem, - FormattedBuilderEntry, CreateExceptionListItemBuilderSchema, ExceptionsBuilderExceptionItem, } from './types'; @@ -23,13 +20,14 @@ import { EXCEPTION_OPERATORS, isOperator } from '../autocomplete/operators'; import { OperatorOption } from '../autocomplete/types'; import { CommentsArray, - Comments, - CreateComments, + Comment, + CreateComment, Entry, ExceptionListItemSchema, NamespaceType, OperatorTypeEnum, CreateExceptionListItemSchema, + comment, entry, entriesNested, createExceptionListItemSchema, @@ -37,8 +35,8 @@ import { UpdateExceptionListItemSchema, ExceptionListType, EntryNested, -} from '../../../lists_plugin_deps'; -import { IFieldType, IIndexPattern } from '../../../../../../../src/plugins/data/common'; +} from '../../../shared_imports'; +import { IIndexPattern } from '../../../../../../../src/plugins/data/common'; import { validate } from '../../../../common/validate'; import { TimelineNonEcsData } from '../../../graphql/types'; import { WithCopyToClipboard } from '../../lib/clipboard/with_copy_to_clipboard'; @@ -68,7 +66,7 @@ export const getOperatorType = (item: BuilderEntry): OperatorTypeEnum => { * @param item a single ExceptionItem entry */ export const getExceptionOperatorSelect = (item: BuilderEntry): OperatorOption => { - if (entriesNested.is(item)) { + if (item.type === 'nested') { return isOperator; } else { const operatorType = getOperatorType(item); @@ -81,39 +79,10 @@ export const getExceptionOperatorSelect = (item: BuilderEntry): OperatorOption = }; /** - * Formats ExceptionItem entries into simple field, operator, value - * for use in rendering items in table + * Returns the fields corresponding value for an entry * - * @param entries an ExceptionItem's entries + * @param item a single ExceptionItem entry */ -export const getFormattedEntries = (entries: BuilderEntry[]): FormattedEntry[] => { - const formattedEntries = entries.map((item) => { - if (entriesNested.is(item)) { - const parent = { - fieldName: item.field, - operator: undefined, - value: undefined, - isNested: false, - }; - return item.entries.reduce( - (acc, nestedEntry) => { - const formattedEntry = formatEntry({ - isNested: true, - parent: item.field, - item: nestedEntry, - }); - return [...acc, { ...formattedEntry }]; - }, - [parent] - ); - } else { - return formatEntry({ isNested: false, item }); - } - }); - - return formattedEntries.flat(); -}; - export const getEntryValue = (item: BuilderEntry): string | string[] | undefined => { switch (item.type) { case OperatorTypeEnum.MATCH: @@ -128,29 +97,6 @@ export const getEntryValue = (item: BuilderEntry): string | string[] | undefined } }; -/** - * Helper method for `getFormattedEntries` - */ -export const formatEntry = ({ - isNested, - parent, - item, -}: { - isNested: boolean; - parent?: string; - item: BuilderEntry; -}): FormattedEntry => { - const operator = getExceptionOperatorSelect(item); - const value = getEntryValue(item); - - return { - fieldName: isNested ? `${parent}.${item.field}` : item.field ?? '', - operator: operator.message, - value, - isNested, - }; -}; - /** * Retrieves the values of tags marked as os * @@ -189,126 +135,27 @@ export const getTagsInclude = ({ return [matches != null, match]; }; -/** - * Formats ExceptionItem information for description list component - * - * @param exceptionItem an ExceptionItem - */ -export const getDescriptionListContent = ( - exceptionItem: ExceptionListItemSchema -): DescriptionListItem[] => { - const details = [ - { - title: i18n.OPERATING_SYSTEM, - value: formatOperatingSystems(getOperatingSystems(exceptionItem._tags ?? [])), - }, - { - title: i18n.DATE_CREATED, - value: moment(exceptionItem.created_at).format('MMMM Do YYYY @ HH:mm:ss'), - }, - { - title: i18n.CREATED_BY, - value: exceptionItem.created_by, - }, - { - title: i18n.COMMENT, - value: exceptionItem.description, - }, - ]; - - return details.reduce((acc, { value, title }) => { - if (value != null && value.trim() !== '') { - return [...acc, { title, description: value }]; - } else { - return acc; - } - }, []); -}; - /** * Formats ExceptionItem.comments into EuiCommentList format * * @param comments ExceptionItem.comments */ export const getFormattedComments = (comments: CommentsArray): EuiCommentProps[] => - comments.map((comment) => ({ - username: comment.created_by, - timestamp: moment(comment.created_at).format('on MMM Do YYYY @ HH:mm:ss'), + comments.map((commentItem) => ({ + username: commentItem.created_by, + timestamp: moment(commentItem.created_at).format('on MMM Do YYYY @ HH:mm:ss'), event: i18n.COMMENT_EVENT, - timelineIcon: , - children: {comment.comment}, + timelineIcon: , + children: {commentItem.comment}, actions: ( ), })); -export const getFormattedBuilderEntries = ( - indexPattern: IIndexPattern, - entries: BuilderEntry[] -): FormattedBuilderEntry[] => { - const { fields } = indexPattern; - return entries.map((item) => { - if (entriesNested.is(item)) { - return { - parent: item.field, - operator: isOperator, - nested: getFormattedBuilderEntries(indexPattern, item.entries), - field: undefined, - value: undefined, - }; - } else { - const [selectedField] = fields.filter( - ({ name }) => item.field != null && item.field === name - ); - return { - field: selectedField, - operator: getExceptionOperatorSelect(item), - value: getEntryValue(item), - }; - } - }); -}; - -export const getValueFromOperator = ( - field: IFieldType | undefined, - selectedOperator: OperatorOption -): Entry => { - const fieldValue = field != null ? field.name : ''; - switch (selectedOperator.type) { - case 'match': - return { - field: fieldValue, - type: OperatorTypeEnum.MATCH, - operator: selectedOperator.operator, - value: '', - }; - case 'match_any': - return { - field: fieldValue, - type: OperatorTypeEnum.MATCH_ANY, - operator: selectedOperator.operator, - value: [], - }; - case 'list': - return { - field: fieldValue, - type: OperatorTypeEnum.LIST, - operator: selectedOperator.operator, - list: { id: '', type: 'ip' }, - }; - default: - return { - field: fieldValue, - type: OperatorTypeEnum.EXISTS, - operator: selectedOperator.operator, - }; - } -}; - export const getNewExceptionItem = ({ listType, listId, @@ -425,11 +272,11 @@ export const prepareExceptionItemsForBulkClose = ( /** * Adds new and existing comments to all new exceptionItems if not present already * @param exceptionItems new or existing ExceptionItem[] - * @param comments new Comments + * @param comments new Comment */ -export const enrichExceptionItemsWithComments = ( +export const enrichNewExceptionItemsWithComments = ( exceptionItems: Array, - comments: Array + comments: Array ): Array => { return exceptionItems.map((item: ExceptionListItemSchema | CreateExceptionListItemSchema) => { return { @@ -439,6 +286,36 @@ export const enrichExceptionItemsWithComments = ( }); }; +/** + * Adds new and existing comments to exceptionItem + * @param exceptionItem existing ExceptionItem + * @param comments array of comments that can include existing + * and new comments + */ +export const enrichExistingExceptionItemWithComments = ( + exceptionItem: ExceptionListItemSchema | CreateExceptionListItemSchema, + comments: Array +): ExceptionListItemSchema | CreateExceptionListItemSchema => { + const formattedComments = comments.map((item) => { + if (comment.is(item)) { + const { id, comment: existingComment } = item; + return { + id, + comment: existingComment, + }; + } else { + return { + comment: item.comment, + }; + } + }); + + return { + ...exceptionItem, + comments: formattedComments, + }; +}; + /** * Adds provided osTypes to all exceptionItems if not present already * @param exceptionItems new or existing ExceptionItem[] @@ -537,6 +414,7 @@ export const defaultEndpointExceptionItems = ( fieldName: 'file.Ext.code_signature.trusted', }); const [sha1Hash] = getMappedNonEcsValue({ data: alertData, fieldName: 'file.hash.sha1' }); + const [eventCode] = getMappedNonEcsValue({ data: alertData, fieldName: 'event.code' }); const namespaceType = 'agnostic'; return [ @@ -544,49 +422,40 @@ export const defaultEndpointExceptionItems = ( ...getNewExceptionItem({ listType, listId, namespaceType, ruleName }), entries: [ { - field: 'file.path', - operator: 'included', - type: 'match', - value: filePath ?? '', - }, - ], - }, - { - ...getNewExceptionItem({ listType, listId, namespaceType, ruleName }), - entries: [ - { - field: 'file.Ext.code_signature.subject_name', - operator: 'included', - type: 'match', - value: signatureSigner ?? '', + field: 'file.Ext.code_signature', + type: 'nested', + entries: [ + { + field: 'subject_name', + operator: 'included', + type: 'match', + value: signatureSigner ?? '', + }, + { + field: 'trusted', + operator: 'included', + type: 'match', + value: signatureTrusted ?? '', + }, + ], }, { - field: 'file.Ext.code_signature.trusted', + field: 'file.path.text', operator: 'included', type: 'match', - value: signatureTrusted ?? '', + value: filePath ?? '', }, - ], - }, - { - ...getNewExceptionItem({ listType, listId, namespaceType, ruleName }), - entries: [ { field: 'file.hash.sha1', operator: 'included', type: 'match', value: sha1Hash ?? '', }, - ], - }, - { - ...getNewExceptionItem({ listType, listId, namespaceType, ruleName }), - entries: [ { - field: 'event.category', + field: 'event.code', operator: 'included', - type: 'match_any', - value: getMappedNonEcsValue({ data: alertData, fieldName: 'event.category' }), + type: 'match', + value: eventCode ?? '', }, ], }, diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts index 870f98f63ee2c..87d2f9dcda935 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts @@ -151,34 +151,6 @@ export const VALUE = i18n.translate('xpack.securitySolution.exceptions.valueDesc defaultMessage: 'Value', }); -export const EXCEPTION_FIELD_PLACEHOLDER = i18n.translate( - 'xpack.securitySolution.exceptions.exceptionFieldPlaceholderDescription', - { - defaultMessage: 'Search', - } -); - -export const EXCEPTION_OPERATOR_PLACEHOLDER = i18n.translate( - 'xpack.securitySolution.exceptions.exceptionOperatorPlaceholderDescription', - { - defaultMessage: 'Operator', - } -); - -export const EXCEPTION_FIELD_VALUE_PLACEHOLDER = i18n.translate( - 'xpack.securitySolution.exceptions.exceptionFieldValuePlaceholderDescription', - { - defaultMessage: 'Search field value...', - } -); - -export const EXCEPTION_FIELD_LISTS_PLACEHOLDER = i18n.translate( - 'xpack.securitySolution.exceptions.exceptionListsPlaceholderDescription', - { - defaultMessage: 'Search for list...', - } -); - export const AND = i18n.translate('xpack.securitySolution.exceptions.andDescription', { defaultMessage: 'AND', }); @@ -187,13 +159,6 @@ export const OR = i18n.translate('xpack.securitySolution.exceptions.orDescriptio defaultMessage: 'OR', }); -export const ADD_NESTED_DESCRIPTION = i18n.translate( - 'xpack.securitySolution.exceptions.addNestedDescription', - { - defaultMessage: 'Add nested condition', - } -); - export const ADD_COMMENT_PLACEHOLDER = i18n.translate( 'xpack.securitySolution.exceptions.viewer.addCommentPlaceholder', { @@ -207,3 +172,7 @@ export const ADD_TO_CLIPBOARD = i18n.translate( defaultMessage: 'Add to clipboard', } ); + +export const DESCRIPTION = i18n.translate('xpack.securitySolution.exceptions.descriptionLabel', { + defaultMessage: 'Description', +}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts index 994aed3952cf0..54caab03e615a 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts @@ -9,6 +9,9 @@ import { OperatorOption } from '../autocomplete/types'; import { EntryNested, Entry, + EntryMatch, + EntryMatchAny, + EntryExists, ExceptionListItemSchema, CreateExceptionListItemSchema, NamespaceType, @@ -52,15 +55,13 @@ export interface ExceptionsPagination { pageSizeOptions: number[]; } -export interface FormattedBuilderEntryBase { +export interface FormattedBuilderEntry { field: IFieldType | undefined; operator: OperatorOption; value: string | string[] | undefined; -} - -export interface FormattedBuilderEntry extends FormattedBuilderEntryBase { - parent?: string; - nested?: FormattedBuilderEntryBase[]; + nested: 'parent' | 'child' | undefined; + entryIndex: number; + parent: { parent: EntryNested; parentIndex: number } | undefined; } export interface EmptyEntry { @@ -77,7 +78,13 @@ export interface EmptyListEntry { list: { id: string | undefined; type: string | undefined }; } -export type BuilderEntry = Entry | EmptyListEntry | EmptyEntry | EntryNested; +export interface EmptyNestedEntry { + field: string | undefined; + type: OperatorTypeEnum.NESTED; + entries: Array; +} + +export type BuilderEntry = Entry | EmptyListEntry | EmptyEntry | EntryNested | EmptyNestedEntry; export type ExceptionListItemBuilderSchema = Omit & { entries: BuilderEntry[]; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx index bf07ff21823eb..cb1a80abedb27 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx @@ -144,7 +144,7 @@ describe('useAddOrUpdateException', () => { await act(async () => { const { result, waitForNextUpdate } = render(); await waitForNextUpdate(); - expect(result.current).toEqual([{ isLoading: false }, null]); + expect(result.current).toEqual([{ isLoading: false }, result.current[1]]); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.tsx index 55c3ea35716d5..9d45a411b5130 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState, useCallback } from 'react'; import { HttpStart } from '../../../../../../../src/core/public'; import { @@ -60,7 +60,19 @@ export const useAddOrUpdateException = ({ onSuccess, }: UseAddOrUpdateExceptionProps): ReturnUseAddOrUpdateException => { const [isLoading, setIsLoading] = useState(false); - const addOrUpdateException = useRef(null); + const addOrUpdateExceptionRef = useRef(null); + const addOrUpdateException = useCallback( + async (exceptionItemsToAddOrUpdate, alertIdToClose, bulkCloseIndex) => { + if (addOrUpdateExceptionRef.current !== null) { + addOrUpdateExceptionRef.current( + exceptionItemsToAddOrUpdate, + alertIdToClose, + bulkCloseIndex + ); + } + }, + [] + ); useEffect(() => { let isSubscribed = true; @@ -114,6 +126,7 @@ export const useAddOrUpdateException = ({ await updateAlertStatus({ query: getUpdateAlertsQuery([alertIdToClose]), status: 'closed', + signal: abortCtrl.signal, }); } @@ -131,6 +144,7 @@ export const useAddOrUpdateException = ({ query: filter, }, status: 'closed', + signal: abortCtrl.signal, }); } @@ -148,12 +162,12 @@ export const useAddOrUpdateException = ({ } }; - addOrUpdateException.current = addOrUpdateExceptionItems; + addOrUpdateExceptionRef.current = addOrUpdateExceptionItems; return (): void => { isSubscribed = false; abortCtrl.abort(); }; }, [http, onSuccess, onError]); - return [{ isLoading }, addOrUpdateException.current]; + return [{ isLoading }, addOrUpdateException]; }; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.test.tsx index 7bef771d367f3..6dbf5922e0a97 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.test.tsx @@ -38,6 +38,7 @@ describe('useFetchOrCreateRuleExceptionList', () => { ReturnUseFetchOrCreateRuleExceptionList >; const onError = jest.fn(); + const onSuccess = jest.fn(); const error = new Error('Something went wrong'); const ruleId = 'myRuleId'; const abortCtrl = new AbortController(); @@ -94,6 +95,7 @@ describe('useFetchOrCreateRuleExceptionList', () => { ruleId, exceptionListType: listType, onError, + onSuccess, }) ); }); @@ -168,6 +170,15 @@ describe('useFetchOrCreateRuleExceptionList', () => { expect(patchRule).toHaveBeenCalledTimes(1); }); }); + it('invokes onSuccess indicating that the rule changed', async () => { + await act(async () => { + const { waitForNextUpdate } = render(); + await waitForNextUpdate(); + await waitForNextUpdate(); + await waitForNextUpdate(); + expect(onSuccess).toHaveBeenCalledWith(true); + }); + }); }); describe("when the rule has exception list references and 'detection' is passed in", () => { @@ -207,6 +218,15 @@ describe('useFetchOrCreateRuleExceptionList', () => { expect(result.current[1]).toEqual(detectionExceptionList); }); }); + it('invokes onSuccess indicating that the rule did not change', async () => { + await act(async () => { + const { waitForNextUpdate } = render(); + await waitForNextUpdate(); + await waitForNextUpdate(); + await waitForNextUpdate(); + expect(onSuccess).toHaveBeenCalledWith(false); + }); + }); describe("but the rule does not have a reference to 'detection' type exception list", () => { beforeEach(() => { @@ -362,5 +382,14 @@ describe('useFetchOrCreateRuleExceptionList', () => { expect(onError).toHaveBeenCalledWith(error); }); }); + + it('does not call onSuccess', async () => { + await act(async () => { + const { waitForNextUpdate } = render(); + await waitForNextUpdate(); + await waitForNextUpdate(); + expect(onSuccess).not.toHaveBeenCalled(); + }); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.tsx index b238e25f6de59..0d367e03a799f 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.tsx @@ -31,6 +31,7 @@ export interface UseFetchOrCreateRuleExceptionListProps { ruleId: Rule['id']; exceptionListType: ExceptionListSchema['type']; onError: (arg: Error) => void; + onSuccess?: (ruleWasChanged: boolean) => void; } /** @@ -47,6 +48,7 @@ export const useFetchOrCreateRuleExceptionList = ({ ruleId, exceptionListType, onError, + onSuccess, }: UseFetchOrCreateRuleExceptionListProps): ReturnUseFetchOrCreateRuleExceptionList => { const [isLoading, setIsLoading] = useState(false); const [exceptionList, setExceptionList] = useState(null); @@ -100,6 +102,7 @@ export const useFetchOrCreateRuleExceptionList = ({ const newExceptionListReference = { id: newExceptionList.id, + list_id: newExceptionList.list_id, type: newExceptionList.type, namespace_type: newExceptionList.namespace_type, }; @@ -168,6 +171,9 @@ export const useFetchOrCreateRuleExceptionList = ({ if (isSubscribed) { setExceptionList(exceptionListToUse); setIsLoading(false); + if (onSuccess) { + onSuccess(matchingList == null); + } } } catch (error) { if (isSubscribed) { @@ -183,7 +189,7 @@ export const useFetchOrCreateRuleExceptionList = ({ isSubscribed = false; abortCtrl.abort(); }; - }, [http, ruleId, exceptionListType, onError]); + }, [http, ruleId, exceptionListType, onError, onSuccess]); return [isLoading, exceptionList]; }; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx index 4fc744c2c9d01..ab6588b67d5ba 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx @@ -12,7 +12,7 @@ import moment from 'moment-timezone'; import { ExceptionDetails } from './exception_details'; import { getExceptionListItemSchemaMock } from '../../../../../../../lists/common/schemas/response/exception_list_item_schema.mock'; -import { getCommentsArrayMock } from '../../../../../../../lists/common/schemas/types/comments.mock'; +import { getCommentsArrayMock } from '../../../../../../../lists/common/schemas/types/comment.mock'; describe('ExceptionDetails', () => { beforeEach(() => { @@ -211,7 +211,7 @@ describe('ExceptionDetails', () => {
); - expect(wrapper.find('EuiDescriptionListTitle').at(3).text()).toEqual('Comment'); + expect(wrapper.find('EuiDescriptionListTitle').at(3).text()).toEqual('Description'); expect(wrapper.find('EuiDescriptionListDescription').at(3).text()).toEqual('some description'); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx index 44632236ea7a0..cca7d76899a19 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx @@ -16,7 +16,7 @@ import React, { useMemo, Fragment } from 'react'; import styled, { css } from 'styled-components'; import { DescriptionListItem } from '../../types'; -import { getDescriptionListContent } from '../../helpers'; +import { getDescriptionListContent } from '../helpers'; import * as i18n from '../../translations'; import { ExceptionListItemSchema } from '../../../../../../public/lists_plugin_deps'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.stories.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.stories.tsx index 56b029aaee81e..fec7354855935 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.stories.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.stories.tsx @@ -11,7 +11,7 @@ import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; import { ExceptionItem } from './'; import { getExceptionListItemSchemaMock } from '../../../../../../../lists/common/schemas/response/exception_list_item_schema.mock'; -import { getCommentsArrayMock } from '../../../../../../../lists/common/schemas/types/comments.mock'; +import { getCommentsArrayMock } from '../../../../../../../lists/common/schemas/types/comment.mock'; addDecorator((storyFn) => ( ({ eui: euiLightVars, darkMode: false })}>{storyFn()} diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx index 90752f9450e4c..c9def092fda47 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx @@ -11,7 +11,7 @@ import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; import { ExceptionItem } from './'; import { getExceptionListItemSchemaMock } from '../../../../../../../lists/common/schemas/response/exception_list_item_schema.mock'; -import { getCommentsArrayMock } from '../../../../../../../lists/common/schemas/types/comments.mock'; +import { getCommentsArrayMock } from '../../../../../../../lists/common/schemas/types/comment.mock'; jest.mock('../../../../lib/kibana'); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.tsx index 3b85c6741a480..13a90091ba4c8 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.tsx @@ -17,7 +17,8 @@ import styled from 'styled-components'; import { ExceptionDetails } from './exception_details'; import { ExceptionEntries } from './exception_entries'; -import { getFormattedEntries, getFormattedComments } from '../../helpers'; +import { getFormattedComments } from '../../helpers'; +import { getFormattedEntries } from '../helpers'; import { FormattedEntry, ExceptionListItemIdentifiers } from '../../types'; import { ExceptionListItemSchema } from '../../../../../../public/lists_plugin_deps'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/helpers.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/helpers.test.tsx new file mode 100644 index 0000000000000..5d4340db9a448 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/helpers.test.tsx @@ -0,0 +1,218 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import moment from 'moment-timezone'; + +import { getFormattedEntries, formatEntry, getDescriptionListContent } from './helpers'; +import { FormattedEntry, DescriptionListItem } from '../types'; +import { getExceptionListItemSchemaMock } from '../../../../../../lists/common/schemas/response/exception_list_item_schema.mock'; +import { getEntriesArrayMock } from '../../../../../../lists/common/schemas/types/entries.mock'; +import { getEntryMatchMock } from '../../../../../../lists/common/schemas/types/entry_match.mock'; +import { getEntryMatchAnyMock } from '../../../../../../lists/common/schemas/types/entry_match_any.mock'; +import { getEntryExistsMock } from '../../../../../../lists/common/schemas/types/entry_exists.mock'; + +describe('Exception viewer helpers', () => { + beforeEach(() => { + moment.tz.setDefault('UTC'); + }); + + afterEach(() => { + moment.tz.setDefault('Browser'); + }); + + describe('#getFormattedEntries', () => { + test('it returns empty array if no entries passed', () => { + const result = getFormattedEntries([]); + + expect(result).toEqual([]); + }); + + test('it formats nested entries as expected', () => { + const payload = [getEntryMatchMock()]; + const result = getFormattedEntries(payload); + const expected: FormattedEntry[] = [ + { + fieldName: 'host.name', + isNested: false, + operator: 'is', + value: 'some host name', + }, + ]; + expect(result).toEqual(expected); + }); + + test('it formats "exists" entries as expected', () => { + const payload = [getEntryExistsMock()]; + const result = getFormattedEntries(payload); + const expected: FormattedEntry[] = [ + { + fieldName: 'host.name', + isNested: false, + operator: 'exists', + value: undefined, + }, + ]; + expect(result).toEqual(expected); + }); + + test('it formats non-nested entries as expected', () => { + const payload = [getEntryMatchAnyMock(), getEntryMatchMock()]; + const result = getFormattedEntries(payload); + const expected: FormattedEntry[] = [ + { + fieldName: 'host.name', + isNested: false, + operator: 'is one of', + value: ['some host name'], + }, + { + fieldName: 'host.name', + isNested: false, + operator: 'is', + value: 'some host name', + }, + ]; + expect(result).toEqual(expected); + }); + + test('it formats a mix of nested and non-nested entries as expected', () => { + const payload = getEntriesArrayMock(); + const result = getFormattedEntries(payload); + const expected: FormattedEntry[] = [ + { + fieldName: 'host.name', + isNested: false, + operator: 'is', + value: 'some host name', + }, + { + fieldName: 'host.name', + isNested: false, + operator: 'is one of', + value: ['some host name'], + }, + { + fieldName: 'host.name', + isNested: false, + operator: 'exists', + value: undefined, + }, + { + fieldName: 'host.name', + isNested: false, + operator: undefined, + value: undefined, + }, + { + fieldName: 'host.name.host.name', + isNested: true, + operator: 'is', + value: 'some host name', + }, + { + fieldName: 'host.name.host.name', + isNested: true, + operator: 'is one of', + value: ['some host name'], + }, + ]; + expect(result).toEqual(expected); + }); + }); + + describe('#formatEntry', () => { + test('it formats an entry', () => { + const payload = getEntryMatchMock(); + const formattedEntry = formatEntry({ isNested: false, item: payload }); + const expected: FormattedEntry = { + fieldName: 'host.name', + isNested: false, + operator: 'is', + value: 'some host name', + }; + + expect(formattedEntry).toEqual(expected); + }); + + test('it formats as expected when "isNested" is "true"', () => { + const payload = getEntryMatchMock(); + const formattedEntry = formatEntry({ isNested: true, parent: 'parent', item: payload }); + const expected: FormattedEntry = { + fieldName: 'parent.host.name', + isNested: true, + operator: 'is', + value: 'some host name', + }; + + expect(formattedEntry).toEqual(expected); + }); + }); + + describe('#getDescriptionListContent', () => { + test('it returns formatted description list with os if one is specified', () => { + const payload = getExceptionListItemSchemaMock(); + payload.description = ''; + const result = getDescriptionListContent(payload); + const expected: DescriptionListItem[] = [ + { + description: 'Linux', + title: 'OS', + }, + { + description: 'April 20th 2020 @ 15:25:31', + title: 'Date created', + }, + { + description: 'some user', + title: 'Created by', + }, + ]; + + expect(result).toEqual(expected); + }); + + test('it returns formatted description list with a description if one specified', () => { + const payload = getExceptionListItemSchemaMock(); + payload._tags = []; + payload.description = 'Im a description'; + const result = getDescriptionListContent(payload); + const expected: DescriptionListItem[] = [ + { + description: 'April 20th 2020 @ 15:25:31', + title: 'Date created', + }, + { + description: 'some user', + title: 'Created by', + }, + { + description: 'Im a description', + title: 'Description', + }, + ]; + + expect(result).toEqual(expected); + }); + + test('it returns just user and date created if no other fields specified', () => { + const payload = getExceptionListItemSchemaMock(); + payload._tags = []; + payload.description = ''; + const result = getDescriptionListContent(payload); + const expected: DescriptionListItem[] = [ + { + description: 'April 20th 2020 @ 15:25:31', + title: 'Date created', + }, + { + description: 'some user', + title: 'Created by', + }, + ]; + + expect(result).toEqual(expected); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/helpers.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/helpers.tsx new file mode 100644 index 0000000000000..345db5bf1e75e --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/helpers.tsx @@ -0,0 +1,109 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import moment from 'moment'; + +import { entriesNested, ExceptionListItemSchema } from '../../../../lists_plugin_deps'; +import { + getEntryValue, + getExceptionOperatorSelect, + formatOperatingSystems, + getOperatingSystems, +} from '../helpers'; +import { FormattedEntry, BuilderEntry, DescriptionListItem } from '../types'; +import * as i18n from '../translations'; + +/** + * Helper method for `getFormattedEntries` + */ +export const formatEntry = ({ + isNested, + parent, + item, +}: { + isNested: boolean; + parent?: string; + item: BuilderEntry; +}): FormattedEntry => { + const operator = getExceptionOperatorSelect(item); + const value = getEntryValue(item); + + return { + fieldName: isNested ? `${parent}.${item.field}` : item.field ?? '', + operator: operator.message, + value, + isNested, + }; +}; + +/** + * Formats ExceptionItem entries into simple field, operator, value + * for use in rendering items in table + * + * @param entries an ExceptionItem's entries + */ +export const getFormattedEntries = (entries: BuilderEntry[]): FormattedEntry[] => { + const formattedEntries = entries.map((item) => { + if (entriesNested.is(item)) { + const parent = { + fieldName: item.field, + operator: undefined, + value: undefined, + isNested: false, + }; + return item.entries.reduce( + (acc, nestedEntry) => { + const formattedEntry = formatEntry({ + isNested: true, + parent: item.field, + item: nestedEntry, + }); + return [...acc, { ...formattedEntry }]; + }, + [parent] + ); + } else { + return formatEntry({ isNested: false, item }); + } + }); + + return formattedEntries.flat(); +}; + +/** + * Formats ExceptionItem details for description list component + * + * @param exceptionItem an ExceptionItem + */ +export const getDescriptionListContent = ( + exceptionItem: ExceptionListItemSchema +): DescriptionListItem[] => { + const details = [ + { + title: i18n.OPERATING_SYSTEM, + value: formatOperatingSystems(getOperatingSystems(exceptionItem._tags ?? [])), + }, + { + title: i18n.DATE_CREATED, + value: moment(exceptionItem.created_at).format('MMMM Do YYYY @ HH:mm:ss'), + }, + { + title: i18n.CREATED_BY, + value: exceptionItem.created_by, + }, + { + title: i18n.DESCRIPTION, + value: exceptionItem.description, + }, + ]; + + return details.reduce((acc, { value, title }) => { + if (value != null && value.trim() !== '') { + return [...acc, { title, description: value }]; + } else { + return acc; + } + }, []); +}; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx index 986f27f6495ec..84613d1c73536 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx @@ -72,6 +72,7 @@ describe('ExceptionsViewer', () => { exceptionListsMeta={[ { id: '5b543420', + listId: 'list_id', type: 'endpoint', namespaceType: 'single', }, @@ -124,6 +125,7 @@ describe('ExceptionsViewer', () => { exceptionListsMeta={[ { id: '5b543420', + listId: 'list_id', type: 'endpoint', namespaceType: 'single', }, diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx index 9cc73d4491146..7f4d825276406 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx @@ -57,6 +57,7 @@ interface ExceptionsViewerProps { exceptionListsMeta: ExceptionIdentifiers[]; availableListTypes: ExceptionListTypeEnum[]; commentsAccordionId: string; + onRuleChange?: () => void; } const ExceptionsViewerComponent = ({ @@ -66,6 +67,7 @@ const ExceptionsViewerComponent = ({ exceptionListsMeta, availableListTypes, commentsAccordionId, + onRuleChange, }: ExceptionsViewerProps): JSX.Element => { const { services } = useKibana(); const [, dispatchToaster] = useStateToaster(); @@ -174,8 +176,6 @@ const ExceptionsViewerComponent = ({ const handleEditException = useCallback( (exception: ExceptionListItemSchema): void => { - // TODO: Added this just for testing. Update - // modal state logic as needed once ready dispatch({ type: 'updateExceptionToEdit', exception, @@ -188,7 +188,8 @@ const ExceptionsViewerComponent = ({ const handleOnCancelExceptionModal = useCallback((): void => { setCurrentModal(null); - }, [setCurrentModal]); + handleFetchList(); + }, [setCurrentModal, handleFetchList]); const handleOnConfirmExceptionModal = useCallback((): void => { setCurrentModal(null); @@ -275,6 +276,7 @@ const ExceptionsViewerComponent = ({ exceptionListType={exceptionListTypeToEdit} onCancel={handleOnCancelExceptionModal} onConfirm={handleOnConfirmExceptionModal} + onRuleChange={onRuleChange} /> )} diff --git a/x-pack/plugins/security_solution/public/common/components/filters_global/filters_global.test.tsx b/x-pack/plugins/security_solution/public/common/components/filters_global/filters_global.test.tsx index ffac0496e9f1a..9fda60b1f289d 100644 --- a/x-pack/plugins/security_solution/public/common/components/filters_global/filters_global.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/filters_global/filters_global.test.tsx @@ -4,20 +4,120 @@ * you may not use this file except in compliance with the Elastic License. */ -import { shallow } from 'enzyme'; +import { mount, ReactWrapper, shallow } from 'enzyme'; import React from 'react'; +import { StickyContainer } from 'react-sticky'; import '../../mock/match_media'; import { FiltersGlobal } from './filters_global'; +import { TestProviders } from '../../mock/test_providers'; describe('rendering', () => { test('renders correctly', () => { const wrapper = shallow( - +

{'Additional filters here.'}

); expect(wrapper).toMatchSnapshot(); }); + + describe('full screen mode', () => { + let wrapper: ReactWrapper; + + beforeEach(() => { + wrapper = mount( + + + +

{'Filter content'}

+
+
+
+ ); + }); + + test('it does NOT render the sticky container', () => { + expect(wrapper.find('[data-test-subj="sticky-filters-global-container"]').exists()).toBe( + false + ); + }); + + test('it renders the non-sticky container', () => { + expect(wrapper.find('[data-test-subj="non-sticky-global-container"]').exists()).toBe(true); + }); + + test('it does NOT render the container with a `display: none` style when `show` is true (the default)', () => { + expect( + wrapper.find('[data-test-subj="non-sticky-global-container"]').first() + ).not.toHaveStyleRule('display', 'none'); + }); + }); + + describe('non-full screen mode', () => { + let wrapper: ReactWrapper; + + beforeEach(() => { + wrapper = mount( + + + +

{'Filter content'}

+
+
+
+ ); + }); + + test('it renders the sticky container', () => { + expect(wrapper.find('[data-test-subj="sticky-filters-global-container"]').exists()).toBe( + true + ); + }); + + test('it does NOT render the non-sticky container', () => { + expect(wrapper.find('[data-test-subj="non-sticky-global-container"]').exists()).toBe(false); + }); + + test('it does NOT render the container with a `display: none` style when `show` is true (the default)', () => { + expect( + wrapper.find('[data-test-subj="sticky-filters-global-container"]').first() + ).not.toHaveStyleRule('display', 'none'); + }); + }); + + describe('when show is false', () => { + test('in full screen mode it renders the container with a `display: none` style', () => { + const wrapper = mount( + + + +

{'Filter content'}

+
+
+
+ ); + + expect( + wrapper.find('[data-test-subj="non-sticky-global-container"]').first() + ).toHaveStyleRule('display', 'none'); + }); + + test('in non-full screen mode it renders the container with a `display: none` style', () => { + const wrapper = mount( + + + +

{'Filter content'}

+
+
+
+ ); + + expect( + wrapper.find('[data-test-subj="sticky-filters-global-container"]').first() + ).toHaveStyleRule('display', 'none'); + }); + }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/filters_global/filters_global.tsx b/x-pack/plugins/security_solution/public/common/components/filters_global/filters_global.tsx index b52438486406e..80e7209492fa5 100644 --- a/x-pack/plugins/security_solution/public/common/components/filters_global/filters_global.tsx +++ b/x-pack/plugins/security_solution/public/common/components/filters_global/filters_global.tsx @@ -47,20 +47,33 @@ const FiltersGlobalContainer = styled.header<{ show: boolean }>` FiltersGlobalContainer.displayName = 'FiltersGlobalContainer'; +const NO_STYLE: React.CSSProperties = {}; + export interface FiltersGlobalProps { children: React.ReactNode; + globalFullScreen: boolean; show?: boolean; } -export const FiltersGlobal = React.memo(({ children, show = true }) => ( - - {({ style, isSticky }) => ( - - +export const FiltersGlobal = React.memo( + ({ children, globalFullScreen, show = true }) => + globalFullScreen ? ( + + {children} - )} - -)); + ) : ( + + {({ style, isSticky }) => ( + + + {children} + + + )} + + ) +); + FiltersGlobal.displayName = 'FiltersGlobal'; diff --git a/x-pack/plugins/security_solution/public/common/components/help_menu/index.tsx b/x-pack/plugins/security_solution/public/common/components/help_menu/index.tsx index f4477740f7b58..1eaa16fd058a5 100644 --- a/x-pack/plugins/security_solution/public/common/components/help_menu/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/help_menu/index.tsx @@ -39,7 +39,7 @@ export const HelpMenu = React.memo(() => { }, { linkType: 'discuss', - href: 'https://discuss.elastic.co/c/siem', + href: 'https://discuss.elastic.co/c/security', target: '_blank', rel: 'noopener', }, diff --git a/x-pack/plugins/security_solution/public/common/components/markdown_editor/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/markdown_editor/index.test.tsx new file mode 100644 index 0000000000000..b5e5b01189418 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/markdown_editor/index.test.tsx @@ -0,0 +1,49 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { mount } from 'enzyme'; +import React from 'react'; + +import { MarkdownEditor } from '.'; +import { TestProviders } from '../../mock'; + +describe('Markdown Editor', () => { + const onChange = jest.fn(); + const onCursorPositionUpdate = jest.fn(); + const defaultProps = { + content: 'hello world', + onChange, + onCursorPositionUpdate, + }; + beforeEach(() => { + jest.clearAllMocks(); + }); + test('it calls onChange with correct value', () => { + const wrapper = mount( + + + + ); + const newValue = 'a new string'; + wrapper + .find(`[data-test-subj="textAreaInput"]`) + .first() + .simulate('change', { target: { value: newValue } }); + expect(onChange).toBeCalledWith(newValue); + }); + test('it calls onCursorPositionUpdate with correct args', () => { + const wrapper = mount( + + + + ); + wrapper.find(`[data-test-subj="textAreaInput"]`).first().simulate('blur'); + expect(onCursorPositionUpdate).toBeCalledWith({ + start: 0, + end: 0, + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/markdown_editor/index.tsx b/x-pack/plugins/security_solution/public/common/components/markdown_editor/index.tsx index c40b3910ec152..d4ad4a11b60a3 100644 --- a/x-pack/plugins/security_solution/public/common/components/markdown_editor/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/markdown_editor/index.tsx @@ -103,7 +103,6 @@ export const MarkdownEditor = React.memo<{ end: e!.target!.selectionEnd ?? 0, }); } - return false; }, [onCursorPositionUpdate] ); diff --git a/x-pack/plugins/security_solution/public/common/components/ml_popover/api.tsx b/x-pack/plugins/security_solution/public/common/components/ml_popover/api.tsx index b4da4fa79e035..7c72098209a06 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml_popover/api.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml_popover/api.tsx @@ -71,7 +71,7 @@ export const setupMlJob = async ({ configTemplate, indexPatternName = 'auditbeat-*', jobIdErrorFilter = [], - groups = ['siem'], + groups = ['security'], prefix = '', }: MlSetupArgs): Promise => { const response = await KibanaServices.get().http.fetch( diff --git a/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/translations.ts b/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/translations.ts index 2b37c437866e0..7b29bab2e38f3 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/translations.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/translations.ts @@ -9,6 +9,6 @@ import { i18n } from '@kbn/i18n'; export const SIEM_JOB_FETCH_FAILURE = i18n.translate( 'xpack.securitySolution.components.mlPopup.hooks.errors.siemJobFetchFailureTitle', { - defaultMessage: 'SIEM job fetch failure', + defaultMessage: 'Security job fetch failure', } ); diff --git a/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_siem_jobs_helpers.tsx b/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_siem_jobs_helpers.tsx index 658d2659282ce..adbd712ffeb3e 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_siem_jobs_helpers.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_siem_jobs_helpers.tsx @@ -104,7 +104,7 @@ export const getInstalledJobs = ( compatibleModuleIds: string[] ): SiemJob[] => jobSummaryData - .filter(({ groups }) => groups.includes('siem')) + .filter(({ groups }) => groups.includes('siem') || groups.includes('security')) .map((jobSummary) => ({ ...jobSummary, ...getAugmentedFields(jobSummary.id, moduleJobs, compatibleModuleIds), diff --git a/x-pack/plugins/security_solution/public/common/components/ml_popover/jobs_table/filters/groups_filter_popover.tsx b/x-pack/plugins/security_solution/public/common/components/ml_popover/jobs_table/filters/groups_filter_popover.tsx index 1aa3ad630306e..d879942b8b101 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml_popover/jobs_table/filters/groups_filter_popover.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml_popover/jobs_table/filters/groups_filter_popover.tsx @@ -25,8 +25,8 @@ interface GroupsFilterPopoverProps { /** * Popover for selecting which SiemJob groups to filter on. Component extracts unique groups and - * their counts from the provided SiemJobs. The 'siem' group is filtered out as all jobs will be - * siem jobs + * their counts from the provided SiemJobs. The 'siem' & 'security' groups are filtered out as all jobs will be + * siem/security jobs * * @param siemJobs jobs to fetch groups from to display for filtering * @param onSelectedGroupsChanged change listener to be notified when group selection changes @@ -41,7 +41,7 @@ export const GroupsFilterPopoverComponent = ({ const groups = siemJobs .map((j) => j.groups) .flat() - .filter((g) => g !== 'siem'); + .filter((g) => g !== 'siem' && g !== 'security'); const uniqueGroups = Array.from(new Set(groups)); useEffect(() => { diff --git a/x-pack/plugins/security_solution/public/common/components/ml_popover/ml_modules.tsx b/x-pack/plugins/security_solution/public/common/components/ml_popover/ml_modules.tsx index b956cf2c1494c..4dccba08590a4 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml_popover/ml_modules.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml_popover/ml_modules.tsx @@ -12,6 +12,7 @@ export const mlModules: string[] = [ 'siem_auditbeat', 'siem_auditbeat_auth', + 'siem_cloudtrail', 'siem_packetbeat', 'siem_winlogbeat', 'siem_winlogbeat_auth', diff --git a/x-pack/plugins/security_solution/public/common/components/navigation/breadcrumbs/index.test.ts b/x-pack/plugins/security_solution/public/common/components/navigation/breadcrumbs/index.test.ts index 7e508c28c62df..89aa77106933e 100644 --- a/x-pack/plugins/security_solution/public/common/components/navigation/breadcrumbs/index.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/navigation/breadcrumbs/index.test.ts @@ -36,6 +36,13 @@ const getMockObject = ( ): RouteSpyState & TabNavigationProps => ({ detailName, navTabs: { + case: { + disabled: false, + href: '/app/security/cases', + id: 'case', + name: 'Cases', + urlKey: 'case', + }, hosts: { disabled: false, href: '/app/security/hosts', @@ -227,6 +234,73 @@ describe('Navigation Breadcrumbs', () => { { text: 'Flows', href: '' }, ]); }); + + test('should return Alerts breadcrumbs when supplied detection pathname', () => { + const breadcrumbs = getBreadcrumbsForRoute( + getMockObject('detections', '/', undefined), + getUrlForAppMock + ); + expect(breadcrumbs).toEqual([ + { text: 'Security', href: '/app/security/overview' }, + { + text: 'Detections', + href: + "securitySolution:detections?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", + }, + ]); + }); + test('should return Cases breadcrumbs when supplied case pathname', () => { + const breadcrumbs = getBreadcrumbsForRoute( + getMockObject('case', '/', undefined), + getUrlForAppMock + ); + expect(breadcrumbs).toEqual([ + { text: 'Security', href: '/app/security/overview' }, + { + text: 'Cases', + href: + "securitySolution:case?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", + }, + ]); + }); + test('should return Case details breadcrumbs when supplied case details pathname', () => { + const sampleCase = { + id: 'my-case-id', + name: 'Case name', + }; + const breadcrumbs = getBreadcrumbsForRoute( + { + ...getMockObject('case', `/${sampleCase.id}`, sampleCase.id), + state: { caseTitle: sampleCase.name }, + }, + getUrlForAppMock + ); + expect(breadcrumbs).toEqual([ + { text: 'Security', href: '/app/security/overview' }, + { + text: 'Cases', + href: + "securitySolution:case?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", + }, + { + text: sampleCase.name, + href: `securitySolution:case/${sampleCase.id}?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))`, + }, + ]); + }); + test('should return Admin breadcrumbs when supplied admin pathname', () => { + const breadcrumbs = getBreadcrumbsForRoute( + getMockObject('administration', '/', undefined), + getUrlForAppMock + ); + expect(breadcrumbs).toEqual([ + { text: 'Security', href: '/app/security/overview' }, + { + text: 'Administration', + href: 'securitySolution:administration', + }, + ]); + }); }); describe('setBreadcrumbs()', () => { diff --git a/x-pack/plugins/security_solution/public/common/components/news_feed/helpers.test.ts b/x-pack/plugins/security_solution/public/common/components/news_feed/helpers.test.ts index cdd04b50a6d50..35a59f4d18e8b 100644 --- a/x-pack/plugins/security_solution/public/common/components/news_feed/helpers.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/news_feed/helpers.test.ts @@ -144,7 +144,7 @@ describe('helpers', () => { hash: '5a35c984a9cdc1c6a25913f3d0b99b1aefc7257bc3b936c39db9fa0435edeed0', imageUrl: 'https://aws1.discourse-cdn.com/elastic/original/3X/f/8/f8c3d0b9971cfcd0be349d973aa5799f71d280cc.png?blade=securitysolutionfeed', - linkUrl: 'https://discuss.elastic.co/c/siem?blade=securitysolutionfeed', + linkUrl: 'https://discuss.elastic.co/c/security?blade=securitysolutionfeed', publishOn: expect.any(Date), title: 'Got SIEM Questions?', }, @@ -284,7 +284,7 @@ describe('helpers', () => { }, link_text: null, link_url: { - en: 'https://discuss.elastic.co/c/siem?blade=securitysolutionfeed', + en: 'https://discuss.elastic.co/c/security?blade=securitysolutionfeed', ja: translatedLinkUrl, }, languages: null, diff --git a/x-pack/plugins/security_solution/public/common/components/page/index.tsx b/x-pack/plugins/security_solution/public/common/components/page/index.tsx index 9a5654ed6475f..8bf0690bfd0ad 100644 --- a/x-pack/plugins/security_solution/public/common/components/page/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/page/index.tsx @@ -7,7 +7,10 @@ import { EuiBadge, EuiDescriptionList, EuiFlexGroup, EuiIcon, EuiPage } from '@elastic/eui'; import styled, { createGlobalStyle } from 'styled-components'; -import { FULL_SCREEN_TOGGLED_CLASS_NAME } from '../../../../common/constants'; +import { + FULL_SCREEN_TOGGLED_CLASS_NAME, + SCROLLING_DISABLED_CLASS_NAME, +} from '../../../../common/constants'; /* SIDE EFFECT: the following `createGlobalStyle` overrides default styling in angular code that was not theme-friendly @@ -49,8 +52,8 @@ export const AppGlobalStyle = createGlobalStyle<{ theme: { eui: { euiColorPrimar border: none; } - /* hide open popovers when a modal is being displayed to prevent them from covering the modal */ - body.euiBody-hasOverlayMask .euiPopover__panel-isOpen { + /* hide open draggable popovers when a modal is being displayed to prevent them from covering the modal */ + body.euiBody-hasOverlayMask .withHoverActions__popover.euiPopover__panel-isOpen{ visibility: hidden !important; } @@ -63,6 +66,14 @@ export const AppGlobalStyle = createGlobalStyle<{ theme: { eui: { euiColorPrimar .${FULL_SCREEN_TOGGLED_CLASS_NAME} { ${({ theme }) => `background-color: ${theme.eui.euiColorPrimary} !important`}; } + + .${SCROLLING_DISABLED_CLASS_NAME} body { + overflow-y: hidden; + } + + .${SCROLLING_DISABLED_CLASS_NAME} #kibana-body { + overflow-y: hidden; + } `; export const DescriptionListStyled = styled(EuiDescriptionList)` diff --git a/x-pack/plugins/security_solution/public/common/components/with_hover_actions/index.tsx b/x-pack/plugins/security_solution/public/common/components/with_hover_actions/index.tsx index e6577bd040e25..b4abdd4b91805 100644 --- a/x-pack/plugins/security_solution/public/common/components/with_hover_actions/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/with_hover_actions/index.tsx @@ -10,6 +10,11 @@ import styled from 'styled-components'; import { IS_DRAGGING_CLASS_NAME } from '../drag_and_drop/helpers'; +/** + * To avoid expensive changes to the DOM, delay showing the popover menu + */ +const HOVER_INTENT_DELAY = 100; // ms + // eslint-disable-next-line @typescript-eslint/no-explicit-any const WithHoverActionsPopover = (styled(EuiPopover as any)` .euiPopover__anchor { @@ -51,18 +56,27 @@ export const WithHoverActions = React.memo( ({ alwaysShow = false, closePopOverTrigger, hoverContent, render }) => { const [isOpen, setIsOpen] = useState(hoverContent != null && alwaysShow); const [showHoverContent, setShowHoverContent] = useState(false); + const [hoverTimeout, setHoverTimeout] = useState(undefined); + const onMouseEnter = useCallback(() => { - // NOTE: the following read from the DOM is expensive, but not as - // expensive as the default behavior, which adds a div to the body, - // which-in turn performs a more expensive change to the layout - if (!document.body.classList.contains(IS_DRAGGING_CLASS_NAME)) { - setShowHoverContent(true); - } - }, []); + setHoverTimeout( + Number( + setTimeout(() => { + // NOTE: the following read from the DOM is expensive, but not as + // expensive as the default behavior, which adds a div to the body, + // which-in turn performs a more expensive change to the layout + if (!document.body.classList.contains(IS_DRAGGING_CLASS_NAME)) { + setShowHoverContent(true); + } + }, HOVER_INTENT_DELAY) + ) + ); + }, [setHoverTimeout, setShowHoverContent]); const onMouseLeave = useCallback(() => { + clearTimeout(hoverTimeout); setShowHoverContent(false); - }, []); + }, [hoverTimeout, setShowHoverContent]); const content = useMemo( () => ( @@ -90,6 +104,7 @@ export const WithHoverActions = React.memo( hasArrow={false} isOpen={isOpen} panelPaddingSize={!alwaysShow ? 's' : 'none'} + panelClassName="withHoverActions__popover" > {isOpen ? <>{hoverContent} : null} diff --git a/x-pack/plugins/security_solution/public/common/containers/source/index.tsx b/x-pack/plugins/security_solution/public/common/containers/source/index.tsx index 54d49d7279d68..ffbecf9e3d433 100644 --- a/x-pack/plugins/security_solution/public/common/containers/source/index.tsx +++ b/x-pack/plugins/security_solution/public/common/containers/source/index.tsx @@ -122,7 +122,12 @@ interface UseWithSourceState { export const useWithSource = ( sourceId = 'default', indexToAdd?: string[] | null, - onlyCheckIndexToAdd?: boolean + onlyCheckIndexToAdd?: boolean, + // Fun fact: When using this hook multiple times within a component (e.g. add_exception_modal & edit_exception_modal), + // the apolloClient will perform queryDeduplication and prevent the first query from executing. A deep compare is not + // performed on `indices`, so another field must be passed to circumvent this. + // For details, see https://github.com/apollographql/react-apollo/issues/2202 + queryDeduplication = 'default' ) => { const [configIndex] = useUiSetting$(DEFAULT_INDEX_KEY); const defaultIndex = useMemo(() => { @@ -154,12 +159,16 @@ export const useWithSource = ( setState((prevState) => ({ ...prevState, loading: true })); try { - const result = await apolloClient.query({ + const result = await apolloClient.query< + SourceQuery.Query, + SourceQuery.Variables & { queryDeduplication: string } + >({ query: sourceQuery, - fetchPolicy: 'network-only', + fetchPolicy: 'cache-first', variables: { sourceId, defaultIndex, + queryDeduplication, }, context: { fetchOptions: { @@ -206,7 +215,7 @@ export const useWithSource = ( isSubscribed = false; return abortCtrl.abort(); }; - }, [apolloClient, sourceId, defaultIndex]); + }, [apolloClient, sourceId, defaultIndex, queryDeduplication]); return state; }; diff --git a/x-pack/plugins/security_solution/public/common/containers/use_full_screen/index.tsx b/x-pack/plugins/security_solution/public/common/containers/use_full_screen/index.tsx index b8050034d34a6..aa0d90a216035 100644 --- a/x-pack/plugins/security_solution/public/common/containers/use_full_screen/index.tsx +++ b/x-pack/plugins/security_solution/public/common/containers/use_full_screen/index.tsx @@ -6,6 +6,7 @@ import { useCallback, useMemo } from 'react'; import { useDispatch, useSelector } from 'react-redux'; +import { SCROLLING_DISABLED_CLASS_NAME } from '../../../../common/constants'; import { inputsSelectors } from '../../store'; import { inputsActions } from '../../store/actions'; @@ -16,7 +17,16 @@ export const useFullScreen = () => { const timelineFullScreen = useSelector(inputsSelectors.timelineFullScreenSelector) ?? false; const setGlobalFullScreen = useCallback( - (fullScreen: boolean) => dispatch(inputsActions.setFullScreen({ id: 'global', fullScreen })), + (fullScreen: boolean) => { + if (fullScreen) { + document.body.classList.add(SCROLLING_DISABLED_CLASS_NAME); + } else { + document.body.classList.remove(SCROLLING_DISABLED_CLASS_NAME); + setTimeout(() => window.scrollTo(0, 0), 0); + } + + dispatch(inputsActions.setFullScreen({ id: 'global', fullScreen })); + }, [dispatch] ); diff --git a/x-pack/plugins/security_solution/public/common/lib/kibana/__mocks__/index.ts b/x-pack/plugins/security_solution/public/common/lib/kibana/__mocks__/index.ts index 6ada887ece175..2c52acd3ec747 100644 --- a/x-pack/plugins/security_solution/public/common/lib/kibana/__mocks__/index.ts +++ b/x-pack/plugins/security_solution/public/common/lib/kibana/__mocks__/index.ts @@ -24,3 +24,4 @@ export const useToasts = jest.fn(() => notificationServiceMock.createStartContra export const useCurrentUser = jest.fn(); export const withKibana = jest.fn(createWithKibanaMock()); export const KibanaContextProvider = jest.fn(createKibanaContextProviderMock()); +export const useGetUserSavedObjectPermissions = jest.fn(); diff --git a/x-pack/plugins/security_solution/public/common/mock/news.ts b/x-pack/plugins/security_solution/public/common/mock/news.ts index 3e421ce19ae9c..51449347e649a 100644 --- a/x-pack/plugins/security_solution/public/common/mock/news.ts +++ b/x-pack/plugins/security_solution/public/common/mock/news.ts @@ -16,7 +16,7 @@ export const rawNewsApiResponse: RawNewsApiResponse = { "There's an awesome community of Elastic SIEM users out there. Join the discussion about configuring, learning, and using the Elastic SIEM app, and detecting threats!", }, link_text: null, - link_url: { en: 'https://discuss.elastic.co/c/siem?blade=securitysolutionfeed' }, + link_url: { en: 'https://discuss.elastic.co/c/security?blade=securitysolutionfeed' }, languages: null, badge: { en: '7.6' }, image_url: { diff --git a/x-pack/plugins/security_solution/public/common/mock/raw_news.ts b/x-pack/plugins/security_solution/public/common/mock/raw_news.ts index 85bef15a41b23..9cd06ed107956 100644 --- a/x-pack/plugins/security_solution/public/common/mock/raw_news.ts +++ b/x-pack/plugins/security_solution/public/common/mock/raw_news.ts @@ -17,7 +17,7 @@ export const rawNewsJSON = ` }, "link_text":null, "link_url":{ - "en":"https://discuss.elastic.co/c/siem?blade=securitysolutionfeed" + "en":"https://discuss.elastic.co/c/security?blade=securitysolutionfeed" }, "languages":null, "badge":{ diff --git a/x-pack/plugins/security_solution/public/common/translations.ts b/x-pack/plugins/security_solution/public/common/translations.ts index 413119fb40f14..3b94ac8959496 100644 --- a/x-pack/plugins/security_solution/public/common/translations.ts +++ b/x-pack/plugins/security_solution/public/common/translations.ts @@ -7,16 +7,39 @@ import { i18n } from '@kbn/i18n'; export const EMPTY_TITLE = i18n.translate('xpack.securitySolution.pages.common.emptyTitle', { - defaultMessage: 'Welcome to Security Solution. Let’s get you started.', + defaultMessage: 'Welcome to Elastic Security. Let’s get you started.', }); -export const EMPTY_ACTION_PRIMARY = i18n.translate( - 'xpack.securitySolution.pages.common.emptyActionPrimary', +export const EMPTY_ACTION_ELASTIC_AGENT = i18n.translate( + 'xpack.securitySolution.pages.common.emptyActionElasticAgent', + { + defaultMessage: 'Add data with Elastic Agent', + } +); + +export const EMPTY_ACTION_ELASTIC_AGENT_DESCRIPTION = i18n.translate( + 'xpack.securitySolution.pages.common.emptyActionElasticAgentDescription', + { + defaultMessage: + 'The Elastic Agent provides a simple, unified way to add monitoring to your hosts.', + } +); + +export const EMPTY_ACTION_BEATS = i18n.translate( + 'xpack.securitySolution.pages.common.emptyActionBeats', { defaultMessage: 'Add data with Beats', } ); +export const EMPTY_ACTION_BEATS_DESCRIPTION = i18n.translate( + 'xpack.securitySolution.pages.common.emptyActionBeatsDescription', + { + defaultMessage: + 'Lightweight Beats can send data from hundreds or thousands of machines and systems', + } +); + export const EMPTY_ACTION_SECONDARY = i18n.translate( 'xpack.securitySolution.pages.common.emptyActionSecondary', { @@ -27,6 +50,14 @@ export const EMPTY_ACTION_SECONDARY = i18n.translate( export const EMPTY_ACTION_ENDPOINT = i18n.translate( 'xpack.securitySolution.pages.common.emptyActionEndpoint', { - defaultMessage: 'Add data with Elastic Agent (Beta)', + defaultMessage: 'Add Elastic Endpoint Security', + } +); + +export const EMPTY_ACTION_ENDPOINT_DESCRIPTION = i18n.translate( + 'xpack.securitySolution.pages.common.emptyActionEndpointDescription', + { + defaultMessage: + 'Protect your hosts with threat prevention, detection, and deep security data visibility.', } ); diff --git a/x-pack/plugins/security_solution/public/common/utils/timeline/use_show_timeline.test.tsx b/x-pack/plugins/security_solution/public/common/utils/timeline/use_show_timeline.test.tsx new file mode 100644 index 0000000000000..db6e2536ce558 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/utils/timeline/use_show_timeline.test.tsx @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { renderHook, act } from '@testing-library/react-hooks'; +import { useShowTimeline } from './use_show_timeline'; +import { globalNode } from '../../mock'; + +describe('use show timeline', () => { + it('shows timeline for routes on default', async () => { + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => useShowTimeline()); + await waitForNextUpdate(); + const uninitializedTimeline = result.current; + expect(uninitializedTimeline).toEqual([true]); + }); + }); + it('hides timeline for blacklist routes', async () => { + await act(async () => { + Object.defineProperty(globalNode.window, 'location', { + value: { + pathname: `/cases/configure`, + }, + }); + const { result, waitForNextUpdate } = renderHook(() => useShowTimeline()); + await waitForNextUpdate(); + const uninitializedTimeline = result.current; + expect(uninitializedTimeline).toEqual([false]); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/default_config.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/default_config.tsx index a4ce6c0200eb3..010129d2d4593 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/default_config.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/default_config.tsx @@ -204,6 +204,7 @@ export const requiredFieldsForActions = [ 'file.Ext.code_signature.trusted', 'file.hash.sha1', 'host.os.family', + 'event.code', ]; interface AlertActionArgs { diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx index 1eda358fe5944..ab95e433d92f3 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx @@ -116,8 +116,9 @@ export const AlertsTableComponent: React.FC = ({ const [addExceptionModalState, setAddExceptionModalState] = useState( addExceptionModalInitialState ); - const [{ browserFields, indexPatterns }] = useFetchIndexPatterns( - signalsIndex !== '' ? [signalsIndex] : [] + const [{ browserFields, indexPatterns, isLoading: indexPatternsLoading }] = useFetchIndexPatterns( + signalsIndex !== '' ? [signalsIndex] : [], + 'alerts_table' ); const kibana = useKibana(); const [, dispatchToaster] = useStateToaster(); @@ -433,7 +434,7 @@ export const AlertsTableComponent: React.FC = ({ closeAddExceptionModal, ]); - if (loading || isEmpty(signalsIndex)) { + if (loading || indexPatternsLoading || isEmpty(signalsIndex)) { return ( diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.test.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.test.tsx index 2a6cd3fc5bb7a..0d98a0f2f26ff 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.test.tsx @@ -331,6 +331,7 @@ describe('helpers', () => { const result: ListItems[] = buildSeverityDescription({ value: 'low', mapping: [{ field: 'host.name', operator: 'equals', value: 'hello', severity: 'high' }], + isMappingChecked: true, }); expect(result[0].title).toEqual('Severity'); diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.tsx index 1110c8c098988..600bc999849d1 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.tsx @@ -35,6 +35,7 @@ import { SeverityBadge } from '../severity_badge'; import ListTreeIcon from './assets/list_tree_icon.svg'; import { assertUnreachable } from '../../../../common/lib/helpers'; import { AboutStepRiskScore, AboutStepSeverity } from '../../../pages/detection_engine/rules/types'; +import { defaultToEmptyTag } from '../../../../common/components/empty_value'; const NoteDescriptionContainer = styled(EuiFlexItem)` height: 105px; @@ -236,35 +237,44 @@ export const buildSeverityDescription = (severity: AboutStepSeverity): ListItems title: i18nSeverity.DEFAULT_SEVERITY, description: , }, - ...severity.mapping.map((severityItem, index) => { - return { - title: index === 0 ? i18nSeverity.SEVERITY_MAPPING : '', - description: ( - - - - <>{severityItem.field} - - - - <>{severityItem.value} - - - - - - - - - ), - }; - }), + ...(severity.isMappingChecked + ? severity.mapping + .filter((severityItem) => severityItem.field !== '') + .map((severityItem, index) => { + return { + title: index === 0 ? i18nSeverity.SEVERITY_MAPPING : '', + description: ( + + + + <>{`${severityItem.field}:`} + + + + + {defaultToEmptyTag(severityItem.value)} + + + + + + + + + + ), + }; + }) + : []), ]; export const buildRiskScoreDescription = (riskScore: AboutStepRiskScore): ListItems[] => [ @@ -272,27 +282,31 @@ export const buildRiskScoreDescription = (riskScore: AboutStepRiskScore): ListIt title: i18nRiskScore.RISK_SCORE, description: riskScore.value, }, - ...riskScore.mapping.map((riskScoreItem, index) => { - return { - title: index === 0 ? i18nRiskScore.RISK_SCORE_MAPPING : '', - description: ( - - - - <>{riskScoreItem.field} - - - - - - {'signal.rule.risk_score'} - - ), - }; - }), + ...(riskScore.isMappingChecked + ? riskScore.mapping + .filter((riskScoreItem) => riskScoreItem.field !== '') + .map((riskScoreItem, index) => { + return { + title: index === 0 ? i18nRiskScore.RISK_SCORE_MAPPING : '', + description: ( + + + + <>{riskScoreItem.field} + + + + + + {'signal.rule.risk_score'} + + ), + }; + }) + : []), ]; const MyRefUrlLink = styled(EuiLink)` diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/mitre/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/mitre/index.tsx index e898a362c7771..71734affd42ce 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/mitre/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/mitre/index.tsx @@ -35,7 +35,7 @@ const MyEuiSuperSelect = styled(EuiSuperSelect)` `; interface AddItemProps { field: FieldHook; - dataTestSubj: string; + dataTestSubj: string; // eslint-disable-line react/no-unused-prop-types idAria: string; isDisabled: boolean; } diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/ml_job_select/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/ml_job_select/index.tsx index cb084d4daa782..cdfdf4ca6b66b 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/ml_job_select/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/ml_job_select/index.tsx @@ -41,7 +41,7 @@ const HelpText: React.FC<{ href: string; showEnableWarning: boolean }> = ({ <> diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/translations.ts b/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/translations.ts index 37c1715c05d71..49da7dbf6d514 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/translations.ts +++ b/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/translations.ts @@ -24,7 +24,7 @@ export const PRE_BUILT_MSG = i18n.translate( export const PRE_BUILT_ACTION = i18n.translate( 'xpack.securitySolution.detectionEngine.rules.prePackagedRules.loadPreBuiltButton', { - defaultMessage: 'Load prebuilt detection rules', + defaultMessage: 'Load prebuilt detection rules and timeline templates', } ); diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/update_callout.test.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/update_callout.test.tsx index 5033fcd11dc7c..283bba462792c 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/update_callout.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/update_callout.test.tsx @@ -9,6 +9,7 @@ import { shallow } from 'enzyme'; import { UpdatePrePackagedRulesCallOut } from './update_callout'; import { useKibana } from '../../../../common/lib/kibana'; + jest.mock('../../../../common/lib/kibana'); describe('UpdatePrePackagedRulesCallOut', () => { @@ -22,6 +23,7 @@ describe('UpdatePrePackagedRulesCallOut', () => { }, }); }); + it('renders correctly', () => { const wrapper = shallow( { expect(wrapper.find('EuiCallOut')).toHaveLength(1); }); + + it('renders callOutMessage correctly: numberOfUpdatedRules > 0 and numberOfUpdatedTimelines = 0', () => { + const wrapper = shallow( + + ); + + expect(wrapper.find('[data-test-subj="update-callout"]').find('p').text()).toEqual( + 'You can update 1 Elastic prebuilt ruleRelease notes' + ); + }); + + it('renders buttonTitle correctly: numberOfUpdatedRules > 0 and numberOfUpdatedTimelines = 0', () => { + const wrapper = shallow( + + ); + + expect(wrapper.find('[data-test-subj="update-callout-button"]').prop('children')).toEqual( + 'Update 1 Elastic prebuilt rule' + ); + }); + + it('renders callOutMessage correctly: numberOfUpdatedRules = 0 and numberOfUpdatedTimelines > 0', () => { + const wrapper = shallow( + + ); + + expect(wrapper.find('[data-test-subj="update-callout"]').find('p').text()).toEqual( + 'You can update 1 Elastic prebuilt timelineRelease notes' + ); + }); + + it('renders buttonTitle correctly: numberOfUpdatedRules = 0 and numberOfUpdatedTimelines > 0', () => { + const wrapper = shallow( + + ); + + expect(wrapper.find('[data-test-subj="update-callout-button"]').prop('children')).toEqual( + 'Update 1 Elastic prebuilt timeline' + ); + }); + + it('renders callOutMessage correctly: numberOfUpdatedRules > 0 and numberOfUpdatedTimelines > 0', () => { + const wrapper = shallow( + + ); + + expect(wrapper.find('[data-test-subj="update-callout"]').find('p').text()).toEqual( + 'You can update 1 Elastic prebuilt rule and 1 Elastic prebuilt timeline. Note that this will reload deleted Elastic prebuilt rules.Release notes' + ); + }); + + it('renders buttonTitle correctly: numberOfUpdatedRules > 0 and numberOfUpdatedTimelines > 0', () => { + const wrapper = shallow( + + ); + + expect(wrapper.find('[data-test-subj="update-callout-button"]').prop('children')).toEqual( + 'Update 1 Elastic prebuilt rule and 1 Elastic prebuilt timeline' + ); + }); }); diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/update_callout.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/update_callout.tsx index 4b454a9ed4d4a..30f8cfa7fb3a5 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/update_callout.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/update_callout.tsx @@ -51,7 +51,7 @@ const UpdatePrePackagedRulesCallOutComponent: React.FC +

{prepackagedRulesOrTimelines?.callOutMessage}
@@ -62,7 +62,12 @@ const UpdatePrePackagedRulesCallOutComponent: React.FC

- + {prepackagedRulesOrTimelines?.buttonTitle}
diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/risk_score_mapping/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/risk_score_mapping/index.tsx index c9e2cb1a8ca24..35816e82540d1 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/risk_score_mapping/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/risk_score_mapping/index.tsx @@ -14,8 +14,9 @@ import { EuiIcon, EuiSpacer, } from '@elastic/eui'; -import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import React, { useCallback, useMemo } from 'react'; import styled from 'styled-components'; +import { noop } from 'lodash/fp'; import * as i18n from './translations'; import { FieldHook } from '../../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; import { CommonUseField } from '../../../../cases/components/create'; @@ -24,6 +25,10 @@ import { FieldComponent } from '../../../../common/components/autocomplete/field import { IFieldType } from '../../../../../../../../src/plugins/data/common/index_patterns/fields'; import { IIndexPattern } from '../../../../../../../../src/plugins/data/common/index_patterns'; +const RiskScoreMappingEuiFormRow = styled(EuiFormRow)` + width: 468px; +`; + const NestedContent = styled.div` margin-left: 24px; `; @@ -41,6 +46,7 @@ interface RiskScoreFieldProps { field: FieldHook; idAria: string; indices: IIndexPattern; + isDisabled: boolean; placeholder?: string; } @@ -49,40 +55,23 @@ export const RiskScoreField = ({ field, idAria, indices, + isDisabled, placeholder, }: RiskScoreFieldProps) => { - const [isRiskScoreMappingChecked, setIsRiskScoreMappingChecked] = useState(false); - const [initialFieldCheck, setInitialFieldCheck] = useState(true); - const fieldTypeFilter = useMemo(() => ['number'], []); - useEffect(() => { - if ( - !isRiskScoreMappingChecked && - initialFieldCheck && - (field.value as AboutStepRiskScore).mapping?.length > 0 - ) { - setIsRiskScoreMappingChecked(true); - setInitialFieldCheck(false); - } - }, [ - field, - initialFieldCheck, - isRiskScoreMappingChecked, - setIsRiskScoreMappingChecked, - setInitialFieldCheck, - ]); - const handleFieldChange = useCallback( ([newField]: IFieldType[]): void => { const values = field.value as AboutStepRiskScore; field.setValue({ value: values.value, + isMappingChecked: values.isMappingChecked, mapping: [ { field: newField?.name ?? '', operator: 'equals', - value: '', + value: undefined, + riskScore: undefined, }, ], }); @@ -99,8 +88,13 @@ export const RiskScoreField = ({ }, [field.value, indices]); const handleRiskScoreMappingChecked = useCallback(() => { - setIsRiskScoreMappingChecked(!isRiskScoreMappingChecked); - }, [isRiskScoreMappingChecked, setIsRiskScoreMappingChecked]); + const values = field.value as AboutStepRiskScore; + field.setValue({ + value: values.value, + mapping: [...values.mapping], + isMappingChecked: !values.isMappingChecked, + }); + }, [field]); const riskScoreLabel = useMemo(() => { return ( @@ -117,11 +111,16 @@ export const RiskScoreField = ({ const riskScoreMappingLabel = useMemo(() => { return (
- + @@ -133,7 +132,7 @@ export const RiskScoreField = ({
); - }, [handleRiskScoreMappingChecked, isRiskScoreMappingChecked]); + }, [field.value, handleRiskScoreMappingChecked, isDisabled]); return ( @@ -153,6 +152,7 @@ export const RiskScoreField = ({ componentProps={{ idAria: 'detectionEngineStepAboutRuleRiskScore', 'data-test-subj': 'detectionEngineStepAboutRuleRiskScore', + isDisabled, euiFieldProps: { max: 100, min: 0, @@ -166,11 +166,11 @@ export const RiskScoreField = ({ - {i18n.RISK_SCORE_MAPPING_DETAILS} ) : ( '' @@ -184,7 +184,7 @@ export const RiskScoreField = ({ > - {isRiskScoreMappingChecked && ( + {(field.value as AboutStepRiskScore).isMappingChecked && ( @@ -208,11 +208,11 @@ export const RiskScoreField = ({ fieldTypeFilter={fieldTypeFilter} isLoading={false} isClearable={false} - isDisabled={false} + isDisabled={isDisabled} onChange={handleFieldChange} data-test-subj={dataTestSubj} aria-label={idAria} - fieldInputWidth={230} + fieldInputWidth={270} /> @@ -226,7 +226,7 @@ export const RiskScoreField = ({ )} - + ); diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/severity_mapping/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/severity_mapping/index.tsx index 579c60579b32e..54d505a4d867f 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/severity_mapping/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/severity_mapping/index.tsx @@ -14,7 +14,8 @@ import { EuiIcon, EuiSpacer, } from '@elastic/eui'; -import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import { noop } from 'lodash/fp'; +import React, { useCallback, useMemo } from 'react'; import styled from 'styled-components'; import * as i18n from './translations'; import { FieldHook } from '../../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; @@ -27,10 +28,16 @@ import { } from '../../../../../../../../src/plugins/data/common/index_patterns'; import { FieldComponent } from '../../../../common/components/autocomplete/field'; import { AutocompleteFieldMatchComponent } from '../../../../common/components/autocomplete/field_value_match'; +import { + Severity, + SeverityMapping, + SeverityMappingItem, +} from '../../../../../common/detection_engine/schemas/common/schemas'; -const SeverityMappingParentContainer = styled(EuiFlexItem)` - max-width: 471px; +const SeverityMappingEuiFormRow = styled(EuiFormRow)` + width: 468px; `; + const NestedContent = styled.div` margin-left: 24px; `; @@ -48,6 +55,7 @@ interface SeverityFieldProps { field: FieldHook; idAria: string; indices: IIndexPattern; + isDisabled: boolean; options: SeverityOptionItem[]; } @@ -56,42 +64,20 @@ export const SeverityField = ({ field, idAria, indices, + isDisabled, options, }: SeverityFieldProps) => { - const [isSeverityMappingChecked, setIsSeverityMappingChecked] = useState(false); - const [initialFieldCheck, setInitialFieldCheck] = useState(true); const fieldValueInputWidth = 160; - useEffect(() => { - if ( - !isSeverityMappingChecked && - initialFieldCheck && - (field.value as AboutStepSeverity).mapping?.length > 0 - ) { - setIsSeverityMappingChecked(true); - setInitialFieldCheck(false); - } - }, [ - field, - initialFieldCheck, - isSeverityMappingChecked, - setIsSeverityMappingChecked, - setInitialFieldCheck, - ]); - - const handleFieldChange = useCallback( - (index: number, severity: string, [newField]: IFieldType[]): void => { + const handleFieldValueChange = useCallback( + (newMappingItems: SeverityMapping, index: number): void => { const values = field.value as AboutStepSeverity; field.setValue({ value: values.value, + isMappingChecked: values.isMappingChecked, mapping: [ ...values.mapping.slice(0, index), - { - ...values.mapping[index], - field: newField?.name ?? '', - operator: 'equals', - severity, - }, + ...newMappingItems, ...values.mapping.slice(index + 1), ], }); @@ -99,40 +85,59 @@ export const SeverityField = ({ [field] ); + const handleFieldChange = useCallback( + (index: number, severity: Severity, [newField]: IFieldType[]): void => { + const values = field.value as AboutStepSeverity; + const newMappingItems: SeverityMapping = [ + { + ...values.mapping[index], + field: newField?.name ?? '', + value: newField != null ? values.mapping[index].value : '', + operator: 'equals', + severity, + }, + ]; + handleFieldValueChange(newMappingItems, index); + }, + [field, handleFieldValueChange] + ); + const handleFieldMatchValueChange = useCallback( - (index: number, severity: string, newMatchValue: string): void => { + (index: number, severity: Severity, newMatchValue: string): void => { const values = field.value as AboutStepSeverity; - field.setValue({ - value: values.value, - mapping: [ - ...values.mapping.slice(0, index), - { - ...values.mapping[index], - value: newMatchValue, - operator: 'equals', - severity, - }, - ...values.mapping.slice(index + 1), - ], - }); + const newMappingItems: SeverityMapping = [ + { + ...values.mapping[index], + field: values.mapping[index].field, + value: + values.mapping[index].field != null && values.mapping[index].field !== '' + ? newMatchValue + : '', + operator: 'equals', + severity, + }, + ]; + handleFieldValueChange(newMappingItems, index); }, - [field] + [field, handleFieldValueChange] ); - const selectedState = useMemo(() => { - return ( - (field.value as AboutStepSeverity).mapping?.map((mapping) => { - const [newSelectedField] = indices.fields.filter( - ({ name }) => mapping.field != null && mapping.field === name - ); - return { field: newSelectedField, value: mapping.value }; - }) ?? [] - ); - }, [field.value, indices]); + const getIFieldTypeFromFieldName = ( + fieldName: string | undefined, + iIndexPattern: IIndexPattern + ): IFieldType | undefined => { + const [iFieldType] = iIndexPattern.fields.filter(({ name }) => fieldName === name); + return iFieldType; + }; - const handleSeverityMappingSelected = useCallback(() => { - setIsSeverityMappingChecked(!isSeverityMappingChecked); - }, [isSeverityMappingChecked, setIsSeverityMappingChecked]); + const handleSeverityMappingChecked = useCallback(() => { + const values = field.value as AboutStepSeverity; + field.setValue({ + value: values.value, + mapping: [...values.mapping], + isMappingChecked: !values.isMappingChecked, + }); + }, [field]); const severityLabel = useMemo(() => { return ( @@ -149,12 +154,17 @@ export const SeverityField = ({ const severityMappingLabel = useMemo(() => { return (
- + {i18n.SEVERITY_MAPPING} @@ -165,7 +175,7 @@ export const SeverityField = ({
); - }, [handleSeverityMappingSelected, isSeverityMappingChecked]); + }, [field.value, handleSeverityMappingChecked, isDisabled]); return ( @@ -185,6 +195,7 @@ export const SeverityField = ({ componentProps={{ idAria: 'detectionEngineStepAboutRuleSeverity', 'data-test-subj': 'detectionEngineStepAboutRuleSeverity', + isDisabled, euiFieldProps: { fullWidth: false, disabled: false, @@ -195,12 +206,12 @@ export const SeverityField = ({ - - + {i18n.SEVERITY_MAPPING_DETAILS} ) : ( '' @@ -214,7 +225,7 @@ export const SeverityField = ({ > - {isSeverityMappingChecked && ( + {(field.value as AboutStepSeverity).isMappingChecked && ( @@ -231,53 +242,72 @@ export const SeverityField = ({ - {options.map((option, index) => ( - - - - - + {(field.value as AboutStepSeverity).mapping.map( + (severityMappingItem: SeverityMappingItem, index) => ( + + + + + - - - - - - - - {option.inputDisplay} - - - - ))} + + + + + + + + { + options.find((o) => o.value === severityMappingItem.severity) + ?.inputDisplay + } + + + + ) + )} )} - - + + ); }; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/default_value.ts b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/default_value.ts index f5d61553b595b..b9c3e4f84c18e 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/default_value.ts +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/default_value.ts @@ -5,6 +5,7 @@ */ import { AboutStepRule } from '../../../pages/detection_engine/rules/types'; +import { fillEmptySeverityMappings } from '../../../pages/detection_engine/rules/helpers'; export const threatDefault = [ { @@ -21,8 +22,8 @@ export const stepAboutDefaultValue: AboutStepRule = { isAssociatedToEndpointList: false, isBuildingBlock: false, isNew: true, - severity: { value: 'low', mapping: [] }, - riskScore: { value: 50, mapping: [] }, + severity: { value: 'low', mapping: fillEmptySeverityMappings([]), isMappingChecked: false }, + riskScore: { value: 50, mapping: [], isMappingChecked: false }, references: [''], falsePositives: [''], license: '', diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx index a86c1b7ce1bea..cb3fd5e5bec32 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx @@ -16,6 +16,7 @@ import { stepAboutDefaultValue } from './default_value'; // we don't have the types for waitFor just yet, so using "as waitFor" until when we do import { wait as waitFor } from '@testing-library/react'; import { AboutStepRule } from '../../../pages/detection_engine/rules/types'; +import { fillEmptySeverityMappings } from '../../../pages/detection_engine/rules/helpers'; const theme = () => ({ eui: euiDarkVars, darkMode: true }); @@ -176,8 +177,8 @@ describe('StepAboutRuleComponent', () => { name: 'Test name text', note: '', references: [''], - riskScore: { value: 50, mapping: [] }, - severity: { value: 'low', mapping: [] }, + riskScore: { value: 50, mapping: [], isMappingChecked: false }, + severity: { value: 'low', mapping: fillEmptySeverityMappings([]), isMappingChecked: false }, tags: [], threat: [ { @@ -236,8 +237,8 @@ describe('StepAboutRuleComponent', () => { name: 'Test name text', note: '', references: [''], - riskScore: { value: 80, mapping: [] }, - severity: { value: 'low', mapping: [] }, + riskScore: { value: 80, mapping: [], isMappingChecked: false }, + severity: { value: 'low', mapping: fillEmptySeverityMappings([]), isMappingChecked: false }, tags: [], threat: [ { diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx index ec812fa63eadf..5edf6f0a9312e 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx @@ -74,7 +74,8 @@ const StepAboutRuleComponent: FC = ({ const initialState = defaultValues ?? stepAboutDefaultValue; const [myStepData, setMyStepData] = useState(initialState); const [{ isLoading: indexPatternLoading, indexPatterns }] = useFetchIndexPatterns( - defineRuleData?.index ?? [] + defineRuleData?.index ?? [], + 'step_about_rule' ); const canUseExceptions = defineRuleData?.ruleType && diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/schema.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/schema.tsx index fbd03850eee75..20470d7bb924f 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/schema.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/schema.tsx @@ -117,18 +117,16 @@ export const schema: FormSchema = { }, ], }, - mapping: { - type: FIELD_TYPES.TEXT, - }, + mapping: {}, + isMappingChecked: {}, }, riskScore: { value: { type: FIELD_TYPES.RANGE, serializer: (input: string) => Number(input), }, - mapping: { - type: FIELD_TYPES.TEXT, - }, + mapping: {}, + isMappingChecked: {}, }, references: { label: i18n.translate( diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/index.tsx index 51e9291f31941..3d5b66b8869cc 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/index.tsx @@ -117,7 +117,7 @@ const StepDefineRuleComponent: FC = ({ const [myStepData, setMyStepData] = useState(initialState); const [ { browserFields, indexPatterns: indexPatternQueryBar, isLoading: indexPatternLoadingQueryBar }, - ] = useFetchIndexPatterns(myStepData.index); + ] = useFetchIndexPatterns(myStepData.index, 'step_define_rule'); const { form } = useForm({ defaultValue: initialState, diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_rule_actions/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_rule_actions/index.tsx index 2b842515d0b71..5b4f7677dbc30 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_rule_actions/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_rule_actions/index.tsx @@ -15,6 +15,7 @@ import { import { findIndex } from 'lodash/fp'; import React, { FC, memo, useCallback, useEffect, useMemo, useState } from 'react'; +import { ActionVariable } from '../../../../../../triggers_actions_ui/public'; import { RuleStep, RuleStepProps, @@ -36,7 +37,7 @@ import { APP_ID } from '../../../../../common/constants'; interface StepRuleActionsProps extends RuleStepProps { defaultValues?: ActionsStepRule | null; - actionMessageParams: string[]; + actionMessageParams: ActionVariable[]; } const stepActionsDefaultValue = { diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/auto_download.test.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/auto_download.test.tsx new file mode 100644 index 0000000000000..53dcf986d395c --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/auto_download.test.tsx @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { mount } from 'enzyme'; + +import { globalNode } from '../../../common/mock'; +import { AutoDownload } from './auto_download'; + +describe('AutoDownload', () => { + beforeEach(() => { + // our DOM environment lacks this function that our component needs + Object.defineProperty(globalNode.window.URL, 'revokeObjectURL', { + writable: true, + value: jest.fn(), + }); + }); + + it('calls onDownload once if a blob is provided', () => { + const onDownload = jest.fn(); + mount(); + + expect(onDownload).toHaveBeenCalledTimes(1); + }); + + it('does not call onDownload if no blob is provided', () => { + const onDownload = jest.fn(); + mount(); + + expect(onDownload).not.toHaveBeenCalled(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/auto_download.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/auto_download.tsx new file mode 100644 index 0000000000000..9c8280bebe4fd --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/auto_download.tsx @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useEffect, useRef } from 'react'; +import styled from 'styled-components'; + +const InvisibleAnchor = styled.a` + display: none; +`; + +interface AutoDownloadProps { + blob: Blob | undefined; + name?: string; + onDownload?: () => void; +} + +export const AutoDownload: React.FC = ({ blob, name, onDownload }) => { + const anchorRef = useRef(null); + + useEffect(() => { + if (blob && anchorRef?.current) { + if (typeof window.navigator.msSaveOrOpenBlob === 'function') { + window.navigator.msSaveBlob(blob); + } else { + const objectURL = window.URL.createObjectURL(blob); + anchorRef.current.href = objectURL; + anchorRef.current.download = name ?? 'download.txt'; + anchorRef.current.click(); + window.URL.revokeObjectURL(objectURL); + } + + if (onDownload) { + onDownload(); + } + } + }, [blob, name, onDownload]); + + return ; +}; diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.tsx index aab665289e80d..c35cc612129d5 100644 --- a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.tsx @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useCallback, useState, ReactNode, useEffect, useRef } from 'react'; -import styled from 'styled-components'; +import React, { useCallback, useState, useEffect, useRef } from 'react'; import { EuiButton, EuiButtonEmpty, @@ -14,34 +13,30 @@ import { EuiFilePicker, EuiFlexGroup, EuiFlexItem, - EuiRadioGroup, + EuiSelect, + EuiSelectOption, } from '@elastic/eui'; import { useImportList, ListSchema, Type } from '../../../shared_imports'; import * as i18n from './translations'; import { useKibana } from '../../../common/lib/kibana'; -const InlineRadioGroup = styled(EuiRadioGroup)` - display: flex; - - .euiRadioGroup__item + .euiRadioGroup__item { - margin: 0 0 0 12px; - } -`; - -interface ListTypeOptions { - id: Type; - label: ReactNode; -} - -const options: ListTypeOptions[] = [ +const options: EuiSelectOption[] = [ { - id: 'keyword', - label: i18n.KEYWORDS_RADIO, + value: 'keyword', + text: i18n.KEYWORDS_RADIO, }, { - id: 'ip', - label: i18n.IP_RADIO, + value: 'ip', + text: i18n.IP_RADIO, + }, + { + value: 'ip_range', + text: i18n.IP_RANGE_RADIO, + }, + { + value: 'text', + text: i18n.TEXT_RADIO, }, ]; @@ -63,8 +58,10 @@ export const ValueListsFormComponent: React.FC = ({ onError const fileIsValid = !file || validFileTypes.some((fileType) => file.type === fileType); - // EuiRadioGroup's onChange only infers 'string' from our options - const handleRadioChange = useCallback((t: string) => setType(t as Type), [setType]); + const handleRadioChange = useCallback( + (event: React.ChangeEvent) => setType(event.target.value as Type), + [setType] + ); const handleFileChange = useCallback((files: FileList | null) => { setFile(files?.item(0) ?? null); @@ -133,6 +130,7 @@ export const ValueListsFormComponent: React.FC = ({ onError > = ({ onError - - + {importState.loading && ( diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx index 175882de551cb..ff743d1d5090a 100644 --- a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx @@ -6,11 +6,38 @@ import React from 'react'; import { mount } from 'enzyme'; +import { act } from 'react-dom/test-utils'; +import { getListResponseMock } from '../../../../../lists/common/schemas/response/list_schema.mock'; +import { exportList, useDeleteList, useFindLists, ListSchema } from '../../../shared_imports'; import { TestProviders } from '../../../common/mock'; import { ValueListsModal } from './modal'; +jest.mock('../../../shared_imports', () => { + const actual = jest.requireActual('../../../shared_imports'); + + return { + ...actual, + exportList: jest.fn(), + useDeleteList: jest.fn(), + useFindLists: jest.fn(), + }; +}); + describe('ValueListsModal', () => { + beforeEach(() => { + // Do not resolve the export in tests as it causes unexpected state updates + (exportList as jest.Mock).mockImplementation(() => new Promise(() => {})); + (useFindLists as jest.Mock).mockReturnValue({ + start: jest.fn(), + result: { data: Array(3).fill(getListResponseMock()), total: 3 }, + }); + (useDeleteList as jest.Mock).mockReturnValue({ + start: jest.fn(), + result: getListResponseMock(), + }); + }); + it('renders nothing if showModal is false', () => { const container = mount( @@ -47,7 +74,7 @@ describe('ValueListsModal', () => { container.unmount(); }); - it('renders ValueListsForm and ValueListsTable', () => { + it('renders ValueListsForm and an EuiTable', () => { const container = mount( @@ -55,7 +82,50 @@ describe('ValueListsModal', () => { ); expect(container.find('ValueListsForm')).toHaveLength(1); - expect(container.find('ValueListsTable')).toHaveLength(1); + expect(container.find('EuiBasicTable')).toHaveLength(1); container.unmount(); }); + + describe('modal table actions', () => { + it('calls exportList when export is clicked', () => { + const container = mount( + + + + ); + + act(() => { + container + .find('button[data-test-subj="action-export-value-list"]') + .first() + .simulate('click'); + container.unmount(); + }); + + expect(exportList).toHaveBeenCalledWith(expect.objectContaining({ listId: 'some-list-id' })); + }); + + it('calls deleteList when delete is clicked', () => { + const deleteListMock = jest.fn(); + (useDeleteList as jest.Mock).mockReturnValue({ + start: deleteListMock, + result: getListResponseMock(), + }); + const container = mount( + + + + ); + + act(() => { + container + .find('button[data-test-subj="action-delete-value-list"]') + .first() + .simulate('click'); + container.unmount(); + }); + + expect(deleteListMock).toHaveBeenCalledWith(expect.objectContaining({ id: 'some-list-id' })); + }); + }); }); diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.tsx index dc72260439090..4921a98b38bd1 100644 --- a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.tsx @@ -6,6 +6,7 @@ import React, { useCallback, useEffect, useState } from 'react'; import { + EuiBasicTable, EuiButton, EuiModal, EuiModalBody, @@ -13,7 +14,9 @@ import { EuiModalHeader, EuiModalHeaderTitle, EuiOverlayMask, + EuiPanel, EuiSpacer, + EuiText, } from '@elastic/eui'; import { @@ -25,10 +28,10 @@ import { } from '../../../shared_imports'; import { useKibana } from '../../../common/lib/kibana'; import { useAppToasts } from '../../../common/hooks/use_app_toasts'; -import { GenericDownloader } from '../../../common/components/generic_downloader'; import * as i18n from './translations'; -import { ValueListsTable } from './table'; +import { buildColumns } from './table_helpers'; import { ValueListsForm } from './form'; +import { AutoDownload } from './auto_download'; interface ValueListsModalProps { onClose: () => void; @@ -45,8 +48,9 @@ export const ValueListsModalComponent: React.FC = ({ const { http } = useKibana().services; const { start: findLists, ...lists } = useFindLists(); const { start: deleteList, result: deleteResult } = useDeleteList(); - const [exportListId, setExportListId] = useState(); const [deletingListIds, setDeletingListIds] = useState([]); + const [exportingListIds, setExportingListIds] = useState([]); + const [exportDownload, setExportDownload] = useState<{ name?: string; blob?: Blob }>({}); const { addError, addSuccess } = useAppToasts(); const fetchLists = useCallback(() => { @@ -62,19 +66,26 @@ export const ValueListsModalComponent: React.FC = ({ ); useEffect(() => { - if (deleteResult != null && deletingListIds.length > 0) { - setDeletingListIds([...deletingListIds.filter((id) => id !== deleteResult.id)]); + if (deleteResult != null) { + setDeletingListIds((ids) => [...ids.filter((id) => id !== deleteResult.id)]); fetchLists(); } - }, [deleteResult, deletingListIds, fetchLists]); + }, [deleteResult, fetchLists]); const handleExport = useCallback( - async ({ ids }: { ids: string[] }) => - exportList({ http, listId: ids[0], signal: new AbortController().signal }), - [http] + async ({ id }: { id: string }) => { + try { + setExportingListIds((ids) => [...ids, id]); + const blob = await exportList({ http, listId: id, signal: new AbortController().signal }); + setExportDownload({ name: id, blob }); + } catch (error) { + addError(error, { title: i18n.EXPORT_ERROR }); + } finally { + setExportingListIds((ids) => [...ids.filter((_id) => _id !== id)]); + } + }, + [addError, http] ); - const handleExportClick = useCallback(({ id }: { id: string }) => setExportListId(id), []); - const handleExportComplete = useCallback(() => setExportListId(undefined), []); const handleTableChange = useCallback( ({ page: { index, size } }: { page: { index: number; size: number } }) => { @@ -121,8 +132,8 @@ export const ValueListsModalComponent: React.FC = ({ const tableItems = (lists.result?.data ?? []).map((item) => ({ ...item, - isExporting: item.id === exportListId, isDeleting: deletingListIds.includes(item.id), + isExporting: exportingListIds.includes(item.id), })); const pagination = { @@ -131,6 +142,7 @@ export const ValueListsModalComponent: React.FC = ({ totalItemCount: lists.result?.total ?? 0, hidePerPageOptions: true, }; + const columns = buildColumns(handleExport, handleDelete); return ( @@ -141,14 +153,19 @@ export const ValueListsModalComponent: React.FC = ({ - + + +

{i18n.TABLE_TITLE}

+
+ +
@@ -156,12 +173,10 @@ export const ValueListsModalComponent: React.FC = ({ - setExportDownload({})} />
); diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.test.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.test.tsx deleted file mode 100644 index 2724c0a0696b6..0000000000000 --- a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.test.tsx +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { mount } from 'enzyme'; -import { act } from 'react-dom/test-utils'; - -import { getListResponseMock } from '../../../../../lists/common/schemas/response/list_schema.mock'; -import { ListSchema } from '../../../../../lists/common/schemas/response'; -import { TestProviders } from '../../../common/mock'; -import { ValueListsTable } from './table'; -import { TableItem } from './types'; - -const buildItems = (lists: ListSchema[]): TableItem[] => - lists.map((list) => ({ - ...list, - isDeleting: false, - isExporting: false, - })); - -describe('ValueListsTable', () => { - it('renders a row for each list', () => { - const lists = Array(3).fill(getListResponseMock()); - const items = buildItems(lists); - const container = mount( - - - - ); - - expect(container.find('tbody tr')).toHaveLength(3); - }); - - it('calls onChange when pagination is modified', () => { - const lists = Array(6).fill(getListResponseMock()); - const items = buildItems(lists); - const onChange = jest.fn(); - const container = mount( - - - - ); - - act(() => { - container.find('a[data-test-subj="pagination-button-next"]').simulate('click'); - }); - - expect(onChange).toHaveBeenCalledWith( - expect.objectContaining({ page: expect.objectContaining({ index: 1 }) }) - ); - }); - - it('calls onExport when export is clicked', () => { - const lists = Array(3).fill(getListResponseMock()); - const items = buildItems(lists); - const onExport = jest.fn(); - const container = mount( - - - - ); - - act(() => { - container - .find('tbody tr') - .first() - .find('button[data-test-subj="action-export-value-list"]') - .simulate('click'); - }); - - expect(onExport).toHaveBeenCalledWith(expect.objectContaining({ id: 'some-list-id' })); - }); - - it('calls onDelete when delete is clicked', () => { - const lists = Array(3).fill(getListResponseMock()); - const items = buildItems(lists); - const onDelete = jest.fn(); - const container = mount( - - - - ); - - act(() => { - container - .find('tbody tr') - .first() - .find('button[data-test-subj="action-delete-value-list"]') - .simulate('click'); - }); - - expect(onDelete).toHaveBeenCalledWith(expect.objectContaining({ id: 'some-list-id' })); - }); -}); diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.tsx deleted file mode 100644 index 850716ce54e26..0000000000000 --- a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.tsx +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { EuiBasicTable, EuiText, EuiPanel } from '@elastic/eui'; - -import * as i18n from './translations'; -import { buildColumns } from './table_helpers'; -import { TableProps, TableItemCallback } from './types'; - -export interface ValueListsTableProps { - items: TableProps['items']; - loading: boolean; - onChange: TableProps['onChange']; - onExport: TableItemCallback; - onDelete: TableItemCallback; - pagination: Exclude; -} - -export const ValueListsTableComponent: React.FC = ({ - items, - loading, - onChange, - onExport, - onDelete, - pagination, -}) => { - const columns = buildColumns(onExport, onDelete); - return ( - - -

{i18n.TABLE_TITLE}

-
- -
- ); -}; - -ValueListsTableComponent.displayName = 'ValueListsTableComponent'; - -export const ValueListsTable = React.memo(ValueListsTableComponent); - -ValueListsTable.displayName = 'ValueListsTable'; diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table_helpers.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table_helpers.tsx index e90d106636e63..bb3a97749a11a 100644 --- a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table_helpers.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table_helpers.tsx @@ -8,40 +8,18 @@ import React from 'react'; import styled from 'styled-components'; -import { EuiButtonIcon, IconType, EuiLoadingSpinner, EuiToolTip } from '@elastic/eui'; +import { EuiButtonIcon, EuiLoadingSpinner, EuiToolTip } from '@elastic/eui'; import { ListSchema } from '../../../../../lists/common/schemas/response'; import { FormattedDate } from '../../../common/components/formatted_date'; import * as i18n from './translations'; -import { TableItem, TableItemCallback, TableProps } from './types'; +import { TableItemCallback, TableProps } from './types'; const AlignedSpinner = styled(EuiLoadingSpinner)` margin: ${({ theme }) => theme.eui.euiSizeXS}; vertical-align: middle; `; -const ActionButton: React.FC<{ - content: string; - dataTestSubj: string; - icon: IconType; - isLoading: boolean; - item: TableItem; - onClick: TableItemCallback; -}> = ({ content, dataTestSubj, icon, item, onClick, isLoading }) => ( - - {isLoading ? ( - - ) : ( - onClick(item)} - /> - )} - -); - export const buildColumns = ( onExport: TableItemCallback, onDelete: TableItemCallback @@ -70,26 +48,34 @@ export const buildColumns = ( actions: [ { render: (item) => ( - + + {item.isExporting ? ( + + ) : ( + onExport(item)} + /> + )} + ), }, { render: (item) => ( - + + {item.isDeleting ? ( + + ) : ( + onDelete(item)} + /> + )} + ), }, ], diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/translations.ts b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/translations.ts index 91f3f3797f422..7063dca2341ca 100644 --- a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/translations.ts +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/translations.ts @@ -65,6 +65,10 @@ export const uploadSuccessMessage = (fileName: string) => values: { fileName }, }); +export const EXPORT_ERROR = i18n.translate('xpack.securitySolution.lists.valueListsExportError', { + defaultMessage: 'There was an error exporting the value list.', +}); + export const COLUMN_FILE_NAME = i18n.translate( 'xpack.securitySolution.lists.valueListsTable.fileNameColumn', { @@ -142,3 +146,17 @@ export const KEYWORDS_RADIO = i18n.translate( defaultMessage: 'Keywords', } ); + +export const IP_RANGE_RADIO = i18n.translate( + 'xpack.securitySolution.lists.valueListsForm.ipRangesRadioLabel', + { + defaultMessage: 'IP ranges', + } +); + +export const TEXT_RADIO = i18n.translate( + 'xpack.securitySolution.lists.valueListsForm.textRadioLabel', + { + defaultMessage: 'Text', + } +); diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/api.ts b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/api.ts index 66be5397c72c1..08d564230b85f 100644 --- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/api.ts +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/api.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import { HttpStart } from '../../../../../../../../src/core/public'; import { DETECTION_ENGINE_RULES_URL, DETECTION_ENGINE_PREPACKAGED_URL, @@ -126,7 +127,23 @@ export const fetchRules = async ({ * @throws An error if response is not OK */ export const fetchRuleById = async ({ id, signal }: FetchRuleProps): Promise => - KibanaServices.get().http.fetch(DETECTION_ENGINE_RULES_URL, { + pureFetchRuleById({ id, http: KibanaServices.get().http, signal }); + +/** + * Fetch a Rule by providing a Rule ID + * + * @param id Rule ID's (not rule_id) + * @param http Kibana http service + * @param signal to cancel request + * + * @throws An error if response is not OK + */ +export const pureFetchRuleById = async ({ + id, + http, + signal, +}: FetchRuleProps & { http: HttpStart }): Promise => + http.fetch(DETECTION_ENGINE_RULES_URL, { method: 'GET', query: { id }, signal, diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/fetch_index_patterns.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/fetch_index_patterns.tsx index c0997a5e62908..82c9292af7451 100644 --- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/fetch_index_patterns.tsx +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/fetch_index_patterns.tsx @@ -77,7 +77,7 @@ export const useFetchIndexPatterns = ( apolloClient .query({ query: sourceQuery, - fetchPolicy: 'network-only', + fetchPolicy: 'cache-first', variables: { sourceId: 'default', defaultIndex: indices, diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/use_pre_packaged_rules.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/use_pre_packaged_rules.tsx index 08c85695e9313..d82d97883a3d0 100644 --- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/use_pre_packaged_rules.tsx +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/use_pre_packaged_rules.tsx @@ -169,7 +169,9 @@ export const usePrePackagedRules = ({ if ( isSubscribed && ((prePackagedRuleStatusResponse.rules_not_installed === 0 && - prePackagedRuleStatusResponse.rules_not_updated === 0) || + prePackagedRuleStatusResponse.rules_not_updated === 0 && + prePackagedRuleStatusResponse.timelines_not_installed === 0 && + prePackagedRuleStatusResponse.timelines_not_updated === 0) || iterationTryOfFetchingPrePackagedCount > 100) ) { setLoadingCreatePrePackagedRules(false); diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/use_rule_async.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/use_rule_async.tsx new file mode 100644 index 0000000000000..fbca46097dcd9 --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/use_rule_async.tsx @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { useEffect, useCallback } from 'react'; + +import { useAsync, withOptionalSignal } from '../../../../shared_imports'; +import { useHttp } from '../../../../common/lib/kibana'; +import { useAppToasts } from '../../../../common/hooks/use_app_toasts'; +import { pureFetchRuleById } from './api'; +import { Rule } from './types'; +import * as i18n from './translations'; + +export interface UseRuleAsync { + error: unknown; + loading: boolean; + refresh: () => void; + rule: Rule | null; +} + +const _fetchRule = withOptionalSignal(pureFetchRuleById); +const _useRuleAsync = () => useAsync(_fetchRule); + +export const useRuleAsync = (ruleId: string): UseRuleAsync => { + const { start, loading, result, error } = _useRuleAsync(); + const http = useHttp(); + const { addError } = useAppToasts(); + + const fetch = useCallback(() => { + start({ id: ruleId, http }); + }, [http, ruleId, start]); + + // initial fetch + useEffect(() => { + fetch(); + }, [fetch]); + + // toast on error + useEffect(() => { + if (error != null) { + addError(error, { title: i18n.RULE_AND_TIMELINE_FETCH_FAILURE }); + } + }, [addError, error]); + + return { error, loading, refresh: fetch, rule: result ?? null }; +}; diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx index 110620fad7eba..982712cbe9797 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx @@ -53,6 +53,9 @@ jest.mock('react-router-dom', () => { useHistory: jest.fn(), }; }); +jest.mock('../../components/alerts_info', () => ({ + useAlertInfo: jest.fn().mockReturnValue([]), +})); const state: State = { ...mockGlobalState, diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx index 090fdc4980933..c114e4519df10 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx @@ -36,7 +36,7 @@ import { alertsHistogramOptions } from '../../components/alerts_histogram_panel/ import { useUserInfo } from '../../components/user_info'; import { EVENTS_VIEWER_HEADER_HEIGHT } from '../../../common/components/events_viewer/events_viewer'; import { OverviewEmpty } from '../../../overview/components/overview_empty'; -import { DetectionEngineNoIndex } from './detection_engine_no_signal_index'; +import { DetectionEngineNoIndex } from './detection_engine_no_index'; import { DetectionEngineHeaderPage } from '../../components/detection_engine_header_page'; import { useListsConfig } from '../../containers/detection_engine/lists/use_lists_config'; import { DetectionEngineUserUnauthenticated } from './detection_engine_user_unauthenticated'; @@ -144,7 +144,10 @@ export const DetectionEnginePageComponent: React.FC = ({ return ( - + ); } @@ -156,7 +159,10 @@ export const DetectionEnginePageComponent: React.FC = ({ {indicesExist ? ( - + diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_no_signal_index.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_no_index.test.tsx similarity index 72% rename from x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_no_signal_index.test.tsx rename to x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_no_index.test.tsx index 34d55908c9ba1..82d8ee9c63862 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_no_signal_index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_no_index.test.tsx @@ -7,12 +7,14 @@ import React from 'react'; import { shallow } from 'enzyme'; -import { DetectionEngineNoIndex } from './detection_engine_no_signal_index'; +import { DetectionEngineNoIndex } from './detection_engine_no_index'; jest.mock('../../../common/lib/kibana'); describe('DetectionEngineNoIndex', () => { it('renders correctly', () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); expect(wrapper.find('EmptyPage')).toHaveLength(1); }); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_no_index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_no_index.tsx new file mode 100644 index 0000000000000..648a9405606ef --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_no_index.tsx @@ -0,0 +1,53 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useMemo } from 'react'; + +import { EmptyPage } from '../../../common/components/empty_page'; +import * as i18n from './translations'; +import { useKibana } from '../../../common/lib/kibana'; + +const buildMessage = (needsListsIndex: boolean, needsSignalsIndex: boolean): string => { + if (needsSignalsIndex && needsListsIndex) { + return i18n.NEEDS_INDEX_PERMISSIONS(i18n.NEEDS_SIGNALS_AND_LISTS_INDEXES); + } else if (needsSignalsIndex) { + return i18n.NEEDS_INDEX_PERMISSIONS(i18n.NEEDS_SIGNALS_INDEX); + } else if (needsListsIndex) { + return i18n.NEEDS_INDEX_PERMISSIONS(i18n.NEEDS_LISTS_INDEXES); + } else { + return i18n.NEEDS_INDEX_PERMISSIONS(''); + } +}; + +const DetectionEngineNoIndexComponent: React.FC<{ + needsListsIndex: boolean; + needsSignalsIndex: boolean; +}> = ({ needsListsIndex, needsSignalsIndex }) => { + const docLinks = useKibana().services.docLinks; + const actions = useMemo( + () => ({ + detections: { + icon: 'documents', + label: i18n.GO_TO_DOCUMENTATION, + url: `${docLinks.ELASTIC_WEBSITE_URL}guide/en/security/${docLinks.DOC_LINK_VERSION}/detection-engine-overview.html#detections-permissions`, + target: '_blank', + }, + }), + [docLinks] + ); + const message = buildMessage(needsListsIndex, needsSignalsIndex); + + return ( + + ); +}; + +export const DetectionEngineNoIndex = React.memo(DetectionEngineNoIndexComponent); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_no_signal_index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_no_signal_index.tsx deleted file mode 100644 index 32ae585aec191..0000000000000 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_no_signal_index.tsx +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; - -import { EmptyPage } from '../../../common/components/empty_page'; -import * as i18n from './translations'; -import { useKibana } from '../../../common/lib/kibana'; - -export const DetectionEngineNoIndex = React.memo(() => { - const docLinks = useKibana().services.docLinks; - return ( - - ); -}); - -DetectionEngineNoIndex.displayName = 'DetectionEngineNoIndex'; diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_user_unauthenticated.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_user_unauthenticated.tsx index 6123e3740e306..355898cff0120 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_user_unauthenticated.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine_user_unauthenticated.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { useMemo } from 'react'; import { EmptyPage } from '../../../common/components/empty_page'; import * as i18n from './translations'; @@ -12,13 +12,20 @@ import { useKibana } from '../../../common/lib/kibana'; export const DetectionEngineUserUnauthenticated = React.memo(() => { const docLinks = useKibana().services.docLinks; - + const actions = useMemo( + () => ({ + detectionUnauthenticated: { + icon: 'documents', + label: i18n.GO_TO_DOCUMENTATION, + url: `${docLinks.ELASTIC_WEBSITE_URL}guide/en/security/${docLinks.DOC_LINK_VERSION}/detection-engine-overview.html#detections-permissions`, + target: '_blank', + }, + }), + [docLinks] + ); return ( ({ license: 'Elastic License', name: 'Query with rule-id', description: '24/7', - severity: { value: 'low', mapping: [] }, - riskScore: { value: 21, mapping: [] }, + riskScore: { value: 21, mapping: [], isMappingChecked: false }, + severity: { value: 'low', mapping: fillEmptySeverityMappings([]), isMappingChecked: false }, references: ['www.test.co'], falsePositives: ['test'], tags: ['tag1', 'tag2'], diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/rules_table_filters/tags_filter_popover.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/rules_table_filters/tags_filter_popover.tsx index fd75c229d479d..49fe3438664c6 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/rules_table_filters/tags_filter_popover.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/rules_table_filters/tags_filter_popover.tsx @@ -22,6 +22,7 @@ interface TagsFilterPopoverProps { selectedTags: string[]; tags: string[]; onSelectedTagsChanged: Dispatch>; + // eslint-disable-next-line react/no-unused-prop-types isLoading: boolean; // TO DO reimplement? } diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.test.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.test.ts index 745518b90df00..4f2055424ca61 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.test.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.test.ts @@ -4,7 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ +import { List } from '../../../../../../common/detection_engine/schemas/types'; import { NewRule } from '../../../../containers/detection_engine/rules'; +import { + getListMock, + getEndpointListMock, +} from '../../../../../../common/detection_engine/schemas/types/lists.mock'; import { DefineStepRuleJson, ScheduleStepRuleJson, @@ -373,6 +378,51 @@ describe('helpers', () => { expect(result).toEqual(expected); }); + test('returns formatted object with endpoint exceptions_list', () => { + const result: AboutStepRuleJson = formatAboutStepData( + { + ...mockData, + isAssociatedToEndpointList: true, + }, + [] + ); + expect(result.exceptions_list).toEqual([getEndpointListMock()]); + }); + + test('returns formatted object with detections exceptions_list', () => { + const result: AboutStepRuleJson = formatAboutStepData(mockData, [getListMock()]); + expect(result.exceptions_list).toEqual([getListMock()]); + }); + + test('returns formatted object with both exceptions_lists', () => { + const result: AboutStepRuleJson = formatAboutStepData( + { + ...mockData, + isAssociatedToEndpointList: true, + }, + [getListMock()] + ); + expect(result.exceptions_list).toEqual([getEndpointListMock(), getListMock()]); + }); + + test('returns formatted object with pre-existing exceptions lists', () => { + const exceptionsLists: List[] = [getEndpointListMock(), getListMock()]; + const result: AboutStepRuleJson = formatAboutStepData( + { + ...mockData, + isAssociatedToEndpointList: true, + }, + exceptionsLists + ); + expect(result.exceptions_list).toEqual(exceptionsLists); + }); + + test('returns formatted object with pre-existing endpoint exceptions list disabled', () => { + const exceptionsLists: List[] = [getEndpointListMock(), getListMock()]; + const result: AboutStepRuleJson = formatAboutStepData(mockData, exceptionsLists); + expect(result.exceptions_list).toEqual([getListMock()]); + }); + test('returns formatted object with empty falsePositive and references filtered out', () => { const mockStepData = { ...mockData, diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.ts index 38f7836f678f9..434a33ac37722 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.ts @@ -12,8 +12,10 @@ import { NOTIFICATION_THROTTLE_NO_ACTIONS } from '../../../../../../common/const import { transformAlertToRuleAction } from '../../../../../../common/detection_engine/transform_actions'; import { RuleType } from '../../../../../../common/detection_engine/types'; import { isMlRule } from '../../../../../../common/machine_learning/helpers'; +import { isThresholdRule } from '../../../../../../common/detection_engine/utils'; +import { List } from '../../../../../../common/detection_engine/schemas/types'; import { ENDPOINT_LIST_ID } from '../../../../../shared_imports'; -import { NewRule } from '../../../../containers/detection_engine/rules'; +import { NewRule, Rule } from '../../../../containers/detection_engine/rules'; import { AboutStepRule, @@ -56,7 +58,7 @@ export interface RuleFields { } type QueryRuleFields = Omit; type ThresholdRuleFields = Omit; -type MlRuleFields = Omit; +type MlRuleFields = Omit; const isMlFields = ( fields: QueryRuleFields | MlRuleFields | ThresholdRuleFields @@ -68,9 +70,9 @@ const isThresholdFields = ( export const filterRuleFieldsForType = (fields: T, type: RuleType) => { if (isMlRule(type)) { - const { index, queryBar, ...mlRuleFields } = fields; + const { index, queryBar, threshold, ...mlRuleFields } = fields; return mlRuleFields; - } else if (type === 'threshold') { + } else if (isThresholdRule(type)) { const { anomalyThreshold, machineLearningJobId, ...thresholdRuleFields } = fields; return thresholdRuleFields; } else { @@ -146,7 +148,10 @@ export const formatScheduleStepData = (scheduleData: ScheduleStepRule): Schedule }; }; -export const formatAboutStepData = (aboutStepData: AboutStepRule): AboutStepRuleJson => { +export const formatAboutStepData = ( + aboutStepData: AboutStepRule, + exceptionsList?: List[] +): AboutStepRuleJson => { const { author, falsePositives, @@ -162,23 +167,41 @@ export const formatAboutStepData = (aboutStepData: AboutStepRule): AboutStepRule timestampOverride, ...rest } = aboutStepData; + + const detectionExceptionLists = + exceptionsList != null ? exceptionsList.filter((list) => list.type !== 'endpoint') : []; + const resp = { author: author.filter((item) => !isEmpty(item)), ...(isBuildingBlock ? { building_block_type: 'default' } : {}), ...(isAssociatedToEndpointList ? { exceptions_list: [ - { id: ENDPOINT_LIST_ID, namespace_type: 'agnostic', type: 'endpoint' }, + { + id: ENDPOINT_LIST_ID, + list_id: ENDPOINT_LIST_ID, + namespace_type: 'agnostic', + type: 'endpoint', + }, + ...detectionExceptionLists, ] as AboutStepRuleJson['exceptions_list'], } + : exceptionsList != null + ? { + exceptions_list: [...detectionExceptionLists], + } : {}), false_positives: falsePositives.filter((item) => !isEmpty(item)), references: references.filter((item) => !isEmpty(item)), risk_score: riskScore.value, - risk_score_mapping: riskScore.mapping, + risk_score_mapping: riskScore.isMappingChecked + ? riskScore.mapping.filter((m) => m.field != null && m.field !== '') + : [], rule_name_override: ruleNameOverride !== '' ? ruleNameOverride : undefined, severity: severity.value, - severity_mapping: severity.mapping, + severity_mapping: severity.isMappingChecked + ? severity.mapping.filter((m) => m.field != null && m.field !== '' && m.value != null) + : [], threat: threat .filter((singleThreat) => singleThreat.tactic.name !== 'none') .map((singleThreat) => ({ @@ -218,11 +241,12 @@ export const formatRule = ( defineStepData: DefineStepRule, aboutStepData: AboutStepRule, scheduleData: ScheduleStepRule, - actionsData: ActionsStepRule + actionsData: ActionsStepRule, + rule?: Rule | null ): NewRule => deepmerge.all([ formatDefineStepData(defineStepData), - formatAboutStepData(aboutStepData), + formatAboutStepData(aboutStepData, rule?.exceptions_list), formatScheduleStepData(scheduleData), formatActionsStepData(actionsData), ]) as NewRule; diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx index 5832f07134936..789469e981fb4 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx @@ -37,7 +37,7 @@ import { } from '../../../../../common/components/link_to/redirect_to_detection_engine'; import { SiemSearchBar } from '../../../../../common/components/search_bar'; import { WrapperPage } from '../../../../../common/components/wrapper_page'; -import { useRule, Rule } from '../../../../containers/detection_engine/rules'; +import { Rule } from '../../../../containers/detection_engine/rules'; import { useListsConfig } from '../../../../containers/detection_engine/lists/use_lists_config'; import { useWithSource } from '../../../../../common/containers/source'; @@ -84,7 +84,7 @@ import { ExceptionsViewer } from '../../../../../common/components/exceptions/vi import { DEFAULT_INDEX_PATTERN, FILTERS_GLOBAL_HEIGHT } from '../../../../../../common/constants'; import { useFullScreen } from '../../../../../common/containers/use_full_screen'; import { Display } from '../../../../../hosts/pages/display'; -import { ExceptionListTypeEnum, ExceptionIdentifiers } from '../../../../../lists_plugin_deps'; +import { ExceptionListTypeEnum, ExceptionIdentifiers } from '../../../../../shared_imports'; import { getEventsViewerBodyHeight, MIN_EVENTS_VIEWER_BODY_HEIGHT, @@ -92,6 +92,7 @@ import { import { footerHeight } from '../../../../../timelines/components/timeline/footer'; import { isMlRule } from '../../../../../../common/machine_learning/helpers'; import { isThresholdRule } from '../../../../../../common/detection_engine/utils'; +import { useRuleAsync } from '../../../../containers/detection_engine/rules/use_rule_async'; import { showGlobalFilters } from '../../../../../timelines/components/timeline/helpers'; import { timelineSelectors } from '../../../../../timelines/store/timeline'; import { timelineDefaults } from '../../../../../timelines/store/timeline/defaults'; @@ -146,7 +147,9 @@ export const RuleDetailsPageComponent: FC = ({ } = useListsConfig(); const loading = userInfoLoading || listsConfigLoading; const { detailName: ruleId } = useParams(); - const [isLoading, rule] = useRule(ruleId); + const { rule: maybeRule, refresh: refreshRule, loading: ruleLoading } = useRuleAsync(ruleId); + const [rule, setRule] = useState(null); + const isLoading = ruleLoading && rule == null; // This is used to re-trigger api rule status when user de/activate rule const [ruleEnabled, setRuleEnabled] = useState(null); const [ruleDetailTab, setRuleDetailTab] = useState(RuleDetailTabs.alerts); @@ -172,10 +175,17 @@ export const RuleDetailsPageComponent: FC = ({ mlCapabilities.isPlatinumOrTrialLicense && hasMlAdminPermissions(mlCapabilities); const ruleDetailTabs = getRuleDetailsTabs(rule); - const title = isLoading === true || rule === null ? : rule.name; + // persist rule until refresh is complete + useEffect(() => { + if (maybeRule != null) { + setRule(maybeRule); + } + }, [maybeRule]); + + const title = rule?.name ?? ; const subTitle = useMemo( () => - isLoading === true || rule === null ? ( + rule == null ? ( ) : ( [ @@ -211,7 +221,7 @@ export const RuleDetailsPageComponent: FC = ({ ), ] ), - [isLoading, rule] + [rule] ); // Set showBuildingBlockAlerts if rule is a Building Block Rule otherwise we won't show alerts @@ -318,13 +328,13 @@ export const RuleDetailsPageComponent: FC = ({ lists: ExceptionIdentifiers[]; allowedExceptionListTypes: ExceptionListTypeEnum[]; }>( - (acc, { id, namespace_type, type }) => { + (acc, { id, list_id, namespace_type, type }) => { const { allowedExceptionListTypes, lists } = acc; const shouldAddEndpoint = type === ExceptionListTypeEnum.ENDPOINT && !allowedExceptionListTypes.includes(ExceptionListTypeEnum.ENDPOINT); return { - lists: [...lists, { id, namespaceType: namespace_type, type }], + lists: [...lists, { id, listId: list_id, namespaceType: namespace_type, type }], allowedExceptionListTypes: shouldAddEndpoint ? [...allowedExceptionListTypes, ExceptionListTypeEnum.ENDPOINT] : allowedExceptionListTypes, @@ -356,7 +366,10 @@ export const RuleDetailsPageComponent: FC = ({ {indicesExist ? ( - + @@ -524,6 +537,7 @@ export const RuleDetailsPageComponent: FC = ({ availableListTypes={exceptionLists.allowedExceptionListTypes} commentsAccordionId={'ruleDetailsTabExceptions'} exceptionListsMeta={exceptionLists.lists} + onRuleChange={refreshRule} /> )} {ruleDetailTab === RuleDetailTabs.failures && } diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.tsx index 0900cdb8f4789..3cc874b85ecf3 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.tsx @@ -273,7 +273,8 @@ const EditRulePageComponent: FC = () => { : myScheduleRuleForm.data) as ScheduleStepRule, (activeFormId === RuleStep.ruleActions ? activeForm.data - : myActionsRuleForm.data) as ActionsStepRule + : myActionsRuleForm.data) as ActionsStepRule, + rule ), ...(ruleId ? { id: ruleId } : {}), }); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.test.tsx index c01317e4f48c5..10a20807d6f87 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.test.tsx @@ -13,8 +13,11 @@ import { getActionsStepsData, getHumanizedDuration, getModifiedAboutDetailsData, + getPrePackagedRuleStatus, + getPrePackagedTimelineStatus, determineDetailsValue, userHasNoPermissions, + fillEmptySeverityMappings, } from './helpers'; import { mockRuleWithEverything, mockRule } from './all/__mocks__/mock'; import { esFilters } from '../../../../../../../../src/plugins/data/public'; @@ -95,9 +98,9 @@ describe('rule helpers', () => { name: 'Query with rule-id', note: '# this is some markdown documentation', references: ['www.test.co'], - riskScore: { value: 21, mapping: [] }, + riskScore: { value: 21, mapping: [], isMappingChecked: false }, ruleNameOverride: 'message', - severity: { value: 'low', mapping: [] }, + severity: { value: 'low', mapping: fillEmptySeverityMappings([]), isMappingChecked: false }, tags: ['tag1', 'tag2'], threat: [ { @@ -394,4 +397,138 @@ describe('rule helpers', () => { expect(result).toEqual(userHasNoPermissionsExpectedResult); }); }); + + describe('getPrePackagedRuleStatus', () => { + test('ruleNotInstalled', () => { + const rulesInstalled = 0; + const rulesNotInstalled = 1; + const rulesNotUpdated = 0; + const result: string = getPrePackagedRuleStatus( + rulesInstalled, + rulesNotInstalled, + rulesNotUpdated + ); + + expect(result).toEqual('ruleNotInstalled'); + }); + + test('ruleInstalled', () => { + const rulesInstalled = 1; + const rulesNotInstalled = 0; + const rulesNotUpdated = 0; + const result: string = getPrePackagedRuleStatus( + rulesInstalled, + rulesNotInstalled, + rulesNotUpdated + ); + + expect(result).toEqual('ruleInstalled'); + }); + + test('someRuleUninstall', () => { + const rulesInstalled = 1; + const rulesNotInstalled = 1; + const rulesNotUpdated = 0; + const result: string = getPrePackagedRuleStatus( + rulesInstalled, + rulesNotInstalled, + rulesNotUpdated + ); + + expect(result).toEqual('someRuleUninstall'); + }); + + test('ruleNeedUpdate', () => { + const rulesInstalled = 1; + const rulesNotInstalled = 0; + const rulesNotUpdated = 1; + const result: string = getPrePackagedRuleStatus( + rulesInstalled, + rulesNotInstalled, + rulesNotUpdated + ); + + expect(result).toEqual('ruleNeedUpdate'); + }); + + test('unknown', () => { + const rulesInstalled = null; + const rulesNotInstalled = null; + const rulesNotUpdated = null; + const result: string = getPrePackagedRuleStatus( + rulesInstalled, + rulesNotInstalled, + rulesNotUpdated + ); + + expect(result).toEqual('unknown'); + }); + }); + + describe('getPrePackagedTimelineStatus', () => { + test('timelinesNotInstalled', () => { + const timelinesInstalled = 0; + const timelinesNotInstalled = 1; + const timelinesNotUpdated = 0; + const result: string = getPrePackagedTimelineStatus( + timelinesInstalled, + timelinesNotInstalled, + timelinesNotUpdated + ); + + expect(result).toEqual('timelinesNotInstalled'); + }); + + test('timelinesInstalled', () => { + const timelinesInstalled = 1; + const timelinesNotInstalled = 0; + const timelinesNotUpdated = 0; + const result: string = getPrePackagedTimelineStatus( + timelinesInstalled, + timelinesNotInstalled, + timelinesNotUpdated + ); + + expect(result).toEqual('timelinesInstalled'); + }); + + test('someTimelineUninstall', () => { + const timelinesInstalled = 1; + const timelinesNotInstalled = 1; + const timelinesNotUpdated = 0; + const result: string = getPrePackagedTimelineStatus( + timelinesInstalled, + timelinesNotInstalled, + timelinesNotUpdated + ); + + expect(result).toEqual('someTimelineUninstall'); + }); + + test('timelineNeedUpdate', () => { + const timelinesInstalled = 1; + const timelinesNotInstalled = 0; + const timelinesNotUpdated = 1; + const result: string = getPrePackagedTimelineStatus( + timelinesInstalled, + timelinesNotInstalled, + timelinesNotUpdated + ); + + expect(result).toEqual('timelineNeedUpdate'); + }); + + test('unknown', () => { + const timelinesInstalled = null; + const timelinesNotInstalled = null; + const timelinesNotUpdated = null; + const result: string = getPrePackagedTimelineStatus( + timelinesInstalled, + timelinesNotInstalled, + timelinesNotUpdated + ); + + expect(result).toEqual('unknown'); + }); + }); }); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.tsx index 11b779e71b9b2..f9279ce639534 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.tsx @@ -9,6 +9,7 @@ import moment from 'moment'; import memoizeOne from 'memoize-one'; import { useLocation } from 'react-router-dom'; +import { ActionVariable } from '../../../../../../triggers_actions_ui/public'; import { RuleAlertAction, RuleType } from '../../../../../common/detection_engine/types'; import { isMlRule } from '../../../../../common/machine_learning/helpers'; import { transformRuleToAlertAction } from '../../../../../common/detection_engine/transform_actions'; @@ -23,6 +24,8 @@ import { ScheduleStepRule, ActionsStepRule, } from './types'; +import { SeverityMapping } from '../../../../../common/detection_engine/schemas/common/schemas'; +import { severityOptions } from '../../../components/rules/step_about_rule/data'; export interface GetStepsData { aboutRuleData: AboutStepRule; @@ -149,18 +152,38 @@ export const getAboutStepsData = (rule: Rule, detailsView: boolean): AboutStepRu references, severity: { value: severity, - mapping: severityMapping, + mapping: fillEmptySeverityMappings(severityMapping), + isMappingChecked: severityMapping.length > 0, }, tags, riskScore: { value: riskScore, mapping: riskScoreMapping, + isMappingChecked: riskScoreMapping.length > 0, }, falsePositives, threat: threat as IMitreEnterpriseAttack[], }; }; +const severitySortMapping = { + low: 0, + medium: 1, + high: 2, + critical: 3, +}; + +export const fillEmptySeverityMappings = (mappings: SeverityMapping): SeverityMapping => { + const missingMappings: SeverityMapping = severityOptions.flatMap((so) => + mappings.find((mapping) => mapping.severity === so.value) == null + ? [{ field: '', value: '', operator: 'equals', severity: so.value }] + : [] + ); + return [...mappings, ...missingMappings].sort( + (a, b) => severitySortMapping[a.severity] - severitySortMapping[b.severity] + ); +}; + export const determineDetailsValue = ( rule: Rule, detailsView: boolean @@ -326,18 +349,23 @@ export const getActionMessageRuleParams = (ruleType: RuleType): string[] => { return ruleParamsKeys; }; -export const getActionMessageParams = memoizeOne((ruleType: RuleType | undefined): string[] => { - if (!ruleType) { - return []; +export const getActionMessageParams = memoizeOne( + (ruleType: RuleType | undefined): ActionVariable[] => { + if (!ruleType) { + return []; + } + const actionMessageRuleParams = getActionMessageRuleParams(ruleType); + + return [ + { name: 'state.signals_count', description: 'state.signals_count' }, + { name: '{context.results_link}', description: 'context.results_link' }, + ...actionMessageRuleParams.map((param) => { + const extendedParam = `context.rule.${param}`; + return { name: extendedParam, description: extendedParam }; + }), + ]; } - const actionMessageRuleParams = getActionMessageRuleParams(ruleType); - - return [ - 'state.signals_count', - '{context.results_link}', - ...actionMessageRuleParams.map((param) => `context.rule.${param}`), - ]; -}); +); // typed as null not undefined as the initial state for this value is null. export const userHasNoPermissions = (canUserCRUD: boolean | null): boolean => diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.tsx index c1d8436a7230e..b6f58ef7045f8 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiButton, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { EuiButton, EuiFlexGroup, EuiFlexItem, EuiToolTip } from '@elastic/eui'; import React, { useCallback, useRef, useState } from 'react'; import { useHistory } from 'react-router-dom'; @@ -204,13 +204,16 @@ const RulesPageComponent: React.FC = () => {
)} - - {i18n.UPLOAD_VALUE_LISTS} - + + + {i18n.UPLOAD_VALUE_LISTS} + + { [], getUrlForAppMock ) - ).toEqual([{ href: 'securitySolution:detections', text: 'Detection alerts' }]); + ).toEqual([{ href: 'securitySolution:detections', text: 'Detections' }]); }); }); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/utils.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/utils.ts index 75d1df9406d25..c1b4fa3e2b7d9 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/utils.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/utils.ts @@ -57,7 +57,7 @@ export const getBreadcrumbs = ( ): ChromeBreadcrumb[] => { let breadcrumb = [ { - text: i18nDetections.PAGE_TITLE, + text: i18nDetections.BREADCRUMB_TITLE, href: getUrlForApp(`${APP_ID}:${SecurityPageName.detections}`, { path: !isEmpty(search[0]) ? search[0] : '', }), diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/translations.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/translations.ts index 92dc02ac8478c..dd86d9fd2dfc6 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/translations.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/translations.ts @@ -6,6 +6,13 @@ import { i18n } from '@kbn/i18n'; +export const BREADCRUMB_TITLE = i18n.translate( + 'xpack.securitySolution.detectionEngine.detectionsBreadcrumbTitle', + { + defaultMessage: 'Detections', + } +); + export const PAGE_TITLE = i18n.translate( 'xpack.securitySolution.detectionEngine.detectionsPageTitle', { @@ -51,8 +58,8 @@ export const EMPTY_TITLE = i18n.translate('xpack.securitySolution.detectionEngin 'It looks like you don’t have any indices relevant to the detection engine in the Security application', }); -export const EMPTY_ACTION_PRIMARY = i18n.translate( - 'xpack.securitySolution.detectionEngine.emptyActionPrimary', +export const EMPTY_ACTION_BEATS = i18n.translate( + 'xpack.securitySolution.detectionEngine.emptyActionBeats', { defaultMessage: 'View setup instructions', } @@ -72,14 +79,34 @@ export const NO_INDEX_TITLE = i18n.translate( } ); -export const NO_INDEX_MSG_BODY = i18n.translate( - 'xpack.securitySolution.detectionEngine.noIndexMsgBody', +export const NEEDS_SIGNALS_AND_LISTS_INDEXES = i18n.translate( + 'xpack.securitySolution.detectionEngine.needsSignalsAndListsIndexesMessage', { - defaultMessage: - 'To use the detection engine, a user with the required cluster and index privileges must first access this page. For more help, contact your administrator.', + defaultMessage: 'You need permissions for the signals and lists indices.', + } +); + +export const NEEDS_SIGNALS_INDEX = i18n.translate( + 'xpack.securitySolution.detectionEngine.needsSignalsIndexMessage', + { + defaultMessage: 'You need permissions for the signals index.', + } +); + +export const NEEDS_LISTS_INDEXES = i18n.translate( + 'xpack.securitySolution.detectionEngine.needsListsIndexesMessage', + { + defaultMessage: 'You need permissions for the lists indices.', } ); +export const NEEDS_INDEX_PERMISSIONS = (additionalContext: string) => + i18n.translate('xpack.securitySolution.detectionEngine.needsIndexPermissionsMessage', { + values: { additionalContext }, + defaultMessage: + 'To use the detection engine, a user with the required cluster and index privileges must first access this page. {additionalContext} For more help, contact your Elastic Stack administrator.', + }); + export const GO_TO_DOCUMENTATION = i18n.translate( 'xpack.securitySolution.detectionEngine.goToDocumentationButton', { diff --git a/x-pack/plugins/security_solution/public/hosts/pages/details/index.tsx b/x-pack/plugins/security_solution/public/hosts/pages/details/index.tsx index 781aa711ff0d9..b6c1727ee6afa 100644 --- a/x-pack/plugins/security_solution/public/hosts/pages/details/index.tsx +++ b/x-pack/plugins/security_solution/public/hosts/pages/details/index.tsx @@ -104,7 +104,10 @@ const HostDetailsComponent = React.memo( {indicesExist ? ( - + diff --git a/x-pack/plugins/security_solution/public/hosts/pages/hosts.tsx b/x-pack/plugins/security_solution/public/hosts/pages/hosts.tsx index 1219effa5ff6d..1d0b73f80a69a 100644 --- a/x-pack/plugins/security_solution/public/hosts/pages/hosts.tsx +++ b/x-pack/plugins/security_solution/public/hosts/pages/hosts.tsx @@ -98,7 +98,10 @@ export const HostsComponent = React.memo( {indicesExist ? ( - + diff --git a/x-pack/plugins/security_solution/public/management/components/management_empty_state.tsx b/x-pack/plugins/security_solution/public/management/components/management_empty_state.tsx index fb9f97f3f7570..a4518d1a1f493 100644 --- a/x-pack/plugins/security_solution/public/management/components/management_empty_state.tsx +++ b/x-pack/plugins/security_solution/public/management/components/management_empty_state.tsx @@ -77,57 +77,6 @@ const PolicyEmptyState = React.memo<{ /> - - - - - - - - -

- -

-
-
-
- - - - -
- - - - - - - -

- -

-
-
-
- - - - -
-
- [ { title: i18n.translate('xpack.securitySolution.endpoint.hostList.stepOneTitle', { - defaultMessage: 'Select the policy you want to use to protect your hosts', + defaultMessage: 'Select the integration you want to use', }), children: ( <> @@ -203,7 +152,7 @@ const HostsEmptyState = React.memo<{ ) : selectionOptions.length ? ( @@ -211,7 +160,7 @@ const HostsEmptyState = React.memo<{ ) : ( ); }} @@ -263,13 +212,13 @@ const HostsEmptyState = React.memo<{ headerComponent={ } bodyComponent={ } /> diff --git a/x-pack/plugins/security_solution/public/management/components/management_page_view.tsx b/x-pack/plugins/security_solution/public/management/components/management_page_view.tsx index 42341b524362d..aa562b9a20201 100644 --- a/x-pack/plugins/security_solution/public/management/components/management_page_view.tsx +++ b/x-pack/plugins/security_solution/public/management/components/management_page_view.tsx @@ -4,52 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { memo, useMemo } from 'react'; -import { i18n } from '@kbn/i18n'; -import { useParams } from 'react-router-dom'; +import React, { memo } from 'react'; import { PageView, PageViewProps } from '../../common/components/endpoint/page_view'; -import { AdministrationSubTab } from '../types'; -import { SecurityPageName } from '../../app/types'; -import { useFormatUrl } from '../../common/components/link_to'; -import { getHostListPath, getPoliciesPath } from '../common/routing'; -import { useNavigateByRouterEventHandler } from '../../common/hooks/endpoint/use_navigate_by_router_event_handler'; export const ManagementPageView = memo>((options) => { - const { formatUrl, search } = useFormatUrl(SecurityPageName.administration); - const { tabName } = useParams<{ tabName: AdministrationSubTab }>(); - - const goToEndpoint = useNavigateByRouterEventHandler( - getHostListPath({ name: 'hostList' }, search) - ); - - const goToPolicies = useNavigateByRouterEventHandler(getPoliciesPath(search)); - - const tabs = useMemo((): PageViewProps['tabs'] | undefined => { - if (options.viewType === 'details') { - return undefined; - } - return [ - { - name: i18n.translate('xpack.securitySolution.managementTabs.hosts', { - defaultMessage: 'Hosts', - }), - id: AdministrationSubTab.hosts, - isSelected: tabName === AdministrationSubTab.hosts, - href: formatUrl(getHostListPath({ name: 'hostList' })), - onClick: goToEndpoint, - }, - { - name: i18n.translate('xpack.securitySolution.managementTabs.policies', { - defaultMessage: 'Policies', - }), - id: AdministrationSubTab.policies, - isSelected: tabName === AdministrationSubTab.policies, - href: formatUrl(getPoliciesPath()), - onClick: goToPolicies, - }, - ]; - }, [formatUrl, goToEndpoint, goToPolicies, options.viewType, tabName]); - return ; + return ; }); ManagementPageView.displayName = 'ManagementPageView'; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/action.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/action.ts index 4c01b3644cf63..621fab2e4ee11 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/action.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/action.ts @@ -12,6 +12,7 @@ import { import { ServerApiError } from '../../../../common/types'; import { GetPolicyListResponse } from '../../policy/types'; import { GetPackagesResponse } from '../../../../../../ingest_manager/common'; +import { HostState } from '../types'; interface ServerReturnedHostList { type: 'serverReturnedHostList'; @@ -75,6 +76,11 @@ interface ServerReturnedEndpointPackageInfo { payload: GetPackagesResponse['response'][0]; } +interface ServerReturnedHostNonExistingPolicies { + type: 'serverReturnedHostNonExistingPolicies'; + payload: HostState['nonExistingPolicies']; +} + export type HostAction = | ServerReturnedHostList | ServerFailedToReturnHostList @@ -87,4 +93,5 @@ export type HostAction = | UserSelectedEndpointPolicy | ServerCancelledHostListLoading | ServerCancelledPolicyItemsLoading - | ServerReturnedEndpointPackageInfo; + | ServerReturnedEndpointPackageInfo + | ServerReturnedHostNonExistingPolicies; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/index.test.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/index.test.ts index f2c205661b32c..b6e18506b6111 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/index.test.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/index.test.ts @@ -50,6 +50,7 @@ describe('HostList store concerns', () => { selectedPolicyId: undefined, policyItemsLoading: false, endpointPackageInfo: undefined, + nonExistingPolicies: {}, }); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.ts index 12fa3dc47beac..edeca5659ee38 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { HostResultList } from '../../../../../common/endpoint/types'; +import { HttpSetup } from 'kibana/public'; +import { HostInfo, HostResultList } from '../../../../../common/endpoint/types'; import { GetPolicyListResponse } from '../../policy/types'; import { ImmutableMiddlewareFactory } from '../../../../common/store'; import { @@ -13,12 +14,15 @@ import { uiQueryParams, listData, endpointPackageInfo, + nonExistingPolicies, } from './selectors'; import { HostState } from '../types'; import { sendGetEndpointSpecificPackageConfigs, sendGetEndpointSecurityPackage, + sendGetAgentConfigList, } from '../../policy/store/policy_list/services/ingest'; +import { AGENT_CONFIG_SAVED_OBJECT_TYPE } from '../../../../../../ingest_manager/common'; export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (coreStart) => { return ({ getState, dispatch }) => (next) => async (action) => { @@ -58,6 +62,23 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor type: 'serverReturnedHostList', payload: hostResponse, }); + + getNonExistingPoliciesForHostsList( + coreStart.http, + hostResponse.hosts, + nonExistingPolicies(state) + ) + .then((missingPolicies) => { + if (missingPolicies !== undefined) { + dispatch({ + type: 'serverReturnedHostNonExistingPolicies', + payload: missingPolicies, + }); + } + }) + // Ignore Errors, since this should not hinder the user's ability to use the UI + // eslint-disable-next-line no-console + .catch((error) => console.error(error)); } catch (error) { dispatch({ type: 'serverFailedToReturnHostList', @@ -117,6 +138,23 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor type: 'serverReturnedHostList', payload: response, }); + + getNonExistingPoliciesForHostsList( + coreStart.http, + response.hosts, + nonExistingPolicies(state) + ) + .then((missingPolicies) => { + if (missingPolicies !== undefined) { + dispatch({ + type: 'serverReturnedHostNonExistingPolicies', + payload: missingPolicies, + }); + } + }) + // Ignore Errors, since this should not hinder the user's ability to use the UI + // eslint-disable-next-line no-console + .catch((error) => console.error(error)); } catch (error) { dispatch({ type: 'serverFailedToReturnHostList', @@ -133,11 +171,25 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor // call the host details api const { selected_host: selectedHost } = uiQueryParams(state); try { - const response = await coreStart.http.get(`/api/endpoint/metadata/${selectedHost}`); + const response = await coreStart.http.get( + `/api/endpoint/metadata/${selectedHost}` + ); dispatch({ type: 'serverReturnedHostDetails', payload: response, }); + getNonExistingPoliciesForHostsList(coreStart.http, [response], nonExistingPolicies(state)) + .then((missingPolicies) => { + if (missingPolicies !== undefined) { + dispatch({ + type: 'serverReturnedHostNonExistingPolicies', + payload: missingPolicies, + }); + } + }) + // Ignore Errors, since this should not hinder the user's ability to use the UI + // eslint-disable-next-line no-console + .catch((error) => console.error(error)); } catch (error) { dispatch({ type: 'serverFailedToReturnHostDetails', @@ -163,3 +215,62 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor } }; }; + +const getNonExistingPoliciesForHostsList = async ( + http: HttpSetup, + hosts: HostResultList['hosts'], + currentNonExistingPolicies: HostState['nonExistingPolicies'] +): Promise => { + if (hosts.length === 0) { + return; + } + + // Create an array of unique policy IDs that are not yet known to be non-existing. + const policyIdsToCheck = Array.from( + new Set( + hosts + .filter((host) => !currentNonExistingPolicies[host.metadata.Endpoint.policy.applied.id]) + .map((host) => host.metadata.Endpoint.policy.applied.id) + ) + ); + + if (policyIdsToCheck.length === 0) { + return; + } + + // We use the Agent Config API here, instead of the Package Config, because we can't use + // filter by ID of the Saved Object. Agent Config, however, keeps a reference (array) of + // Package Ids that it uses, thus if a reference exists there, then the package config (policy) + // exists. + const policiesFound = ( + await sendGetAgentConfigList(http, { + query: { + kuery: `${AGENT_CONFIG_SAVED_OBJECT_TYPE}.package_configs: (${policyIdsToCheck.join( + ' or ' + )})`, + }, + }) + ).items.reduce((list, agentConfig) => { + (agentConfig.package_configs as string[]).forEach((packageConfig) => { + list[packageConfig as string] = true; + }); + return list; + }, {}); + + const nonExisting = policyIdsToCheck.reduce( + (list, policyId) => { + if (policiesFound[policyId]) { + return list; + } + list[policyId] = true; + return list; + }, + {} + ); + + if (Object.keys(nonExisting).length === 0) { + return; + } + + return nonExisting; +}; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/reducer.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/reducer.ts index 993267cf1a704..7f68baa4b85bd 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/reducer.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/reducer.ts @@ -28,6 +28,7 @@ export const initialHostListState: Immutable = { selectedPolicyId: undefined, policyItemsLoading: false, endpointPackageInfo: undefined, + nonExistingPolicies: {}, }; /* eslint-disable-next-line complexity */ @@ -57,6 +58,14 @@ export const hostListReducer: ImmutableReducer = ( error: action.payload, loading: false, }; + } else if (action.type === 'serverReturnedHostNonExistingPolicies') { + return { + ...state, + nonExistingPolicies: { + ...state.nonExistingPolicies, + ...action.payload, + }, + }; } else if (action.type === 'serverReturnedHostDetails') { return { ...state, diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/selectors.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/selectors.ts index 4f47eaf565d8c..6e0823a920413 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/selectors.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/selectors.ts @@ -195,3 +195,11 @@ export const policyResponseStatus: (state: Immutable) => string = cre return (policyResponse && policyResponse?.Endpoint?.policy?.applied?.status) || ''; } ); + +/** + * returns the list of known non-existing polices that may have been in the Host API response. + * @param state + */ +export const nonExistingPolicies: ( + state: Immutable +) => Immutable = (state) => state.nonExistingPolicies; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/types.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/types.ts index a5f37a0b49e8f..582a59cfd7605 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/types.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/types.ts @@ -50,6 +50,8 @@ export interface HostState { selectedPolicyId?: string; /** Endpoint package info */ endpointPackageInfo?: GetPackagesResponse['response'][0]; + /** tracks the list of policies IDs used in Host metadata that may no longer exist */ + nonExistingPolicies: Record; } /** diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/host_policy_link.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/host_policy_link.tsx new file mode 100644 index 0000000000000..ec4d7e87b721d --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/host_policy_link.tsx @@ -0,0 +1,53 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { memo, useMemo } from 'react'; +import { EuiLink, EuiLinkAnchorProps } from '@elastic/eui'; +import { useHostSelector } from '../hooks'; +import { nonExistingPolicies } from '../../store/selectors'; +import { getPolicyDetailPath } from '../../../../common/routing'; +import { useFormatUrl } from '../../../../../common/components/link_to'; +import { SecurityPageName } from '../../../../../../common/constants'; +import { useNavigateByRouterEventHandler } from '../../../../../common/hooks/endpoint/use_navigate_by_router_event_handler'; + +/** + * A policy link (to details) that first checks to see if the policy id exists against + * the `nonExistingPolicies` value in the store. If it does not exist, then regular + * text is returned. + */ +export const HostPolicyLink = memo< + Omit & { + policyId: string; + } +>(({ policyId, children, onClick, ...otherProps }) => { + const missingPolicies = useHostSelector(nonExistingPolicies); + const { formatUrl } = useFormatUrl(SecurityPageName.administration); + const { toRoutePath, toRouteUrl } = useMemo(() => { + const toPath = getPolicyDetailPath(policyId); + return { + toRoutePath: toPath, + toRouteUrl: formatUrl(toPath), + }; + }, [formatUrl, policyId]); + const clickHandler = useNavigateByRouterEventHandler(toRoutePath, onClick); + + if (missingPolicies[policyId]) { + return ( + + {children} + + ); + } + + return ( + // eslint-disable-next-line @elastic/eui/href-or-on-click + + {children} + + ); +}); + +HostPolicyLink.displayName = 'HostPolicyLink'; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/host_details.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/host_details.tsx index 62efa621e6e3b..109392cb7a929 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/host_details.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/host_details.tsx @@ -26,10 +26,11 @@ import { POLICY_STATUS_TO_HEALTH_COLOR } from '../host_constants'; import { FormattedDateAndTime } from '../../../../../common/components/endpoint/formatted_date_time'; import { useNavigateByRouterEventHandler } from '../../../../../common/hooks/endpoint/use_navigate_by_router_event_handler'; import { LinkToApp } from '../../../../../common/components/endpoint/link_to_app'; -import { getHostDetailsPath, getPolicyDetailPath } from '../../../../common/routing'; +import { getHostDetailsPath } from '../../../../common/routing'; import { SecurityPageName } from '../../../../../app/types'; import { useFormatUrl } from '../../../../../common/components/link_to'; import { AgentDetailsReassignConfigAction } from '../../../../../../../ingest_manager/public'; +import { HostPolicyLink } from '../components/host_policy_link'; const HostIds = styled(EuiListGroupItem)` margin-top: 0; @@ -116,37 +117,26 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { const policyStatusClickHandler = useNavigateByRouterEventHandler(policyResponseRoutePath); - const [policyDetailsRoutePath, policyDetailsRouteUrl] = useMemo(() => { - return [ - getPolicyDetailPath(details.Endpoint.policy.applied.id), - formatUrl(getPolicyDetailPath(details.Endpoint.policy.applied.id)), - ]; - }, [details.Endpoint.policy.applied.id, formatUrl]); - - const policyDetailsClickHandler = useNavigateByRouterEventHandler(policyDetailsRoutePath); - const detailsResultsPolicy = useMemo(() => { return [ { title: i18n.translate('xpack.securitySolution.endpoint.host.details.policy', { - defaultMessage: 'Policy', + defaultMessage: 'Integration', }), description: ( <> - {/* eslint-disable-next-line @elastic/eui/href-or-on-click */} - {details.Endpoint.policy.applied.name} - + ), }, { title: i18n.translate('xpack.securitySolution.endpoint.host.details.policyStatus', { - defaultMessage: 'Policy Status', + defaultMessage: 'Configuration response', }), description: ( { ), }, ]; - }, [ - details, - policyResponseUri, - policyStatus, - policyStatusClickHandler, - policyDetailsRouteUrl, - policyDetailsClickHandler, - ]); + }, [details, policyResponseUri, policyStatus, policyStatusClickHandler]); const detailsResultsLower = useMemo(() => { return [ { @@ -233,7 +216,7 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/index.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/index.tsx index 71b3885308558..212c8977a8852 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/index.tsx @@ -158,7 +158,7 @@ const PolicyResponseFlyoutPanel = memo<{

@@ -167,7 +167,7 @@ const PolicyResponseFlyoutPanel = memo<{ title={ } /> diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx index 47227244b7066..9d49c8705affe 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx @@ -431,7 +431,7 @@ describe('when on the hosts page', () => { const renderResult = render(); const linkToReassign = await renderResult.findByTestId('hostDetailsLinkToIngest'); expect(linkToReassign).not.toBeNull(); - expect(linkToReassign.textContent).toEqual('Reassign Policy'); + expect(linkToReassign.textContent).toEqual('Reassign Configuration'); expect(linkToReassign.getAttribute('href')).toEqual( `/app/ingestManager#/fleet/agents/${agentId}/activity?openReassignFlyout=true` ); @@ -492,7 +492,7 @@ describe('when on the hosts page', () => { it('should include the sub-panel title', async () => { expect( (await renderResult.findByTestId('hostDetailsPolicyResponseFlyoutTitle')).textContent - ).toBe('Policy Response'); + ).toBe('Configuration Response'); }); it('should show a configuration section for each protection', async () => { diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx index c5ed71cba46d9..2692f7791b7c0 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx @@ -46,9 +46,10 @@ import { AgentConfigDetailsDeployAgentAction, } from '../../../../../../ingest_manager/public'; import { SecurityPageName } from '../../../../app/types'; -import { getHostListPath, getHostDetailsPath, getPolicyDetailPath } from '../../../common/routing'; +import { getHostListPath, getHostDetailsPath } from '../../../common/routing'; import { useFormatUrl } from '../../../../common/components/link_to'; import { HostAction } from '../store/action'; +import { HostPolicyLink } from './components/host_policy_link'; const HostListNavLink = memo<{ name: string; @@ -236,27 +237,26 @@ export const HostList = () => { { field: 'metadata.Endpoint.policy.applied', name: i18n.translate('xpack.securitySolution.endpointList.policy', { - defaultMessage: 'Policy', + defaultMessage: 'Integration', }), truncateText: true, // eslint-disable-next-line react/display-name render: (policy: HostInfo['metadata']['Endpoint']['policy']['applied']) => { - const toRoutePath = getPolicyDetailPath(policy.id); - const toRouteUrl = formatUrl(toRoutePath); return ( - + + {policy.name} + ); }, }, { field: 'metadata.Endpoint.policy.applied', name: i18n.translate('xpack.securitySolution.endpointList.policyStatus', { - defaultMessage: 'Policy Status', + defaultMessage: 'Configuration Status', }), // eslint-disable-next-line react/display-name render: (policy: HostInfo['metadata']['Endpoint']['policy']['applied'], item: HostInfo) => { diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/index.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/index.tsx index 5122bbcd5d55d..681f1f1430926 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/index.tsx @@ -6,17 +6,13 @@ import React, { memo } from 'react'; import { Route, Switch } from 'react-router-dom'; -import { PolicyDetails, PolicyList } from './view'; -import { - MANAGEMENT_ROUTING_POLICIES_PATH, - MANAGEMENT_ROUTING_POLICY_DETAILS_PATH, -} from '../../common/constants'; +import { PolicyDetails } from './view'; +import { MANAGEMENT_ROUTING_POLICY_DETAILS_PATH } from '../../common/constants'; import { NotFoundPage } from '../../../app/404'; export const PolicyContainer = memo(() => { return ( - diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/services/ingest.ts b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/services/ingest.ts index 48b6bedf50fd8..c6e6146f4d5e4 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/services/ingest.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/services/ingest.ts @@ -12,12 +12,15 @@ import { DeletePackageConfigsRequest, PACKAGE_CONFIG_SAVED_OBJECT_TYPE, GetPackagesResponse, + GetAgentConfigsRequest, + GetAgentConfigsResponse, } from '../../../../../../../../ingest_manager/common'; import { GetPolicyListResponse, GetPolicyResponse, UpdatePolicyResponse } from '../../../types'; import { NewPolicyData } from '../../../../../../../common/endpoint/types'; const INGEST_API_ROOT = `/api/ingest_manager`; export const INGEST_API_PACKAGE_CONFIGS = `${INGEST_API_ROOT}/package_configs`; +const INGEST_API_AGENT_CONFIGS = `${INGEST_API_ROOT}/agent_configs`; const INGEST_API_FLEET = `${INGEST_API_ROOT}/fleet`; const INGEST_API_FLEET_AGENT_STATUS = `${INGEST_API_FLEET}/agent-status`; export const INGEST_API_EPM_PACKAGES = `${INGEST_API_ROOT}/epm/packages`; @@ -75,6 +78,18 @@ export const sendDeletePackageConfig = ( }); }; +/** + * Retrieve a list of Agent Configurations + * @param http + * @param options + */ +export const sendGetAgentConfigList = ( + http: HttpStart, + options: HttpFetchOptions & GetAgentConfigsRequest +) => { + return http.get(INGEST_API_AGENT_CONFIGS, options); +}; + /** * Updates a package config * diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_package_config.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_package_config.tsx index 67f24977406c6..2b08bfd2b282b 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_package_config.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_package_config.tsx @@ -6,8 +6,7 @@ import React, { memo, useMemo } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; -import { EuiCallOut, EuiText, EuiTitle, EuiSpacer } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; +import { EuiCallOut, EuiText, EuiSpacer } from '@elastic/eui'; import { LinkToApp } from '../../../../../common/components/endpoint/link_to_app'; import { CustomConfigurePackageConfigContent, @@ -50,52 +49,37 @@ export const ConfigureEndpointPackageConfig = memo - -

- -

-

{from === 'edit' ? ( - <> - - - - - - + + + + ), + }} + /> ) : ( )}

diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx index 8612b15f89857..6ed4e06ee51c5 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx @@ -10,7 +10,7 @@ import { mount } from 'enzyme'; import { PolicyDetails } from './policy_details'; import { EndpointDocGenerator } from '../../../../../common/endpoint/generate_data'; import { AppContextTestRender, createAppRootMockRenderer } from '../../../../common/mock/endpoint'; -import { getPolicyDetailPath, getPoliciesPath } from '../../../common/routing'; +import { getPolicyDetailPath, getHostListPath } from '../../../common/routing'; import { apiPathMockResponseProviders } from '../store/policy_list/test_mock_utils'; jest.mock('../../../../common/components/link_to'); @@ -19,7 +19,7 @@ describe('Policy Details', () => { type FindReactWrapperResponse = ReturnType['find']>; const policyDetailsPathUrl = getPolicyDetailPath('1'); - const policyListPathUrl = getPoliciesPath(); + const hostListPath = getHostListPath({ name: 'hostList' }); const sleep = (ms = 100) => new Promise((wakeup) => setTimeout(wakeup, ms)); const generator = new EndpointDocGenerator(); let history: AppContextTestRender['history']; @@ -127,8 +127,8 @@ describe('Policy Details', () => { const backToListButton = pageHeaderLeft.find('EuiButtonEmpty'); expect(backToListButton.prop('iconType')).toBe('arrowLeft'); - expect(backToListButton.prop('href')).toBe(policyListPathUrl); - expect(backToListButton.text()).toBe('Back to policy list'); + expect(backToListButton.prop('href')).toBe(hostListPath); + expect(backToListButton.text()).toBe('Back to endpoint hosts'); const pageTitle = pageHeaderLeft.find('[data-test-subj="pageViewHeaderLeftTitle"]'); expect(pageTitle).toHaveLength(1); @@ -141,7 +141,7 @@ describe('Policy Details', () => { ); expect(history.location.pathname).toEqual(policyDetailsPathUrl); backToListButton.simulate('click', { button: 0 }); - expect(history.location.pathname).toEqual(policyListPathUrl); + expect(history.location.pathname).toEqual(hostListPath); }); it('should display agent stats', async () => { await asyncActions; @@ -173,7 +173,7 @@ describe('Policy Details', () => { const navigateToAppMockedCalls = coreStart.application.navigateToApp.mock.calls; expect(navigateToAppMockedCalls[navigateToAppMockedCalls.length - 1]).toEqual([ 'securitySolution:administration', - { path: policyListPathUrl }, + { path: hostListPath }, ]); }); it('should display save button', async () => { @@ -232,7 +232,7 @@ describe('Policy Details', () => { ); expect(warningCallout).toHaveLength(1); expect(warningCallout.text()).toEqual( - 'This action will update 5 hostsSaving these changes will apply the updates to all active endpoints assigned to this policy' + 'This action will update 5 hostsSaving these changes will apply updates to all endpoints assigned to this agent configuration.' ); }); it('should close dialog if cancel button is clicked', () => { diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx index 9576e1aedcaf1..cd63991dbac93 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx @@ -42,7 +42,7 @@ import { PageViewHeaderTitle } from '../../../../common/components/endpoint/page import { ManagementPageView } from '../../../components/management_page_view'; import { SpyRoute } from '../../../../common/utils/route/spy_routes'; import { SecurityPageName } from '../../../../app/types'; -import { getPoliciesPath } from '../../../common/routing'; +import { getHostListPath } from '../../../common/routing'; import { useFormatUrl } from '../../../../common/components/link_to'; import { useNavigateToAppEventHandler } from '../../../../common/hooks/endpoint/use_navigate_to_app_event_handler'; import { MANAGEMENT_APP_ID } from '../../../common/constants'; @@ -56,7 +56,7 @@ export const PolicyDetails = React.memo(() => { application: { navigateToApp }, }, } = useKibana(); - const { formatUrl, search } = useFormatUrl(SecurityPageName.administration); + const { formatUrl } = useFormatUrl(SecurityPageName.administration); const { state: locationRouteState } = useLocation(); // Store values @@ -70,6 +70,7 @@ export const PolicyDetails = React.memo(() => { const [showConfirm, setShowConfirm] = useState(false); const [routeState, setRouteState] = useState(); const policyName = policyItem?.name ?? ''; + const hostListRouterPath = getHostListPath({ name: 'hostList' }); // Handle showing update statuses useEffect(() => { @@ -87,7 +88,7 @@ export const PolicyDetails = React.memo(() => { @@ -109,11 +110,11 @@ export const PolicyDetails = React.memo(() => { } }, [navigateToApp, notifications.toasts, policyName, policyUpdateStatus, routeState]); - const handleBackToListOnClick = useNavigateByRouterEventHandler(getPoliciesPath()); + const handleBackToListOnClick = useNavigateByRouterEventHandler(hostListRouterPath); const navigateToAppArguments = useMemo((): Parameters => { - return routeState?.onCancelNavigateTo ?? [MANAGEMENT_APP_ID, { path: getPoliciesPath() }]; - }, [routeState?.onCancelNavigateTo]); + return routeState?.onCancelNavigateTo ?? [MANAGEMENT_APP_ID, { path: hostListRouterPath }]; + }, [hostListRouterPath, routeState?.onCancelNavigateTo]); const handleCancelOnClick = useNavigateToAppEventHandler(...navigateToAppArguments); const handleSaveOnClick = useCallback(() => { @@ -162,11 +163,11 @@ export const PolicyDetails = React.memo(() => { iconType="arrowLeft" contentProps={{ style: { paddingLeft: '0' } }} onClick={handleBackToListOnClick} - href={formatUrl(getPoliciesPath(search))} + href={formatUrl(hostListRouterPath)} > {policyItem.name} @@ -306,7 +307,7 @@ const ConfirmUpdate = React.memo<{ >
diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/config_form.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/config_form.tsx index 763931bc2d3d7..8e3c4138efb36 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/config_form.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/config_form.tsx @@ -34,17 +34,10 @@ export const ConfigForm: React.FC<{ */ supportedOss: React.ReactNode; children: React.ReactNode; - /** - * A description for the component. - */ - description: string; - /** - * The `data-test-subj` attribute to append to a certain child element. - */ dataTestSubj: string; /** React Node to be put on the right corner of the card */ rightCorner: React.ReactNode; -}> = React.memo(({ type, supportedOss, children, dataTestSubj, rightCorner, description }) => { +}> = React.memo(({ type, supportedOss, children, dataTestSubj, rightCorner }) => { const typeTitle = useMemo(() => { return ( @@ -85,12 +78,7 @@ export const ConfigForm: React.FC<{ return ( - + {children} diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/linux.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/linux.tsx index d7bae0d2e6bad..66126adb7a4e1 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/linux.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/linux.tsx @@ -102,12 +102,6 @@ export const LinuxEvents = React.memo(() => { type={i18n.translate('xpack.securitySolution.endpoint.policy.details.eventCollection', { defaultMessage: 'Event Collection', })} - description={i18n.translate( - 'xpack.securitySolution.endpoint.policy.details.eventCollectionLabel', - { - defaultMessage: 'Event Collection', - } - )} supportedOss={i18n.translate('xpack.securitySolution.endpoint.policy.details.linux', { defaultMessage: 'Linux', })} diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/mac.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/mac.tsx index 37709ff608857..dc70fc0ba0f4f 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/mac.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/mac.tsx @@ -102,12 +102,6 @@ export const MacEvents = React.memo(() => { type={i18n.translate('xpack.securitySolution.endpoint.policy.details.eventCollection', { defaultMessage: 'Event Collection', })} - description={i18n.translate( - 'xpack.securitySolution.endpoint.policy.details.eventCollectionLabel', - { - defaultMessage: 'Event Collection', - } - )} supportedOss={i18n.translate('xpack.securitySolution.endpoint.policy.details.mac', { defaultMessage: 'Mac', })} diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/windows.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/windows.tsx index 3c7ecae0d9b4e..5acdf67922a3a 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/windows.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/windows.tsx @@ -142,9 +142,6 @@ export const WindowsEvents = React.memo(() => { type={i18n.translate('xpack.securitySolution.endpoint.policy.details.eventCollection', { defaultMessage: 'Event Collection', })} - description={i18n.translate('xpack.securitySolution.endpoint.policy.details.windowsLabel', { - defaultMessage: 'Windows', - })} supportedOss={i18n.translate('xpack.securitySolution.endpoint.policy.details.windows', { defaultMessage: 'Windows', })} diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/protections/malware.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/protections/malware.tsx index 23ac6cc5b813d..84d4bf5355cd9 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/protections/malware.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/protections/malware.tsx @@ -7,9 +7,18 @@ import React, { useCallback, useMemo } from 'react'; import { useDispatch } from 'react-redux'; import styled from 'styled-components'; -import { EuiRadio, EuiSwitch, EuiTitle, EuiSpacer, htmlIdGenerator } from '@elastic/eui'; +import { + EuiRadio, + EuiSwitch, + EuiTitle, + EuiSpacer, + htmlIdGenerator, + EuiCallOut, +} from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; +import { APP_ID } from '../../../../../../../common/constants'; +import { SecurityPageName } from '../../../../../../app/types'; import { Immutable, ProtectionModes } from '../../../../../../../common/endpoint/types'; import { OS, MalwareProtectionOSes } from '../../../types'; @@ -17,6 +26,7 @@ import { ConfigForm } from '../config_form'; import { policyConfig } from '../../../store/policy_details/selectors'; import { usePolicyDetailsSelector } from '../../policy_hooks'; import { clone } from '../../../models/policy_details_config'; +import { LinkToApp } from '../../../../../../common/components/endpoint/link_to_app'; const ProtectionRadioGroup = styled.div` display: flex; @@ -174,12 +184,26 @@ export const MalwareProtections = React.memo(() => { defaultMessage: 'Windows, Mac', })} dataTestSubj="malwareProtectionsForm" - description={i18n.translate('xpack.securitySolution.endpoint.policy.details.malwareLabel', { - defaultMessage: 'Malware', - })} rightCorner={protectionSwitch} > {radioButtons} + + + + + + ), + }} + /> + ); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.test.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.test.tsx index 047aa6918736e..e35c97698f5cb 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.test.tsx @@ -14,7 +14,8 @@ import { AppAction } from '../../../../common/store/actions'; jest.mock('../../../../common/components/link_to'); -describe('when on the policies page', () => { +// Skipping these test now that the Policy List has been hidden +describe.skip('when on the policies page', () => { let render: () => ReturnType; let history: AppContextTestRender['history']; let store: AppContextTestRender['store']; diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx index 20b6534f7664e..667aacd9df3bf 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx @@ -322,9 +322,8 @@ export const PolicyList = React.memo(() => { }), render(pkg: Immutable) { return i18n.translate('xpack.securitySolution.endpoint.policyList.versionField', { - defaultMessage: '{title} v{version}', + defaultMessage: 'v{version}', values: { - title: pkg.title, version: pkg.version, }, }); diff --git a/x-pack/plugins/security_solution/public/network/pages/ip_details/index.tsx b/x-pack/plugins/security_solution/public/network/pages/ip_details/index.tsx index e06f5489a3fc2..42469a4bf29da 100644 --- a/x-pack/plugins/security_solution/public/network/pages/ip_details/index.tsx +++ b/x-pack/plugins/security_solution/public/network/pages/ip_details/index.tsx @@ -90,7 +90,7 @@ export const IPDetailsComponent: React.FC {indicesExist ? ( - + diff --git a/x-pack/plugins/security_solution/public/network/pages/network.tsx b/x-pack/plugins/security_solution/public/network/pages/network.tsx index ca8da4eb711e5..f516f2a2de346 100644 --- a/x-pack/plugins/security_solution/public/network/pages/network.tsx +++ b/x-pack/plugins/security_solution/public/network/pages/network.tsx @@ -106,7 +106,10 @@ const NetworkComponent = React.memo( {indicesExist ? ( - + diff --git a/x-pack/plugins/security_solution/public/overview/components/endpoint_notice/index.tsx b/x-pack/plugins/security_solution/public/overview/components/endpoint_notice/index.tsx index 7170412cb55ad..1d726a7dbd901 100644 --- a/x-pack/plugins/security_solution/public/overview/components/endpoint_notice/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/endpoint_notice/index.tsx @@ -33,7 +33,7 @@ export const EndpointNotice = memo<{ onDismiss: () => void }>(({ onDismiss }) => } @@ -49,7 +49,7 @@ export const EndpointNotice = memo<{ onDismiss: () => void }>(({ onDismiss }) => diff --git a/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/translations.ts b/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/translations.ts index 34e3347b5ff9a..a7f1be3debb83 100644 --- a/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/translations.ts +++ b/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/translations.ts @@ -9,14 +9,14 @@ import { i18n } from '@kbn/i18n'; export const ENDPOINT_POLICY = i18n.translate( 'xpack.securitySolution.host.details.endpoint.endpointPolicy', { - defaultMessage: 'Endpoint policy', + defaultMessage: 'Integration', } ); export const POLICY_STATUS = i18n.translate( 'xpack.securitySolution.host.details.endpoint.policyStatus', { - defaultMessage: 'Policy status', + defaultMessage: 'Configuration Status', } ); diff --git a/x-pack/plugins/security_solution/public/overview/components/overview_empty/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/overview_empty/index.test.tsx new file mode 100644 index 0000000000000..2112350278e8e --- /dev/null +++ b/x-pack/plugins/security_solution/public/overview/components/overview_empty/index.test.tsx @@ -0,0 +1,83 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; +import { shallow, ShallowWrapper } from 'enzyme'; +import { OverviewEmpty } from '.'; +import { useIngestEnabledCheck } from '../../../common/hooks/endpoint/ingest_enabled'; +jest.mock('../../../common/lib/kibana'); +jest.mock('../../../management/pages/endpoint_hosts/view/hooks', () => ({ + useIngestUrl: jest + .fn() + .mockReturnValue({ appId: 'ingestAppId', appPath: 'ingestPath', url: 'ingestUrl' }), +})); + +jest.mock('../../../common/hooks/endpoint/ingest_enabled', () => ({ + useIngestEnabledCheck: jest.fn().mockReturnValue({ allEnabled: true }), +})); + +jest.mock('../../../common/hooks/endpoint/use_navigate_to_app_event_handler', () => ({ + useNavigateToAppEventHandler: jest.fn(), +})); + +describe('OverviewEmpty', () => { + describe('When isIngestEnabled = true', () => { + let wrapper: ShallowWrapper; + beforeAll(() => { + wrapper = shallow(); + }); + + afterAll(() => { + (useIngestEnabledCheck as jest.Mock).mockReset(); + }); + + test('render with correct actions ', () => { + expect(wrapper.find('[data-test-subj="empty-page"]').prop('actions')).toEqual({ + beats: { + description: + 'Lightweight Beats can send data from hundreds or thousands of machines and systems', + fill: false, + label: 'Add data with Beats', + url: '/app/home#/tutorial_directory/security', + }, + elasticAgent: { + description: + 'The Elastic Agent provides a simple, unified way to add monitoring to your hosts.', + fill: false, + label: 'Add data with Elastic Agent', + url: 'ingestUrl', + }, + endpoint: { + description: + 'Protect your hosts with threat prevention, detection, and deep security data visibility.', + fill: false, + label: 'Add Elastic Endpoint Security', + onClick: undefined, + url: '/app/home#/tutorial_directory/security', + }, + }); + }); + }); + + describe('When isIngestEnabled = false', () => { + let wrapper: ShallowWrapper; + beforeAll(() => { + (useIngestEnabledCheck as jest.Mock).mockReturnValue({ allEnabled: false }); + wrapper = shallow(); + }); + + test('render with correct actions ', () => { + expect(wrapper.find('[data-test-subj="empty-page"]').prop('actions')).toEqual({ + beats: { + description: + 'Lightweight Beats can send data from hundreds or thousands of machines and systems', + fill: false, + label: 'Add data with Beats', + url: '/app/home#/tutorial_directory/security', + }, + }); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/overview/components/overview_empty/index.tsx b/x-pack/plugins/security_solution/public/overview/components/overview_empty/index.tsx index 33413be10079e..1d2c6889213f1 100644 --- a/x-pack/plugins/security_solution/public/overview/components/overview_empty/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/overview_empty/index.tsx @@ -4,11 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { useMemo } from 'react'; +import { omit } from 'lodash/fp'; + import { FormattedMessage } from '@kbn/i18n/react'; import { EuiLink } from '@elastic/eui'; import * as i18nCommon from '../../../common/translations'; -import { EmptyPage } from '../../../common/components/empty_page'; +import { EmptyPage, EmptyPageActionsProps } from '../../../common/components/empty_page'; import { useKibana } from '../../../common/lib/kibana'; import { ADD_DATA_PATH } from '../../../../common/constants'; import { useIngestUrl } from '../../../management/pages/endpoint_hosts/view/hooks'; @@ -23,23 +25,45 @@ const OverviewEmptyComponent: React.FC = () => { ); const handleOnClick = useNavigateToAppEventHandler(ingestAppId, { path: ingestPath }); const { allEnabled: isIngestEnabled } = useIngestEnabledCheck(); + const emptyPageActions: EmptyPageActionsProps = useMemo( + () => ({ + elasticAgent: { + label: i18nCommon.EMPTY_ACTION_ELASTIC_AGENT, + url: ingestUrl, + description: i18nCommon.EMPTY_ACTION_ELASTIC_AGENT_DESCRIPTION, + fill: false, + }, + beats: { + label: i18nCommon.EMPTY_ACTION_BEATS, + url: `${basePath}${ADD_DATA_PATH}`, + description: i18nCommon.EMPTY_ACTION_BEATS_DESCRIPTION, + fill: false, + }, + endpoint: { + label: i18nCommon.EMPTY_ACTION_ENDPOINT, + url: `${basePath}${ADD_DATA_PATH}`, + description: i18nCommon.EMPTY_ACTION_ENDPOINT_DESCRIPTION, + onClick: handleOnClick, + fill: false, + }, + }), + [basePath, ingestUrl, handleOnClick] + ); + + const emptyPageIngestDisabledActions = useMemo( + () => omit(['elasticAgent', 'endpoint'], emptyPageActions), + [emptyPageActions] + ); return isIngestEnabled === true ? ( {i18nCommon.EMPTY_ACTION_SECONDARY} @@ -50,16 +74,13 @@ const OverviewEmptyComponent: React.FC = () => { /> ) : ( {i18nCommon.EMPTY_ACTION_SECONDARY} diff --git a/x-pack/plugins/security_solution/public/overview/pages/overview.test.tsx b/x-pack/plugins/security_solution/public/overview/pages/overview.test.tsx index 286cc870378e1..74225c4e4f823 100644 --- a/x-pack/plugins/security_solution/public/overview/pages/overview.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/pages/overview.test.tsx @@ -83,7 +83,7 @@ describe('Overview', () => { ); - expect(wrapper.find('[data-test-subj="empty-page-secondary-action"]').exists()).toBe(false); + expect(wrapper.find('[data-test-subj="empty-page-endpoint-action"]').exists()).toBe(false); }); it('shows Endpoint get ready button when ingest is enabled', () => { @@ -95,7 +95,7 @@ describe('Overview', () => { ); - expect(wrapper.find('[data-test-subj="empty-page-secondary-action"]').exists()).toBe(true); + expect(wrapper.find('[data-test-subj="empty-page-endpoint-action"]').exists()).toBe(true); }); }); diff --git a/x-pack/plugins/security_solution/public/overview/pages/overview.tsx b/x-pack/plugins/security_solution/public/overview/pages/overview.tsx index 6563f3c2b824d..1b743c259555a 100644 --- a/x-pack/plugins/security_solution/public/overview/pages/overview.tsx +++ b/x-pack/plugins/security_solution/public/overview/pages/overview.tsx @@ -17,6 +17,7 @@ import { SiemSearchBar } from '../../common/components/search_bar'; import { WrapperPage } from '../../common/components/wrapper_page'; import { useGlobalTime } from '../../common/containers/use_global_time'; import { useWithSource } from '../../common/containers/source'; + import { EventsByDataset } from '../components/events_by_dataset'; import { EventCounts } from '../components/event_counts'; import { OverviewEmpty } from '../components/overview_empty'; @@ -66,12 +67,11 @@ const OverviewComponent: React.FC = ({ addMessage('management', 'dismissEndpointNotice'); }, [addMessage]); const { allEnabled: isIngestEnabled } = useIngestEnabledCheck(); - return ( <> {indicesExist ? ( - + diff --git a/x-pack/plugins/security_solution/public/overview/pages/summary.tsx b/x-pack/plugins/security_solution/public/overview/pages/summary.tsx index 0f20e8bea9dc5..d8260858aa245 100644 --- a/x-pack/plugins/security_solution/public/overview/pages/summary.tsx +++ b/x-pack/plugins/security_solution/public/overview/pages/summary.tsx @@ -71,7 +71,7 @@ export const Summary = React.memo(() => { defaultMessage="If you have input or suggestions regarding your experience with Elastic SIEM, please feel free to {feedback}." values={{ feedback: ( - + +): DataAccessLayer { + const dataAccessLayer: DataAccessLayer = { + /** + * Used to get non-process related events for a node. + */ + async relatedEvents(entityID: string): Promise { + return context.services.http.get(`/api/endpoint/resolver/${entityID}/events`, { + query: { events: 100 }, + }); + }, + /** + * Used to get descendant and ancestor process events for a node. + */ + async resolverTree(entityID: string, signal: AbortSignal): Promise { + return context.services.http.get(`/api/endpoint/resolver/${entityID}`, { + signal, + }); + }, + + /** + * Used to get the default index pattern from the SIEM application. + */ + indexPatterns(): string[] { + return context.services.uiSettings.get(defaultIndexKey); + }, + + /** + * Used to get the entity_id for an _id. + */ + async entities({ + _id, + indices, + signal, + }: { + _id: string; + indices: string[]; + signal: AbortSignal; + }): Promise { + return context.services.http.get('/api/endpoint/resolver/entity', { + signal, + query: { + _id, + indices, + }, + }); + }, + }; + return dataAccessLayer; +} diff --git a/x-pack/plugins/security_solution/public/resolver/data_access_layer/mocks/one_ancestor_two_children.ts b/x-pack/plugins/security_solution/public/resolver/data_access_layer/mocks/one_ancestor_two_children.ts new file mode 100644 index 0000000000000..be0bc1b812a0b --- /dev/null +++ b/x-pack/plugins/security_solution/public/resolver/data_access_layer/mocks/one_ancestor_two_children.ts @@ -0,0 +1,96 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + ResolverRelatedEvents, + ResolverTree, + ResolverEntityIndex, +} from '../../../../common/endpoint/types'; +import { mockEndpointEvent } from '../../store/mocks/endpoint_event'; +import { mockTreeWithNoAncestorsAnd2Children } from '../../store/mocks/resolver_tree'; +import { DataAccessLayer } from '../../types'; + +interface Metadata { + /** + * The `_id` of the document being analyzed. + */ + databaseDocumentID: string; + /** + * A record of entityIDs to be used in tests assertions. + */ + entityIDs: { + /** + * The entityID of the node related to the document being analyzed. + */ + origin: 'origin'; + /** + * The entityID of the first child of the origin. + */ + firstChild: 'firstChild'; + /** + * The entityID of the second child of the origin. + */ + secondChild: 'secondChild'; + }; +} + +/** + * A simple mock dataAccessLayer possible that returns a tree with 0 ancestors and 2 direct children. 1 related event is returned. The parameter to `entities` is ignored. + */ +export function oneAncestorTwoChildren(): { dataAccessLayer: DataAccessLayer; metadata: Metadata } { + const metadata: Metadata = { + databaseDocumentID: '_id', + entityIDs: { origin: 'origin', firstChild: 'firstChild', secondChild: 'secondChild' }, + }; + return { + metadata, + dataAccessLayer: { + /** + * Fetch related events for an entity ID + */ + relatedEvents(entityID: string): Promise { + return Promise.resolve({ + entityID, + events: [ + mockEndpointEvent({ + entityID, + name: 'event', + timestamp: 0, + }), + ], + nextEvent: null, + }); + }, + + /** + * Fetch a ResolverTree for a entityID + */ + resolverTree(): Promise { + return Promise.resolve( + mockTreeWithNoAncestorsAnd2Children({ + originID: metadata.entityIDs.origin, + firstChildID: metadata.entityIDs.firstChild, + secondChildID: metadata.entityIDs.secondChild, + }) + ); + }, + + /** + * Get an array of index patterns that contain events. + */ + indexPatterns(): string[] { + return ['index pattern']; + }, + + /** + * Get entities matching a document. + */ + entities(): Promise { + return Promise.resolve([{ entity_id: metadata.entityIDs.origin }]); + }, + }, + }; +} diff --git a/x-pack/plugins/security_solution/public/resolver/lib/date.test.ts b/x-pack/plugins/security_solution/public/resolver/lib/date.test.ts index 0cc116a85fa57..5555578e44f7b 100644 --- a/x-pack/plugins/security_solution/public/resolver/lib/date.test.ts +++ b/x-pack/plugins/security_solution/public/resolver/lib/date.test.ts @@ -3,37 +3,73 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { getFriendlyElapsedTime } from './date'; +import { getFriendlyElapsedTime, getUnixTime } from './date'; describe('date', () => { - describe('getFriendlyElapsedTime', () => { - const second = 1000; - const minute = second * 60; - const hour = minute * 60; - const day = hour * 24; - const week = day * 7; - const month = day * 30; - const year = day * 365; + const second = 1000; + const minute = second * 60; + const hour = minute * 60; + const day = hour * 24; + const week = day * 7; + const month = day * 30; + const year = day * 365; - const initialTime = new Date('6/1/2020').getTime(); + describe('getUnixTime', () => { + const unixTime = new Date('6/1/2020').getTime(); + const unixStringTime = String(unixTime); + const isoTime = new Date('6/1/2020').toISOString(); + const notATime = 'imLate'; + + it('should return the time if already a unix timestamp', () => { + expect(getUnixTime(unixTime)).toEqual(unixTime); + }); + + it('should properly convert a unix timestamp string to a number', () => { + expect(getUnixTime(unixStringTime)).toEqual(unixTime); + }); + + it('should properly convert an ISO string to a unix timestamp', () => { + expect(getUnixTime(isoTime)).toEqual(unixTime); + }); + it('should return NaN if an invalid time is provided', () => { + expect(getUnixTime(notATime)).toBeNaN(); + }); + }); + + describe('getFriendlyElapsedTime', () => { + const initialTime = new Date('6/1/2020').getTime(); + const oneMillisecond = new Date(initialTime + 1).toISOString(); const oneSecond = new Date(initialTime + 1 * second).getTime(); const oneMinute = new Date(initialTime + 1 * minute).getTime(); - const oneHour = new Date(initialTime + 1 * hour).getTime(); + const oneHour = new Date(initialTime + 1 * hour).toISOString(); const oneDay = new Date(initialTime + 1 * day).getTime(); - const oneWeek = new Date(initialTime + 1 * week).getTime(); + const oneWeek = `${new Date(initialTime + 1 * week).getTime()}`; const oneMonth = new Date(initialTime + 1 * month).getTime(); const oneYear = new Date(initialTime + 1 * year).getTime(); - const almostAMinute = new Date(initialTime + 59.9 * second).getTime(); + const almostASecond = new Date(initialTime + 999).getTime(); + const almostAMinute = new Date(initialTime + 59.9 * second).toISOString(); const almostAnHour = new Date(initialTime + 59.9 * minute).getTime(); const almostADay = new Date(initialTime + 23.9 * hour).getTime(); - const almostAWeek = new Date(initialTime + 6.9 * day).getTime(); + const almostAWeek = new Date(initialTime + 6.9 * day).toISOString(); const almostAMonth = new Date(initialTime + 3.9 * week).getTime(); const almostAYear = new Date(initialTime + 11.9 * month).getTime(); const threeYears = new Date(initialTime + 3 * year).getTime(); + it('should return null if invalid times are given', () => { + expect(getFriendlyElapsedTime(initialTime, 'ImTimeless')).toEqual(null); + }); + it('should return the correct singular relative time', () => { + expect(getFriendlyElapsedTime(initialTime, initialTime)).toEqual({ + duration: '<1', + durationType: 'millisecond', + }); + expect(getFriendlyElapsedTime(initialTime, oneMillisecond)).toEqual({ + duration: 1, + durationType: 'millisecond', + }); expect(getFriendlyElapsedTime(initialTime, oneSecond)).toEqual({ duration: 1, durationType: 'second', @@ -65,6 +101,10 @@ describe('date', () => { }); it('should return the correct pluralized relative time', () => { + expect(getFriendlyElapsedTime(initialTime, almostASecond)).toEqual({ + duration: 999, + durationType: 'milliseconds', + }); expect(getFriendlyElapsedTime(initialTime, almostAMinute)).toEqual({ duration: 59, durationType: 'seconds', diff --git a/x-pack/plugins/security_solution/public/resolver/lib/date.ts b/x-pack/plugins/security_solution/public/resolver/lib/date.ts index de0f9dcd7efbe..3cd0c910f46f3 100644 --- a/x-pack/plugins/security_solution/public/resolver/lib/date.ts +++ b/x-pack/plugins/security_solution/public/resolver/lib/date.ts @@ -6,6 +6,26 @@ import { DurationDetails, DurationTypes } from '../types'; +/** + * Given a time, it will convert it to a unix timestamp if not one already. If it is unable to do so, it will return NaN + */ +export const getUnixTime = (time: number | string): number | typeof NaN => { + if (!time) { + return NaN; + } + if (typeof time === 'number') { + return time; + } + // If it's a date string just get the time in MS + let unixTime = Date.parse(time); + if (Number.isNaN(unixTime)) { + // If not an ISO date string, last check will be if it's a unix timestamp string + unixTime = parseInt(time, 10); + } + + return unixTime; +}; + /* * Given two unix timestamps, it will return an object containing the time difference and properly pluralized friendly version of the time difference. * i.e. a time difference of 1000ms will yield => { duration: 1, durationType: 'second' } and 10000ms will yield => { duration: 10, durationType: 'seconds' } @@ -15,13 +35,13 @@ export const getFriendlyElapsedTime = ( from: number | string, to: number | string ): DurationDetails | null => { - const startTime = typeof from === 'number' ? from : parseInt(from, 10); - const endTime = typeof to === 'number' ? to : parseInt(to, 10); - const elapsedTimeInMs = endTime - startTime; + const startTime = getUnixTime(from); + const endTime = getUnixTime(to); - if (Number.isNaN(elapsedTimeInMs)) { + if (Number.isNaN(startTime) || Number.isNaN(endTime)) { return null; } + const elapsedTimeInMs = endTime - startTime; const second = 1000; const minute = second * 60; @@ -31,45 +51,50 @@ export const getFriendlyElapsedTime = ( const month = day * 30; const year = day * 365; - let duration: number; + let duration: DurationDetails['duration']; let singularType: DurationTypes; let pluralType: DurationTypes; switch (true) { case elapsedTimeInMs >= year: - duration = elapsedTimeInMs / year; + duration = Math.floor(elapsedTimeInMs / year); singularType = 'year'; pluralType = 'years'; break; case elapsedTimeInMs >= month: - duration = elapsedTimeInMs / month; + duration = Math.floor(elapsedTimeInMs / month); singularType = 'month'; pluralType = 'months'; break; case elapsedTimeInMs >= week: - duration = elapsedTimeInMs / week; + duration = Math.floor(elapsedTimeInMs / week); singularType = 'week'; pluralType = 'weeks'; break; case elapsedTimeInMs >= day: - duration = elapsedTimeInMs / day; + duration = Math.floor(elapsedTimeInMs / day); singularType = 'day'; pluralType = 'days'; break; case elapsedTimeInMs >= hour: - duration = elapsedTimeInMs / hour; + duration = Math.floor(elapsedTimeInMs / hour); singularType = 'hour'; pluralType = 'hours'; break; case elapsedTimeInMs >= minute: - duration = elapsedTimeInMs / minute; + duration = Math.floor(elapsedTimeInMs / minute); singularType = 'minute'; pluralType = 'minutes'; break; case elapsedTimeInMs >= second: - duration = elapsedTimeInMs / second; + duration = Math.floor(elapsedTimeInMs / second); singularType = 'second'; pluralType = 'seconds'; break; + case elapsedTimeInMs === 0: + duration = '<1'; + singularType = 'millisecond'; + pluralType = 'millisecond'; // Would never show + break; default: duration = elapsedTimeInMs; singularType = 'millisecond'; @@ -77,6 +102,6 @@ export const getFriendlyElapsedTime = ( break; } - const durationType = duration > 1 ? pluralType : singularType; - return { duration: Math.floor(duration), durationType }; + const durationType = duration === 1 ? singularType : pluralType; + return { duration, durationType }; }; diff --git a/x-pack/plugins/security_solution/public/resolver/models/process_event.test.ts b/x-pack/plugins/security_solution/public/resolver/models/process_event.test.ts index 7eb692851bc9b..4b1d555d0a7c3 100644 --- a/x-pack/plugins/security_solution/public/resolver/models/process_event.test.ts +++ b/x-pack/plugins/security_solution/public/resolver/models/process_event.test.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { eventType, orderByTime } from './process_event'; +import { eventType, orderByTime, userInfoForProcess } from './process_event'; import { mockProcessEvent } from './process_event_test_helpers'; import { LegacyEndpointEvent, ResolverEvent } from '../../../common/endpoint/types'; @@ -24,6 +24,22 @@ describe('process event', () => { expect(eventType(event)).toEqual('processCreated'); }); }); + describe('userInfoForProcess', () => { + let event: LegacyEndpointEvent; + beforeEach(() => { + event = mockProcessEvent({ + user: { + name: 'aaa', + domain: 'bbb', + }, + }); + }); + it('returns the right user info for the process', () => { + const { name, domain } = userInfoForProcess(event)!; + expect(name).toEqual('aaa'); + expect(domain).toEqual('bbb'); + }); + }); describe('orderByTime', () => { let mock: (time: number, eventID: string) => ResolverEvent; let events: ResolverEvent[]; diff --git a/x-pack/plugins/security_solution/public/resolver/models/process_event.ts b/x-pack/plugins/security_solution/public/resolver/models/process_event.ts index 4f8df87b3ac0b..1a5c67f6a6f2f 100644 --- a/x-pack/plugins/security_solution/public/resolver/models/process_event.ts +++ b/x-pack/plugins/security_solution/public/resolver/models/process_event.ts @@ -29,7 +29,7 @@ export function isTerminatedProcess(passedEvent: ResolverEvent) { } /** - * ms since unix epoc, based on timestamp. + * ms since Unix epoc, based on timestamp. * may return NaN if the timestamp wasn't present or was invalid. */ export function datetime(passedEvent: ResolverEvent): number | null { @@ -85,7 +85,7 @@ export function eventType(passedEvent: ResolverEvent): ResolverProcessType { } /** - * Returns the process event's pid + * Returns the process event's PID */ export function uniquePidForProcess(passedEvent: ResolverEvent): string { if (event.isLegacyEvent(passedEvent)) { @@ -96,7 +96,7 @@ export function uniquePidForProcess(passedEvent: ResolverEvent): string { } /** - * Returns the pid for the process on the host + * Returns the PID for the process on the host */ export function processPid(passedEvent: ResolverEvent): number | undefined { if (event.isLegacyEvent(passedEvent)) { @@ -107,7 +107,7 @@ export function processPid(passedEvent: ResolverEvent): number | undefined { } /** - * Returns the process event's parent pid + * Returns the process event's parent PID */ export function uniqueParentPidForProcess(passedEvent: ResolverEvent): string | undefined { if (event.isLegacyEvent(passedEvent)) { @@ -118,7 +118,7 @@ export function uniqueParentPidForProcess(passedEvent: ResolverEvent): string | } /** - * Returns the process event's parent pid + * Returns the process event's parent PID */ export function processParentPid(passedEvent: ResolverEvent): number | undefined { if (event.isLegacyEvent(passedEvent)) { @@ -144,12 +144,12 @@ export function processPath(passedEvent: ResolverEvent): string | undefined { */ export function userInfoForProcess( passedEvent: ResolverEvent -): { user?: string; domain?: string } | undefined { +): { name?: string; domain?: string } | undefined { return passedEvent.user; } /** - * Returns the MD5 hash for the `passedEvent` param, or undefined if it can't be located + * Returns the MD5 hash for the `passedEvent` parameter, or undefined if it can't be located * @param {ResolverEvent} passedEvent The `ResolverEvent` to get the MD5 value for * @returns {string | undefined} The MD5 string for the event */ @@ -164,7 +164,7 @@ export function md5HashForProcess(passedEvent: ResolverEvent): string | undefine /** * Returns the command line path and arguments used to run the `passedEvent` if any * - * @param {ResolverEvent} passedEvent The `ResolverEvent` to get the arguemnts value for + * @param {ResolverEvent} passedEvent The `ResolverEvent` to get the arguments value for * @returns {string | undefined} The arguments (including the path) used to run the process */ export function argsForProcess(passedEvent: ResolverEvent): string | undefined { diff --git a/x-pack/plugins/security_solution/public/resolver/store/data/selectors.test.ts b/x-pack/plugins/security_solution/public/resolver/store/data/selectors.test.ts index 683f8f1a5f84a..6786a93f1d9ca 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/data/selectors.test.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/data/selectors.test.ts @@ -12,6 +12,9 @@ import { createStore } from 'redux'; import { mockTreeWithNoAncestorsAnd2Children, mockTreeWith2AncestorsAndNoChildren, + mockTreeWith1AncestorAnd2ChildrenAndAllNodesHave2GraphableEvents, + mockTreeWithAllProcessesTerminated, + mockTreeWithNoProcessEvents, } from '../mocks/resolver_tree'; import { uniquePidForProcess } from '../../models/process_event'; import { EndpointEvent } from '../../../../common/endpoint/types'; @@ -298,6 +301,34 @@ describe('data state', () => { expect(selectors.ariaFlowtoCandidate(state())(secondAncestorID)).toBe(null); }); }); + describe('with a tree with all processes terminated', () => { + const originID = 'c'; + const firstAncestorID = 'b'; + const secondAncestorID = 'a'; + beforeEach(() => { + actions.push({ + type: 'serverReturnedResolverData', + payload: { + result: mockTreeWithAllProcessesTerminated({ + originID, + firstAncestorID, + secondAncestorID, + }), + // this value doesn't matter + databaseDocumentID: '', + }, + }); + }); + it('should have origin as terminated', () => { + expect(selectors.isProcessTerminated(state())(originID)).toBe(true); + }); + it('should have first ancestor as termianted', () => { + expect(selectors.isProcessTerminated(state())(firstAncestorID)).toBe(true); + }); + it('should have second ancestor as terminated', () => { + expect(selectors.isProcessTerminated(state())(secondAncestorID)).toBe(true); + }); + }); describe('with a tree with 2 children and no ancestors', () => { const originID = 'c'; const firstChildID = 'd'; @@ -353,4 +384,51 @@ describe('data state', () => { } }); }); + describe('with a tree with 1 ancestor and 2 children, where all nodes have 2 graphable events', () => { + const ancestorID = 'b'; + const originID = 'c'; + const firstChildID = 'd'; + const secondChildID = 'e'; + beforeEach(() => { + const tree = mockTreeWith1AncestorAnd2ChildrenAndAllNodesHave2GraphableEvents({ + ancestorID, + originID, + firstChildID, + secondChildID, + }); + actions.push({ + type: 'serverReturnedResolverData', + payload: { + result: tree, + // this value doesn't matter + databaseDocumentID: '', + }, + }); + }); + it('should have 4 graphable processes', () => { + expect(selectors.graphableProcesses(state()).length).toBe(4); + }); + }); + describe('with a tree with no process events', () => { + beforeEach(() => { + const tree = mockTreeWithNoProcessEvents(); + actions.push({ + type: 'serverReturnedResolverData', + payload: { + result: tree, + // this value doesn't matter + databaseDocumentID: '', + }, + }); + }); + it('should return an empty layout', () => { + expect(selectors.layout(state())).toMatchInlineSnapshot(` + Object { + "ariaLevels": Map {}, + "edgeLineSegments": Array [], + "processNodePositions": Map {}, + } + `); + }); + }); }); diff --git a/x-pack/plugins/security_solution/public/resolver/store/data/selectors.ts b/x-pack/plugins/security_solution/public/resolver/store/data/selectors.ts index 40138d3f2fd3c..10ace895b3267 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/data/selectors.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/data/selectors.ts @@ -105,12 +105,33 @@ export const terminatedProcesses = createSelector(resolverTreeResponse, function ); }); +/** + * A function that given an entity id returns a boolean indicating if the id is in the set of terminated processes. + */ +export const isProcessTerminated = createSelector(terminatedProcesses, function ( + /* eslint-disable no-shadow */ + terminatedProcesses + /* eslint-enable no-shadow */ +) { + return (entityId: string) => { + return terminatedProcesses.has(entityId); + }; +}); + /** * Process events that will be graphed. */ export const graphableProcesses = createSelector(resolverTreeResponse, function (tree?) { + // Keep track of the last process event (in array order) for each entity ID + const events: Map = new Map(); if (tree) { - return resolverTreeModel.lifecycleEvents(tree).filter(isGraphableProcess); + for (const event of resolverTreeModel.lifecycleEvents(tree)) { + if (isGraphableProcess(event)) { + const entityID = uniquePidForProcess(event); + events.set(entityID, event); + } + } + return [...events.values()]; } else { return []; } @@ -353,9 +374,9 @@ export const layout = createSelector( // find the origin node const originNode = indexedProcessTreeModel.processEvent(indexedProcessTree, originID); - if (!originNode) { - // this should only happen if the `ResolverTree` from the server has an entity ID with no matching lifecycle events. - throw new Error('Origin node not found in ResolverTree'); + if (originNode === null) { + // If a tree is returned that has no process events for the origin, this can happen. + return taxiLayout; } // Find the position of the origin, we'll center the map on it intrinsically diff --git a/x-pack/plugins/security_solution/public/resolver/store/index.ts b/x-pack/plugins/security_solution/public/resolver/store/index.ts index d9e750241ced1..950a61db33f17 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/index.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/index.ts @@ -6,22 +6,20 @@ import { createStore, applyMiddleware, Store } from 'redux'; import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly'; -import { KibanaReactContextValue } from '../../../../../../src/plugins/kibana_react/public'; -import { ResolverState } from '../types'; -import { StartServices } from '../../types'; +import { ResolverState, DataAccessLayer } from '../types'; import { resolverReducer } from './reducer'; import { resolverMiddlewareFactory } from './middleware'; import { ResolverAction } from './actions'; export const storeFactory = ( - context?: KibanaReactContextValue + dataAccessLayer: DataAccessLayer ): Store => { const actionsDenylist: Array = ['userMovedPointer']; const composeEnhancers = composeWithDevTools({ name: 'Resolver', actionsBlacklist: actionsDenylist, }); - const middlewareEnhancer = applyMiddleware(resolverMiddlewareFactory(context)); + const middlewareEnhancer = applyMiddleware(resolverMiddlewareFactory(dataAccessLayer)); return createStore(resolverReducer, composeEnhancers(middlewareEnhancer)); }; diff --git a/x-pack/plugins/security_solution/public/resolver/store/middleware/index.ts b/x-pack/plugins/security_solution/public/resolver/store/middleware/index.ts index 398e855a1f5d4..ef6b1f5eb3c6f 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/middleware/index.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/middleware/index.ts @@ -5,34 +5,26 @@ */ import { Dispatch, MiddlewareAPI } from 'redux'; -import { KibanaReactContextValue } from '../../../../../../../src/plugins/kibana_react/public'; -import { StartServices } from '../../../types'; -import { ResolverState } from '../../types'; +import { ResolverState, DataAccessLayer } from '../../types'; import { ResolverRelatedEvents } from '../../../../common/endpoint/types'; import { ResolverTreeFetcher } from './resolver_tree_fetcher'; import { ResolverAction } from '../actions'; type MiddlewareFactory = ( - context?: KibanaReactContextValue + dataAccessLayer: DataAccessLayer ) => ( api: MiddlewareAPI, S> ) => (next: Dispatch) => (action: ResolverAction) => unknown; /** - * The redux middleware that the app uses to trigger side effects. + * The `redux` middleware that the application uses to trigger side effects. * All data fetching should be done here. - * For actions that the app triggers directly, use `app` as a prefix for the type. + * For actions that the application triggers directly, use `app` as a prefix for the type. * For actions that are triggered as a result of server interaction, use `server` as a prefix for the type. */ -export const resolverMiddlewareFactory: MiddlewareFactory = (context) => { +export const resolverMiddlewareFactory: MiddlewareFactory = (dataAccessLayer: DataAccessLayer) => { return (api) => (next) => { - // This cannot work w/o `context`. - if (!context) { - return async (action: ResolverAction) => { - next(action); - }; - } - const resolverTreeFetcher = ResolverTreeFetcher(context, api); + const resolverTreeFetcher = ResolverTreeFetcher(dataAccessLayer, api); return async (action: ResolverAction) => { next(action); @@ -45,12 +37,7 @@ export const resolverMiddlewareFactory: MiddlewareFactory = (context) => { const entityIdToFetchFor = action.payload; let result: ResolverRelatedEvents | undefined; try { - result = await context.services.http.get( - `/api/endpoint/resolver/${entityIdToFetchFor}/events`, - { - query: { events: 100 }, - } - ); + result = await dataAccessLayer.relatedEvents(entityIdToFetchFor); } catch { api.dispatch({ type: 'serverFailedToReturnRelatedEventData', diff --git a/x-pack/plugins/security_solution/public/resolver/store/middleware/resolver_tree_fetcher.ts b/x-pack/plugins/security_solution/public/resolver/store/middleware/resolver_tree_fetcher.ts index 7d16dc251e6fc..2c98059d420e8 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/middleware/resolver_tree_fetcher.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/middleware/resolver_tree_fetcher.ts @@ -9,11 +9,8 @@ import { Dispatch, MiddlewareAPI } from 'redux'; import { ResolverTree, ResolverEntityIndex } from '../../../../common/endpoint/types'; -import { KibanaReactContextValue } from '../../../../../../../src/plugins/kibana_react/public'; -import { ResolverState } from '../../types'; +import { ResolverState, DataAccessLayer } from '../../types'; import * as selectors from '../selectors'; -import { StartServices } from '../../../types'; -import { DEFAULT_INDEX_KEY as defaultIndexKey } from '../../../../common/constants'; import { ResolverAction } from '../actions'; /** * A function that handles syncing ResolverTree data w/ the current entity ID. @@ -23,7 +20,7 @@ import { ResolverAction } from '../actions'; * This is a factory because it is stateful and keeps that state in closure. */ export function ResolverTreeFetcher( - context: KibanaReactContextValue, + dataAccessLayer: DataAccessLayer, api: MiddlewareAPI, ResolverState> ): () => void { let lastRequestAbortController: AbortController | undefined; @@ -48,17 +45,12 @@ export function ResolverTreeFetcher( payload: databaseDocumentIDToFetch, }); try { - const indices: string[] = context.services.uiSettings.get(defaultIndexKey); - const matchingEntities: ResolverEntityIndex = await context.services.http.get( - '/api/endpoint/resolver/entity', - { - signal: lastRequestAbortController.signal, - query: { - _id: databaseDocumentIDToFetch, - indices, - }, - } - ); + const indices: string[] = dataAccessLayer.indexPatterns(); + const matchingEntities: ResolverEntityIndex = await dataAccessLayer.entities({ + _id: databaseDocumentIDToFetch, + indices, + signal: lastRequestAbortController.signal, + }); if (matchingEntities.length < 1) { // If no entity_id could be found for the _id, bail out with a failure. api.dispatch({ @@ -68,9 +60,10 @@ export function ResolverTreeFetcher( return; } const entityIDToFetch = matchingEntities[0].entity_id; - result = await context.services.http.get(`/api/endpoint/resolver/${entityIDToFetch}`, { - signal: lastRequestAbortController.signal, - }); + result = await dataAccessLayer.resolverTree( + entityIDToFetch, + lastRequestAbortController.signal + ); } catch (error) { // https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-AbortError if (error instanceof DOMException && error.name === 'AbortError') { diff --git a/x-pack/plugins/security_solution/public/resolver/store/mocks/endpoint_event.ts b/x-pack/plugins/security_solution/public/resolver/store/mocks/endpoint_event.ts index b58ea73e1fdc7..709f2faf13b00 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/mocks/endpoint_event.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/mocks/endpoint_event.ts @@ -14,16 +14,18 @@ export function mockEndpointEvent({ name, parentEntityId, timestamp, + lifecycleType, }: { entityID: string; name: string; - parentEntityId: string | undefined; + parentEntityId?: string; timestamp: number; + lifecycleType?: string; }): EndpointEvent { return { '@timestamp': timestamp, event: { - type: 'start', + type: lifecycleType ? lifecycleType : 'start', category: 'process', }, process: { diff --git a/x-pack/plugins/security_solution/public/resolver/store/mocks/resolver_tree.ts b/x-pack/plugins/security_solution/public/resolver/store/mocks/resolver_tree.ts index 862cf47f73947..6a8ab61ccf9b6 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/mocks/resolver_tree.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/mocks/resolver_tree.ts @@ -46,6 +46,69 @@ export function mockTreeWith2AncestorsAndNoChildren({ } as unknown) as ResolverTree; } +export function mockTreeWithAllProcessesTerminated({ + originID, + firstAncestorID, + secondAncestorID, +}: { + secondAncestorID: string; + firstAncestorID: string; + originID: string; +}): ResolverTree { + const secondAncestor: ResolverEvent = mockEndpointEvent({ + entityID: secondAncestorID, + name: 'a', + parentEntityId: 'none', + timestamp: 0, + }); + const firstAncestor: ResolverEvent = mockEndpointEvent({ + entityID: firstAncestorID, + name: 'b', + parentEntityId: secondAncestorID, + timestamp: 1, + }); + const originEvent: ResolverEvent = mockEndpointEvent({ + entityID: originID, + name: 'c', + parentEntityId: firstAncestorID, + timestamp: 2, + }); + const secondAncestorTermination: ResolverEvent = mockEndpointEvent({ + entityID: secondAncestorID, + name: 'a', + parentEntityId: 'none', + timestamp: 0, + lifecycleType: 'end', + }); + const firstAncestorTermination: ResolverEvent = mockEndpointEvent({ + entityID: firstAncestorID, + name: 'b', + parentEntityId: secondAncestorID, + timestamp: 1, + lifecycleType: 'end', + }); + const originEventTermination: ResolverEvent = mockEndpointEvent({ + entityID: originID, + name: 'c', + parentEntityId: firstAncestorID, + timestamp: 2, + lifecycleType: 'end', + }); + return ({ + entityID: originID, + children: { + childNodes: [], + }, + ancestry: { + ancestors: [ + { lifecycle: [secondAncestor, secondAncestorTermination] }, + { lifecycle: [firstAncestor, firstAncestorTermination] }, + ], + }, + lifecycle: [originEvent, originEventTermination], + } as unknown) as ResolverTree; +} + export function mockTreeWithNoAncestorsAnd2Children({ originID, firstChildID, @@ -85,3 +148,111 @@ export function mockTreeWithNoAncestorsAnd2Children({ lifecycle: [origin], } as unknown) as ResolverTree; } + +/** + * Creates a mock tree w/ 2 'graphable' events per node. This simulates the scenario where data has been duplicated in the response from the server. + */ +export function mockTreeWith1AncestorAnd2ChildrenAndAllNodesHave2GraphableEvents({ + ancestorID, + originID, + firstChildID, + secondChildID, +}: { + ancestorID: string; + originID: string; + firstChildID: string; + secondChildID: string; +}): ResolverTree { + const ancestor: ResolverEvent = mockEndpointEvent({ + entityID: ancestorID, + name: ancestorID, + timestamp: 1, + parentEntityId: undefined, + }); + const ancestorClone: ResolverEvent = mockEndpointEvent({ + entityID: ancestorID, + name: ancestorID, + timestamp: 1, + parentEntityId: undefined, + }); + const origin: ResolverEvent = mockEndpointEvent({ + entityID: originID, + name: originID, + parentEntityId: ancestorID, + timestamp: 0, + }); + const originClone: ResolverEvent = mockEndpointEvent({ + entityID: originID, + name: originID, + parentEntityId: ancestorID, + timestamp: 0, + }); + const firstChild: ResolverEvent = mockEndpointEvent({ + entityID: firstChildID, + name: firstChildID, + parentEntityId: originID, + timestamp: 1, + }); + const firstChildClone: ResolverEvent = mockEndpointEvent({ + entityID: firstChildID, + name: firstChildID, + parentEntityId: originID, + timestamp: 1, + }); + const secondChild: ResolverEvent = mockEndpointEvent({ + entityID: secondChildID, + name: secondChildID, + parentEntityId: originID, + timestamp: 2, + }); + const secondChildClone: ResolverEvent = mockEndpointEvent({ + entityID: secondChildID, + name: secondChildID, + parentEntityId: originID, + timestamp: 2, + }); + + return ({ + entityID: originID, + children: { + childNodes: [ + { lifecycle: [firstChild, firstChildClone] }, + { lifecycle: [secondChild, secondChildClone] }, + ], + }, + ancestry: { + ancestors: [{ lifecycle: [ancestor, ancestorClone] }], + }, + lifecycle: [origin, originClone], + } as unknown) as ResolverTree; +} + +export function mockTreeWithNoProcessEvents(): ResolverTree { + return { + entityID: 'entityID', + children: { + childNodes: [], + nextChild: null, + }, + relatedEvents: { + events: [], + nextEvent: null, + }, + relatedAlerts: { + alerts: [], + nextAlert: null, + }, + lifecycle: [], + ancestry: { + ancestors: [], + nextAncestor: null, + }, + stats: { + totalAlerts: 0, + events: { + total: 0, + byCategory: {}, + }, + }, + }; +} diff --git a/x-pack/plugins/security_solution/public/resolver/store/reducer.ts b/x-pack/plugins/security_solution/public/resolver/store/reducer.ts index 028c28d94a41b..d0f9701fe944e 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/reducer.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/reducer.ts @@ -18,7 +18,14 @@ const uiReducer: Reducer = ( }, action ) => { - if (action.type === 'userFocusedOnResolverNode') { + if (action.type === 'serverReturnedResolverData') { + const next: ResolverUIState = { + ...state, + ariaActiveDescendant: action.payload.result.entityID, + selectedNode: action.payload.result.entityID, + }; + return next; + } else if (action.type === 'userFocusedOnResolverNode') { const next: ResolverUIState = { ...state, ariaActiveDescendant: action.payload, diff --git a/x-pack/plugins/security_solution/public/resolver/store/selectors.ts b/x-pack/plugins/security_solution/public/resolver/store/selectors.ts index 66d7e04d118ed..87ef8d5d095ef 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/selectors.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/selectors.ts @@ -53,6 +53,14 @@ export const userIsPanning = composeSelectors(cameraStateSelector, cameraSelecto */ export const isAnimating = composeSelectors(cameraStateSelector, cameraSelectors.isAnimating); +/** + * Whether or not a given entity id is in the set of termination events. + */ +export const isProcessTerminated = composeSelectors( + dataStateSelector, + dataSelectors.isProcessTerminated +); + /** * Given a nodeID (aka entity_id) get the indexed process event. * Legacy functions take process events instead of nodeID, use this to get diff --git a/x-pack/plugins/security_solution/public/resolver/test_utilities/connect_enzyme_wrapper_and_store.ts b/x-pack/plugins/security_solution/public/resolver/test_utilities/connect_enzyme_wrapper_and_store.ts new file mode 100644 index 0000000000000..3a4a1f7d634d1 --- /dev/null +++ b/x-pack/plugins/security_solution/public/resolver/test_utilities/connect_enzyme_wrapper_and_store.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Store } from 'redux'; +import { ReactWrapper } from 'enzyme'; + +/** + * We use the full-DOM emulation mode of `enzyme` via `mount`. Even though we use `react-redux`, `enzyme` + * does not update the DOM after state transitions. This subscribes to the `redux` store and after any state + * transition it asks `enzyme` to update the DOM to match the React state. + */ +export function connectEnzymeWrapperAndStore(store: Store, wrapper: ReactWrapper): void { + store.subscribe(() => { + // See https://enzymejs.github.io/enzyme/docs/api/ReactWrapper/update.html + return wrapper.update(); + }); +} diff --git a/x-pack/plugins/security_solution/public/resolver/test_utilities/extend_jest.ts b/x-pack/plugins/security_solution/public/resolver/test_utilities/extend_jest.ts new file mode 100644 index 0000000000000..9fc7af38beb42 --- /dev/null +++ b/x-pack/plugins/security_solution/public/resolver/test_utilities/extend_jest.ts @@ -0,0 +1,88 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +/** + * Typescript won't allow global namespace stuff unless you're in a module. + * This wouldn't otherwise be a module. The code runs as soon as it's imported. + * This is done this way because the `declare` will be active on import, so in + * order to be correct, the code that the `declare` declares needs to be available on import as well. + */ +export {}; + +declare global { + /* eslint-disable @typescript-eslint/no-namespace */ + namespace jest { + interface Matchers { + toYieldEqualTo(expectedYield: T extends AsyncIterable ? E : never): Promise; + } + } +} + +expect.extend({ + /** + * A custom matcher that takes an async generator and compares each value it yields to an expected value. + * If any yielded value deep-equals the expected value, the matcher will pass. + * If the generator ends with none of the yielded values matching, it will fail. + */ + async toYieldEqualTo( + this: jest.MatcherContext, + receivedIterable: AsyncIterable, + expected: T + ): Promise<{ pass: boolean; message: () => string }> { + // Used in printing out the pass or fail message + const matcherName = 'toSometimesYieldEqualTo'; + const options: jest.MatcherHintOptions = { + comment: 'deep equality with any yielded value', + isNot: this.isNot, + promise: this.promise, + }; + // The last value received: Used in printing the message + const received: T[] = []; + + // Set to true if the test passes. + let pass: boolean = false; + + // Async iterate over the iterable + for await (const next of receivedIterable) { + // keep track of all received values. Used in pass and fail messages + received.push(next); + // Use deep equals to compare the value to the expected value + if (this.equals(next, expected)) { + // If the value is equal, break + pass = true; + break; + } + } + + // Use `pass` as set in the above loop (or initialized to `false`) + // See https://jestjs.io/docs/en/expect#custom-matchers-api and https://jestjs.io/docs/en/expect#thisutils + const message = pass + ? () => + `${this.utils.matcherHint(matcherName, undefined, undefined, options)}\n\n` + + `Expected: not ${this.utils.printExpected(expected)}\n${ + this.utils.stringify(expected) !== this.utils.stringify(received[received.length - 1]!) + ? `Received: ${this.utils.printReceived(received[received.length - 1])}` + : '' + }` + : () => + `${this.utils.matcherHint(matcherName, undefined, undefined, options)}\n\nCompared ${ + received.length + } yields.\n\n${received + .map( + (next, index) => + `yield ${index + 1}:\n\n${this.utils.printDiffOrStringify( + expected, + next, + 'Expected', + 'Received', + this.expand + )}` + ) + .join(`\n\n`)}`; + + return { message, pass }; + }, +}); diff --git a/x-pack/plugins/security_solution/public/resolver/test_utilities/react_wrapper.ts b/x-pack/plugins/security_solution/public/resolver/test_utilities/react_wrapper.ts new file mode 100644 index 0000000000000..40267d83c30f8 --- /dev/null +++ b/x-pack/plugins/security_solution/public/resolver/test_utilities/react_wrapper.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ReactWrapper } from 'enzyme'; + +/** + * Return a collection of attribute 'entries'. + * The 'entries' are attributeName-attributeValue tuples. + */ +export function attributeEntries(wrapper: ReactWrapper): Array<[string, string]> { + return Array.prototype.slice + .call(wrapper.getDOMNode().attributes) + .map(({ name, value }) => [name, value]); +} diff --git a/x-pack/plugins/security_solution/public/resolver/test_utilities/simulator/index.tsx b/x-pack/plugins/security_solution/public/resolver/test_utilities/simulator/index.tsx new file mode 100644 index 0000000000000..7a61427c56a3b --- /dev/null +++ b/x-pack/plugins/security_solution/public/resolver/test_utilities/simulator/index.tsx @@ -0,0 +1,290 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { Store, createStore, applyMiddleware } from 'redux'; +import { mount, ReactWrapper } from 'enzyme'; +import { createMemoryHistory, History as HistoryPackageHistoryInterface } from 'history'; +import { CoreStart } from '../../../../../../../src/core/public'; +import { coreMock } from '../../../../../../../src/core/public/mocks'; +import { connectEnzymeWrapperAndStore } from '../connect_enzyme_wrapper_and_store'; +import { spyMiddlewareFactory } from '../spy_middleware_factory'; +import { resolverMiddlewareFactory } from '../../store/middleware'; +import { resolverReducer } from '../../store/reducer'; +import { MockResolver } from './mock_resolver'; +import { ResolverState, DataAccessLayer, SpyMiddleware } from '../../types'; +import { ResolverAction } from '../../store/actions'; + +/** + * Test a Resolver instance using jest, enzyme, and a mock data layer. + */ +export class Simulator { + /** + * A string that uniquely identifies this Resolver instance among others mounted in the DOM. + */ + private readonly resolverComponentInstanceID: string; + /** + * The redux store, creating in the constructor using the `dataAccessLayer`. + * This code subscribes to state transitions. + */ + private readonly store: Store; + /** + * A fake 'History' API used with `react-router` to simulate a browser history. + */ + private readonly history: HistoryPackageHistoryInterface; + /** + * The 'wrapper' returned by `enzyme` that contains the rendered Resolver react code. + */ + private readonly wrapper: ReactWrapper; + /** + * A `redux` middleware that exposes all actions dispatched (along with the state at that point.) + * This is used by `debugActions`. + */ + private readonly spyMiddleware: SpyMiddleware; + constructor({ + dataAccessLayer, + resolverComponentInstanceID, + databaseDocumentID, + }: { + /** + * A (mock) data access layer that will be used to create the Resolver store. + */ + dataAccessLayer: DataAccessLayer; + /** + * A string that uniquely identifies this Resolver instance among others mounted in the DOM. + */ + resolverComponentInstanceID: string; + /** + * a databaseDocumentID to pass to Resolver. Resolver will use this in requests to the mock data layer. + */ + databaseDocumentID?: string; + }) { + this.resolverComponentInstanceID = resolverComponentInstanceID; + // create the spy middleware (for debugging tests) + this.spyMiddleware = spyMiddlewareFactory(); + + /** + * Create the real resolver middleware with a fake data access layer. + * By providing different data access layers, you can simulate different data and server environments. + */ + const middlewareEnhancer = applyMiddleware( + resolverMiddlewareFactory(dataAccessLayer), + // install the spyMiddleware + this.spyMiddleware.middleware + ); + + // Create a redux store w/ the top level Resolver reducer and the enhancer that includes the Resolver middleware and the `spyMiddleware` + this.store = createStore(resolverReducer, middlewareEnhancer); + + // Create a fake 'history' instance that Resolver will use to read and write query string values + this.history = createMemoryHistory(); + + // Used for `KibanaContextProvider` + const coreStart: CoreStart = coreMock.createStart(); + + // Render Resolver via the `MockResolver` component, using `enzyme`. + this.wrapper = mount( + + ); + + // Update the enzyme wrapper after each state transition + connectEnzymeWrapperAndStore(this.store, this.wrapper); + } + + /** + * Call this to console.log actions (and state). Use this to debug your tests. + * State and actions aren't exposed otherwise because the tests using this simulator should + * assert stuff about the DOM instead of internal state. Use selector/middleware/reducer + * unit tests to test that stuff. + */ + public debugActions(): /** + * Optionally call this to stop debugging actions. + */ () => void { + return this.spyMiddleware.debugActions(); + } + + /** + * Return a promise that resolves after the `store`'s next state transition. + * Used by `mapStateTransitions` + */ + private stateTransitioned(): Promise { + // keep track of the resolve function of the promise that has been returned. + let resolveState: (() => void) | null = null; + + const promise: Promise = new Promise((resolve) => { + // Immediately expose the resolve function in the outer scope. It will be resolved when the next state transition occurs. + resolveState = resolve; + }); + + // Subscribe to the store + const unsubscribe = this.store.subscribe(() => { + // Once a state transition occurs, unsubscribe. + unsubscribe(); + // Resolve the promise. The null assertion is safe here as Promise initializers run immediately (according to spec and node/browser implementations.) + // NB: the state is not resolved here. Code using the simulator should not rely on state or selectors of state. + resolveState!(); + }); + + // Return the promise that will be resolved on the next state transition, allowing code to `await` for the next state transition. + return promise; + } + + /** + * This will yield the return value of `mapper` after each state transition. If no state transition occurs for 10 event loops in a row, this will give up. + */ + public async *mapStateTransitions(mapper: () => R): AsyncIterable { + // Yield the value before any state transitions have occurred. + yield mapper(); + + /** Increment this each time an event loop completes without a state transition. + * If this value hits `10`, end the loop. + * + * Code will test assertions after each state transition. If the assertion hasn't passed and no further state transitions occur, + * then the jest timeout will happen. The timeout doesn't give a useful message about the assertion. + * By short-circuiting this function, code that uses it can short circuit the test timeout and print a useful error message. + * + * NB: the logic to short-circuit the loop is here because knowledge of state is a concern of the simulator, not tests. + */ + let timeoutCount = 0; + while (true) { + /** + * `await` a race between the next state transition and a timeout that happens after `0`ms. + * If the timeout wins, no `dispatch` call caused a state transition in the last loop. + * If this keeps happening, assume that Resolver isn't going to do anything else. + * + * If Resolver adds intentional delay logic (e.g. waiting before making a request), this code might have to change. + * In that case, Resolver should use the side effect context to schedule future work. This code could then subscribe to some event published by the side effect context. That way, this code will be aware of Resolver's intention to do work. + */ + const timedOut: boolean = await Promise.race([ + (async (): Promise => { + await this.stateTransitioned(); + // If a state transition occurs, return false for `timedOut` + return false; + })(), + new Promise((resolve) => { + setTimeout(() => { + // If a timeout occurs, resolve `timedOut` as true + return resolve(true); + }, 0); + }), + ]); + + if (timedOut) { + // If a timout occurred, note it. + timeoutCount++; + if (timeoutCount === 10) { + // if 10 timeouts happen in a row, end the loop early + return; + } + } else { + // If a state transition occurs, reset the timeout count and yield the value + timeoutCount = 0; + yield mapper(); + } + } + } + + /** + * Find a process node element. Takes options supported by `resolverNodeSelector`. + * returns a `ReactWrapper` even if nothing is found, as that is how `enzyme` does things. + */ + public processNodeElements(options: ProcessNodeElementSelectorOptions = {}): ReactWrapper { + return this.findInDOM(processNodeElementSelector(options)); + } + + /** + * true if a process node element is found for the entityID and if it has an [aria-selected] attribute. + */ + public processNodeElementLooksSelected(entityID: string): boolean { + return this.processNodeElements({ entityID, selected: true }).length === 1; + } + + /** + * true if a process node element is found for the entityID and if it *does not have* an [aria-selected] attribute. + */ + public processNodeElementLooksUnselected(entityID: string): boolean { + // find the process node, then exclude it if its selected. + return ( + this.processNodeElements({ entityID }).not( + processNodeElementSelector({ entityID, selected: true }) + ).length === 1 + ); + } + + /** + * Return the selected node query string values. + */ + public queryStringValues(): { selectedNode: string[] } { + const urlSearchParams = new URLSearchParams(this.history.location.search); + return { + selectedNode: urlSearchParams.getAll(`resolver-${this.resolverComponentInstanceID}-id`), + }; + } + + /** + * The element that shows when Resolver is waiting for the graph data. + */ + public graphLoadingElement(): ReactWrapper { + return this.findInDOM('[data-test-subj="resolver:graph:loading"]'); + } + + /** + * The element that shows if Resolver couldn't draw the graph. + */ + public graphErrorElement(): ReactWrapper { + return this.findInDOM('[data-test-subj="resolver:graph:error"]'); + } + + /** + * The element where nodes get drawn. + */ + public graphElement(): ReactWrapper { + return this.findInDOM('[data-test-subj="resolver:graph"]'); + } + + /** + * Like `this.wrapper.find` but only returns DOM nodes. + */ + private findInDOM(selector: string): ReactWrapper { + return this.wrapper.find(selector).filterWhere((wrapper) => typeof wrapper.type() === 'string'); + } +} + +const baseResolverSelector = '[data-test-subj="resolver:node"]'; + +interface ProcessNodeElementSelectorOptions { + /** + * Entity ID of the node. If passed, will be used to create an data-attribute CSS selector that should only get the related node element. + */ + entityID?: string; + /** + * If true, only get nodes with an `[aria-selected="true"]` attribute. + */ + selected?: boolean; +} + +/** + * An `enzyme` supported CSS selector for process node elements. + */ +function processNodeElementSelector({ + entityID, + selected = false, +}: ProcessNodeElementSelectorOptions = {}): string { + let selector: string = baseResolverSelector; + if (entityID !== undefined) { + selector += `[data-test-resolver-node-id="${entityID}"]`; + } + if (selected) { + selector += '[aria-selected="true"]'; + } + return selector; +} diff --git a/x-pack/plugins/security_solution/public/resolver/test_utilities/simulator/mock_resolver.tsx b/x-pack/plugins/security_solution/public/resolver/test_utilities/simulator/mock_resolver.tsx new file mode 100644 index 0000000000000..36bb2a5ffc9fe --- /dev/null +++ b/x-pack/plugins/security_solution/public/resolver/test_utilities/simulator/mock_resolver.tsx @@ -0,0 +1,109 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +/* eslint-disable no-duplicate-imports */ +/* eslint-disable react/display-name */ + +import React, { useMemo, useEffect, useState, useCallback } from 'react'; +import { Router } from 'react-router-dom'; +import { I18nProvider } from '@kbn/i18n/react'; +import { Provider } from 'react-redux'; +import { Store } from 'redux'; +import { KibanaContextProvider } from '../../../../../../../src/plugins/kibana_react/public'; +import { CoreStart } from '../../../../../../../src/core/public'; +import { ResolverState, SideEffectSimulator, ResolverProps } from '../../types'; +import { ResolverAction } from '../../store/actions'; +import { ResolverWithoutProviders } from '../../view/resolver_without_providers'; +import { SideEffectContext } from '../../view/side_effect_context'; +import { sideEffectSimulatorFactory } from '../../view/side_effect_simulator_factory'; + +type MockResolverProps = { + /** + * Used to simulate a raster width. Defaults to 1600. + */ + rasterWidth?: number; + /** + * Used to simulate a raster height. Defaults to 1200. + */ + rasterHeight?: number; + /** + * Used for the `KibanaContextProvider` + */ + coreStart: CoreStart; + /** + * Used for `react-router`. + */ + history: React.ComponentProps['history']; + /** Pass a resolver store. See `storeFactory` and `mockDataAccessLayer` */ + store: Store; + /** + * All the props from `ResolverWithoutStore` can be passed. These aren't defaulted to anything (you might want to test what happens when they aren't present.) + */ +} & ResolverProps; + +/** + * This is a mock Resolver component. It is intended to be used with `enzyme` tests via the `Simulator` class. It wraps Resolver in the required providers: + * * `i18n` + * * `Router` using a provided `History` + * * `SideEffectContext.Provider` using side effect simulator it creates + * * `KibanaContextProvider` using a provided `CoreStart` instance + * * `react-redux`'s `Provider` using a provided `Store`. + * + * Resolver needs to measure its size in the DOM. The `SideEffectSimulator` instance can fake the size of an element. + * However in tests, React doesn't have good DOM reconciliation and the root element is often swapped out. When the + * element is replaced, the fake dimensions stop being applied. In order to get around this issue, this component will + * trigger a simulated resize on the root node reference any time it changes. This simulates the layout process a real + * browser would do when an element is attached to the DOM. + */ +export const MockResolver = React.memo((props: MockResolverProps) => { + const [resolverElement, setResolverElement] = useState(null); + + // Get a ref to the underlying Resolver element so we can resize. + // Use a callback function because the underlying DOM node can change. In fact, `enzyme` seems to change it a lot. + const resolverRef = useCallback((element: HTMLDivElement | null) => { + setResolverElement(element); + }, []); + + const simulator: SideEffectSimulator = useMemo(() => sideEffectSimulatorFactory(), []); + + // Resize the Resolver element to match the passed in props. Resolver is size dependent. + useEffect(() => { + if (resolverElement) { + const size: DOMRect = { + width: props.rasterWidth ?? 1600, + height: props.rasterHeight ?? 1200, + x: 0, + y: 0, + bottom: 0, + left: 0, + top: 0, + right: 0, + toJSON() { + return this; + }, + }; + simulator.controls.simulateElementResize(resolverElement, size); + } + }, [props.rasterWidth, props.rasterHeight, simulator.controls, resolverElement]); + + return ( + + + + + + + + + + + + ); +}); diff --git a/x-pack/plugins/security_solution/public/resolver/test_utilities/spy_middleware_factory.ts b/x-pack/plugins/security_solution/public/resolver/test_utilities/spy_middleware_factory.ts new file mode 100644 index 0000000000000..45730531cf467 --- /dev/null +++ b/x-pack/plugins/security_solution/public/resolver/test_utilities/spy_middleware_factory.ts @@ -0,0 +1,58 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ResolverAction } from '../store/actions'; +import { SpyMiddleware, SpyMiddlewareStateActionPair } from '../types'; + +/** + * Return a `SpyMiddleware` to be used in testing. Use `debugActions` to console.log actions and the state they produced. + * For reducer/middleware tests, you can use `actions` to get access to each dispatched action along with the state it produced. + */ +export const spyMiddlewareFactory: () => SpyMiddleware = () => { + const resolvers: Set<(stateActionPair: SpyMiddlewareStateActionPair) => void> = new Set(); + + const actions = async function* actions() { + while (true) { + const promise: Promise = new Promise((resolve) => { + resolvers.add(resolve); + }); + yield await promise; + } + }; + + return { + middleware: (api) => (next) => (action: ResolverAction) => { + // handle the action first so we get the state after the reducer + next(action); + + const state = api.getState(); + + // Resolving these promises may cause code to await the next result. That will add more resolve functions to `resolvers`. + // For this reason, copy all the existing resolvers to an array and clear the set. + const oldResolvers = [...resolvers]; + resolvers.clear(); + for (const resolve of oldResolvers) { + resolve({ action, state }); + } + }, + actions, + debugActions() { + let stop: boolean = false; + (async () => { + for await (const actionStatePair of actions()) { + if (stop) { + break; + } + // eslint-disable-next-line no-console + console.log('action', actionStatePair.action, 'state', actionStatePair.state); + } + })(); + return () => { + stop = true; + }; + }, + }; +}; diff --git a/x-pack/plugins/security_solution/public/resolver/types.ts b/x-pack/plugins/security_solution/public/resolver/types.ts index 856ae2d6240e3..38e0cd0483559 100644 --- a/x-pack/plugins/security_solution/public/resolver/types.ts +++ b/x-pack/plugins/security_solution/public/resolver/types.ts @@ -4,10 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ +/* eslint-disable no-duplicate-imports */ + import { Store } from 'redux'; +import { Middleware, Dispatch } from 'redux'; import { BBox } from 'rbush'; import { ResolverAction } from './store/actions'; -import { ResolverEvent, ResolverRelatedEvents, ResolverTree } from '../../common/endpoint/types'; +import { + ResolverEvent, + ResolverRelatedEvents, + ResolverTree, + ResolverEntityIndex, +} from '../../common/endpoint/types'; /** * Redux state for the Resolver feature. Properties on this interface are populated via multiple reducers using redux's `combineReducers`. @@ -30,21 +38,21 @@ export interface ResolverState { } /** - * Piece of redux state that models an animation for the camera. + * Piece of `redux` state that models an animation for the camera. */ export interface ResolverUIState { /** - * The nodeID for the process that is selected (in the aria-activedescendent sense of being selected.) + * The `nodeID` for the process that is selected (in the `aria-activedescendent` sense of being selected.) */ readonly ariaActiveDescendant: string | null; /** - * nodeID of the selected node + * `nodeID` of the selected node */ readonly selectedNode: string | null; } /** - * Piece of redux state that models an animation for the camera. + * Piece of `redux` state that models an animation for the camera. */ export interface CameraAnimationState { /** @@ -68,7 +76,7 @@ export interface CameraAnimationState { } /** - * The redux state for the `useCamera` hook. + * The `redux` state for the `useCamera` hook. */ export type CameraState = { /** @@ -88,7 +96,7 @@ export type CameraState = { readonly translationNotCountingCurrentPanning: Vector2; /** - * The world coordinates that the pointing device was last over. This is used during mousewheel zoom. + * The world coordinates that the pointing device was last over. This is used during mouse-wheel zoom. */ readonly latestFocusedWorldCoordinates: Vector2 | null; } & ( @@ -135,7 +143,7 @@ export type CameraState = { export type IndexedEntity = IndexedEdgeLineSegment | IndexedProcessNode; /** - * The entity stored in rbush for resolver edge lines. + * The entity stored in `rbush` for resolver edge lines. */ export interface IndexedEdgeLineSegment extends BBox { type: 'edgeLine'; @@ -143,7 +151,7 @@ export interface IndexedEdgeLineSegment extends BBox { } /** - * The entity store in rbush for resolver process nodes. + * The entity store in `rbush` for resolver process nodes. */ export interface IndexedProcessNode extends BBox { type: 'processNode'; @@ -160,7 +168,7 @@ export interface VisibleEntites { } /** - * State for `data` reducer which handles receiving Resolver data from the backend. + * State for `data` reducer which handles receiving Resolver data from the back-end. */ export interface DataState { readonly relatedEvents: Map; @@ -213,11 +221,11 @@ export type Vector2 = readonly [number, number]; */ export interface AABB { /** - * Vector who's `x` component is the _left_ side of the AABB and who's `y` component is the _bottom_ side of the AABB. + * Vector who's `x` component is the _left_ side of the `AABB` and who's `y` component is the _bottom_ side of the `AABB`. **/ readonly minimum: Vector2; /** - * Vector who's `x` component is the _right_ side of the AABB and who's `y` component is the _bottom_ side of the AABB. + * Vector who's `x` component is the _right_ side of the `AABB` and who's `y` component is the _bottom_ side of the `AABB`. **/ readonly maximum: Vector2; } @@ -266,7 +274,7 @@ export interface ProcessEvent { } /** - * A represention of a process tree with indices for O(1) access to children and values by id. + * A representation of a process tree with indices for O(1) access to children and values by id. */ export interface IndexedProcessTree { /** @@ -280,7 +288,7 @@ export interface IndexedProcessTree { } /** - * A map of ProcessEvents (representing process nodes) to the 'width' of their subtrees as calculated by `widthsOfProcessSubtrees` + * A map of `ProcessEvents` (representing process nodes) to the 'width' of their subtrees as calculated by `widthsOfProcessSubtrees` */ export type ProcessWidths = Map; /** @@ -310,7 +318,7 @@ export type DurationTypes = * duration value and description string */ export interface DurationDetails { - duration: number; + duration: number | '<1'; durationType: DurationTypes; } /** @@ -318,16 +326,16 @@ export interface DurationDetails { */ export interface EdgeLineMetadata { elapsedTime?: DurationDetails; - // A string of the two joined process nodes concatted together. + // A string of the two joined process nodes concatenated together. uniqueId: string; } /** - * A tuple of 2 vector2 points forming a polyline. Used to connect process nodes in the graph. + * A tuple of 2 vector2 points forming a poly-line. Used to connect process nodes in the graph. */ export type EdgeLinePoints = Vector2[]; /** - * Edge line components including the points joining the edgeline and any optional associated metadata + * Edge line components including the points joining the edge-line and any optional associated metadata */ export interface EdgeLineSegment { points: EdgeLinePoints; @@ -335,7 +343,7 @@ export interface EdgeLineSegment { } /** - * Used to provide precalculated info from `widthsOfProcessSubtrees`. These 'width' values are used in the layout of the graph. + * Used to provide pre-calculated info from `widthsOfProcessSubtrees`. These 'width' values are used in the layout of the graph. */ export type ProcessWithWidthMetadata = { process: ResolverEvent; @@ -423,11 +431,11 @@ export type ResolverStore = Store; */ export interface IsometricTaxiLayout { /** - * A map of events to position. each event represents its own node. + * A map of events to position. Each event represents its own node. */ processNodePositions: Map; /** - * A map of edgline segments, which graphically connect nodes. + * A map of edge-line segments, which graphically connect nodes. */ edgeLineSegments: EdgeLineSegment[]; @@ -436,3 +444,91 @@ export interface IsometricTaxiLayout { */ ariaLevels: Map; } + +/** + * An object with methods that can be used to access data from the Kibana server. + * This is injected into Resolver. + * This allows tests to provide a mock data access layer. + * In the future, other implementations of Resolver could provide different data access layers. + */ +export interface DataAccessLayer { + /** + * Fetch related events for an entity ID + */ + relatedEvents: (entityID: string) => Promise; + + /** + * Fetch a ResolverTree for a entityID + */ + resolverTree: (entityID: string, signal: AbortSignal) => Promise; + + /** + * Get an array of index patterns that contain events. + */ + indexPatterns: () => string[]; + + /** + * Get entities matching a document. + */ + entities: (parameters: { + /** _id of the document to find an entity in. */ + _id: string; + /** indices to search in */ + indices: string[]; + /** signal to abort the request */ + signal: AbortSignal; + }) => Promise; +} + +/** + * The externally provided React props. + */ +export interface ResolverProps { + /** + * Used by `styled-components`. + */ + className?: string; + /** + * The `_id` value of an event in ES. + * Used as the origin of the Resolver graph. + */ + databaseDocumentID?: string; + /** + * A string literal describing where in the application resolver is located. + * Used to prevent collisions in things like query parameters. + */ + resolverComponentInstanceID: string; +} + +/** + * Used by `SpyMiddleware`. + */ +export interface SpyMiddlewareStateActionPair { + /** An action dispatched, `state` is the state that the reducer returned when handling this action. + */ + action: ResolverAction; + /** + * A resolver state that was returned by the reducer when handling `action`. + */ + state: ResolverState; +} + +/** + * A wrapper object that has a middleware along with an async generator that returns the actions dispatched to the store (along with state.) + */ +export interface SpyMiddleware { + /** + * A middleware to use with `applyMiddleware`. + */ + middleware: Middleware<{}, ResolverState, Dispatch>; + /** + * A generator that returns all state and action pairs that pass through the middleware. + */ + actions: () => AsyncGenerator; + + /** + * Prints actions to the console. + * Call the returned function to stop debugging. + */ + debugActions: () => () => void; +} diff --git a/x-pack/plugins/security_solution/public/resolver/view/clickthrough.test.tsx b/x-pack/plugins/security_solution/public/resolver/view/clickthrough.test.tsx new file mode 100644 index 0000000000000..9cb900736677e --- /dev/null +++ b/x-pack/plugins/security_solution/public/resolver/view/clickthrough.test.tsx @@ -0,0 +1,99 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { oneAncestorTwoChildren } from '../data_access_layer/mocks/one_ancestor_two_children'; +import { Simulator } from '../test_utilities/simulator'; +// Extend jest with a custom matcher +import '../test_utilities/extend_jest'; + +describe('Resolver, when analyzing a tree that has 1 ancestor and 2 children', () => { + let simulator: Simulator; + let databaseDocumentID: string; + let entityIDs: { origin: string; firstChild: string; secondChild: string }; + + // the resolver component instance ID, used by the react code to distinguish piece of global state from those used by other resolver instances + const resolverComponentInstanceID = 'resolverComponentInstanceID'; + + beforeEach(async () => { + // create a mock data access layer + const { metadata: dataAccessLayerMetadata, dataAccessLayer } = oneAncestorTwoChildren(); + + // save a reference to the entity IDs exposed by the mock data layer + entityIDs = dataAccessLayerMetadata.entityIDs; + + // save a reference to the `_id` supported by the mock data layer + databaseDocumentID = dataAccessLayerMetadata.databaseDocumentID; + + // create a resolver simulator, using the data access layer and an arbitrary component instance ID + simulator = new Simulator({ databaseDocumentID, dataAccessLayer, resolverComponentInstanceID }); + }); + + describe('when it has loaded', () => { + beforeEach(async () => { + await expect( + /** + * It's important that all of these are done in a single `expect`. + * If you do them concurrently with each other, you'll have incorrect results. + * + * For example, there might be no loading element at one point, and 1 graph element at one point, but never a single time when there is both 1 graph element and 0 loading elements. + */ + simulator.mapStateTransitions(() => ({ + graphElements: simulator.graphElement().length, + graphLoadingElements: simulator.graphLoadingElement().length, + graphErrorElements: simulator.graphErrorElement().length, + })) + ).toYieldEqualTo({ + // it should have 1 graph element, an no error or loading elements. + graphElements: 1, + graphLoadingElements: 0, + graphErrorElements: 0, + }); + }); + + // Combining assertions here for performance. Unfortunately, Enzyme + jsdom + React is slow. + it(`should have 3 nodes, with the entityID's 'origin', 'firstChild', and 'secondChild'. 'origin' should be selected.`, async () => { + expect(simulator.processNodeElementLooksSelected(entityIDs.origin)).toBe(true); + + expect(simulator.processNodeElementLooksUnselected(entityIDs.firstChild)).toBe(true); + expect(simulator.processNodeElementLooksUnselected(entityIDs.secondChild)).toBe(true); + + expect(simulator.processNodeElements().length).toBe(3); + }); + + describe("when the second child node's first button has been clicked", () => { + beforeEach(() => { + // Click the first button under the second child element. + simulator + .processNodeElements({ entityID: entityIDs.secondChild }) + .find('button') + .simulate('click'); + }); + it('should render the second child node as selected, and the first child not as not selected, and the query string should indicate that the second child is selected', async () => { + await expect( + simulator.mapStateTransitions(function value() { + return { + // the query string has a key showing that the second child is selected + queryStringSelectedNode: simulator.queryStringValues().selectedNode, + // the second child is rendered in the DOM, and shows up as selected + secondChildLooksSelected: simulator.processNodeElementLooksSelected( + entityIDs.secondChild + ), + // the origin is in the DOM, but shows up as unselected + originLooksUnselected: simulator.processNodeElementLooksUnselected(entityIDs.origin), + }; + }) + ).toYieldEqualTo({ + // Just the second child should be marked as selected in the query string + queryStringSelectedNode: [entityIDs.secondChild], + // The second child is rendered and has `[aria-selected]` + secondChildLooksSelected: true, + // The origin child is rendered and doesn't have `[aria-selected]` + originLooksUnselected: true, + }); + }); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/resolver/view/edge_line.tsx b/x-pack/plugins/security_solution/public/resolver/view/edge_line.tsx index 65c70f94432c7..9f310bb1cc0d6 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/edge_line.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/edge_line.tsx @@ -45,7 +45,7 @@ const StyledElapsedTime = styled.div` left: ${(props) => `${props.leftPct}%`}; padding: 6px 8px; border-radius: 999px; // generate pill shape - transform: translate(-50%, -50%) rotateX(35deg); + transform: translate(-50%, -50%); user-select: none; `; diff --git a/x-pack/plugins/security_solution/public/resolver/view/index.tsx b/x-pack/plugins/security_solution/public/resolver/view/index.tsx index c1ffa42d02abb..d9a0bf291d0e4 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/index.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/index.tsx @@ -7,50 +7,29 @@ import React, { useMemo } from 'react'; import { Provider } from 'react-redux'; -import { ResolverMap } from './map'; import { storeFactory } from '../store'; import { StartServices } from '../../types'; import { useKibana } from '../../../../../../src/plugins/kibana_react/public'; +import { DataAccessLayer, ResolverProps } from '../types'; +import { dataAccessLayerFactory } from '../data_access_layer/factory'; +import { ResolverWithoutProviders } from './resolver_without_providers'; /** - * The top level, unconnected, Resolver component. + * The `Resolver` component to use. This sets up the DataAccessLayer provider. Use `ResolverWithoutProviders` in tests or in other scenarios where you want to provide a different (or fake) data access layer. */ -export const Resolver = React.memo(function ({ - className, - databaseDocumentID, - resolverComponentInstanceID, -}: { - /** - * Used by `styled-components`. - */ - className?: string; - /** - * The `_id` value of an event in ES. - * Used as the origin of the Resolver graph. - */ - databaseDocumentID?: string; - /** - * A string literal describing where in the app resolver is located, - * used to prevent collisions in things like query params - */ - resolverComponentInstanceID: string; -}) { +export const Resolver = React.memo((props: ResolverProps) => { const context = useKibana(); + const dataAccessLayer: DataAccessLayer = useMemo(() => dataAccessLayerFactory(context), [ + context, + ]); + const store = useMemo(() => { - return storeFactory(context); - }, [context]); + return storeFactory(dataAccessLayer); + }, [dataAccessLayer]); - /** - * Setup the store and use `Provider` here. This allows the ResolverMap component to - * dispatch actions and read from state. - */ return ( - + ); }); diff --git a/x-pack/plugins/security_solution/public/resolver/view/map.tsx b/x-pack/plugins/security_solution/public/resolver/view/map.tsx index 69ff9c8e2351b..0ca71c5bf60ce 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/map.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/map.tsx @@ -10,6 +10,7 @@ import React, { useContext } from 'react'; import { useSelector } from 'react-redux'; +import { useEffectOnce } from 'react-use'; import { EuiLoadingSpinner } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import * as selectors from '../store/selectors'; @@ -19,6 +20,7 @@ import { ProcessEventDot } from './process_event_dot'; import { useCamera } from './use_camera'; import { SymbolDefinitions, useResolverTheme } from './assets'; import { useStateSyncingActions } from './use_state_syncing_actions'; +import { useResolverQueryParams } from './use_resolver_query_params'; import { StyledMapContainer, StyledPanel, GraphContainer } from './styles'; import { entityId } from '../../../common/endpoint/models/event'; import { SideEffectContext } from './side_effect_context'; @@ -66,6 +68,11 @@ export const ResolverMap = React.memo(function ({ const hasError = useSelector(selectors.hasError); const activeDescendantId = useSelector(selectors.ariaActiveDescendant); const { colorMap } = useResolverTheme(); + const { cleanUpQueryParams } = useResolverQueryParams(); + + useEffectOnce(() => { + return () => cleanUpQueryParams(); + }); return ( diff --git a/x-pack/plugins/security_solution/public/resolver/view/panel.tsx b/x-pack/plugins/security_solution/public/resolver/view/panel.tsx index cb0acdc29ceb1..83d3930065da6 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panel.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panel.tsx @@ -162,19 +162,10 @@ const PanelContent = memo(function PanelContent() { return 'processListWithCounts'; }, [uiSelectedEvent, crumbEvent, crumbId, graphableProcessEntityIds]); - const terminatedProcesses = useSelector(selectors.terminatedProcesses); - const processEntityId = uiSelectedEvent ? event.entityId(uiSelectedEvent) : undefined; - const isProcessTerminated = processEntityId ? terminatedProcesses.has(processEntityId) : false; - const panelInstance = useMemo(() => { if (panelToShow === 'processDetails') { return ( - + ); } @@ -213,13 +204,7 @@ const PanelContent = memo(function PanelContent() { ); } // The default 'Event List' / 'List of all processes' view - return ( - - ); + return ; }, [ uiSelectedEvent, crumbEvent, @@ -227,7 +212,6 @@ const PanelContent = memo(function PanelContent() { pushToQueryParams, relatedStatsForIdFromParams, panelToShow, - isProcessTerminated, ]); return <>{panelInstance}; diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_process_detail.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_process_detail.tsx index 5d90cd11d31af..7b5eb13359dbb 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_process_detail.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_process_detail.tsx @@ -1,187 +1,184 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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, useMemo } from 'react'; -import { i18n } from '@kbn/i18n'; -import { - htmlIdGenerator, - EuiSpacer, - EuiTitle, - EuiText, - EuiTextColor, - EuiDescriptionList, -} from '@elastic/eui'; -import styled from 'styled-components'; -import { FormattedMessage } from 'react-intl'; -import * as event from '../../../../common/endpoint/models/event'; -import { CrumbInfo, formatDate, StyledBreadcrumbs } from './panel_content_utilities'; -import { - processPath, - processPid, - userInfoForProcess, - processParentPid, - md5HashForProcess, - argsForProcess, -} from '../../models/process_event'; -import { CubeForProcess } from './process_cube_icon'; -import { ResolverEvent } from '../../../../common/endpoint/types'; -import { useResolverTheme } from '../assets'; - -const StyledDescriptionList = styled(EuiDescriptionList)` - &.euiDescriptionList.euiDescriptionList--column dt.euiDescriptionList__title.desc-title { - max-width: 10em; - } -`; - -/** - * A description list view of all the Metadata that goes with a particular process event, like: - * Created, Pid, User/Domain, etc. - */ -export const ProcessDetails = memo(function ProcessDetails({ - processEvent, - isProcessTerminated, - isProcessOrigin, - pushToQueryParams, -}: { - processEvent: ResolverEvent; - isProcessTerminated: boolean; - isProcessOrigin: boolean; - pushToQueryParams: (queryStringKeyValuePair: CrumbInfo) => unknown; -}) { - const processName = event.eventName(processEvent); - const processInfoEntry = useMemo(() => { - const eventTime = event.eventTimestamp(processEvent); - const dateTime = eventTime ? formatDate(eventTime) : ''; - - const createdEntry = { - title: '@timestamp', - description: dateTime, - }; - - const pathEntry = { - title: 'process.executable', - description: processPath(processEvent), - }; - - const pidEntry = { - title: 'process.pid', - description: processPid(processEvent), - }; - - const userEntry = { - title: 'user.name', - description: (userInfoForProcess(processEvent) as { name: string }).name, - }; - - const domainEntry = { - title: 'user.domain', - description: (userInfoForProcess(processEvent) as { domain: string }).domain, - }; - - const parentPidEntry = { - title: 'process.parent.pid', - description: processParentPid(processEvent), - }; - - const md5Entry = { - title: 'process.hash.md5', - description: md5HashForProcess(processEvent), - }; - - const commandLineEntry = { - title: 'process.args', - description: argsForProcess(processEvent), - }; - - // This is the data in {title, description} form for the EUIDescriptionList to display - const processDescriptionListData = [ - createdEntry, - pathEntry, - pidEntry, - userEntry, - domainEntry, - parentPidEntry, - md5Entry, - commandLineEntry, - ] - .filter((entry) => { - return entry.description; - }) - .map((entry) => { - return { - ...entry, - description: String(entry.description), - }; - }); - - return processDescriptionListData; - }, [processEvent]); - - const crumbs = useMemo(() => { - return [ - { - text: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.panel.processDescList.events', - { - defaultMessage: 'Events', - } - ), - onClick: () => { - pushToQueryParams({ crumbId: '', crumbEvent: '' }); - }, - }, - { - text: ( - <> - - - ), - onClick: () => {}, - }, - ]; - }, [processName, pushToQueryParams]); - const { cubeAssetsForNode } = useResolverTheme(); - const { descriptionText } = useMemo(() => { - if (!processEvent) { - return { descriptionText: '' }; - } - return cubeAssetsForNode(isProcessTerminated, isProcessOrigin); - }, [processEvent, cubeAssetsForNode, isProcessTerminated, isProcessOrigin]); - - const titleId = useMemo(() => htmlIdGenerator('resolverTable')(), []); - return ( - <> - - - -

- - {processName} -

-
- - - {descriptionText} - - - - - - ); -}); -ProcessDetails.displayName = 'ProcessDetails'; +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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, useMemo } from 'react'; +import { useSelector } from 'react-redux'; +import { i18n } from '@kbn/i18n'; +import { + htmlIdGenerator, + EuiSpacer, + EuiTitle, + EuiText, + EuiTextColor, + EuiDescriptionList, +} from '@elastic/eui'; +import styled from 'styled-components'; +import { FormattedMessage } from 'react-intl'; +import * as selectors from '../../store/selectors'; +import * as event from '../../../../common/endpoint/models/event'; +import { CrumbInfo, formatDate, StyledBreadcrumbs } from './panel_content_utilities'; +import { + processPath, + processPid, + userInfoForProcess, + processParentPid, + md5HashForProcess, + argsForProcess, +} from '../../models/process_event'; +import { CubeForProcess } from './process_cube_icon'; +import { ResolverEvent } from '../../../../common/endpoint/types'; +import { useResolverTheme } from '../assets'; + +const StyledDescriptionList = styled(EuiDescriptionList)` + &.euiDescriptionList.euiDescriptionList--column dt.euiDescriptionList__title.desc-title { + max-width: 10em; + } +`; + +/** + * A description list view of all the Metadata that goes with a particular process event, like: + * Created, PID, User/Domain, etc. + */ +export const ProcessDetails = memo(function ProcessDetails({ + processEvent, + pushToQueryParams, +}: { + processEvent: ResolverEvent; + pushToQueryParams: (queryStringKeyValuePair: CrumbInfo) => unknown; +}) { + const processName = event.eventName(processEvent); + const entityId = event.entityId(processEvent); + const isProcessTerminated = useSelector(selectors.isProcessTerminated)(entityId); + const processInfoEntry = useMemo(() => { + const eventTime = event.eventTimestamp(processEvent); + const dateTime = eventTime ? formatDate(eventTime) : ''; + + const createdEntry = { + title: '@timestamp', + description: dateTime, + }; + + const pathEntry = { + title: 'process.executable', + description: processPath(processEvent), + }; + + const pidEntry = { + title: 'process.pid', + description: processPid(processEvent), + }; + + const userEntry = { + title: 'user.name', + description: userInfoForProcess(processEvent)?.name, + }; + + const domainEntry = { + title: 'user.domain', + description: userInfoForProcess(processEvent)?.domain, + }; + + const parentPidEntry = { + title: 'process.parent.pid', + description: processParentPid(processEvent), + }; + + const md5Entry = { + title: 'process.hash.md5', + description: md5HashForProcess(processEvent), + }; + + const commandLineEntry = { + title: 'process.args', + description: argsForProcess(processEvent), + }; + + // This is the data in {title, description} form for the EUIDescriptionList to display + const processDescriptionListData = [ + createdEntry, + pathEntry, + pidEntry, + userEntry, + domainEntry, + parentPidEntry, + md5Entry, + commandLineEntry, + ] + .filter((entry) => { + return entry.description; + }) + .map((entry) => { + return { + ...entry, + description: String(entry.description), + }; + }); + + return processDescriptionListData; + }, [processEvent]); + + const crumbs = useMemo(() => { + return [ + { + text: i18n.translate( + 'xpack.securitySolution.endpoint.resolver.panel.processDescList.events', + { + defaultMessage: 'Events', + } + ), + onClick: () => { + pushToQueryParams({ crumbId: '', crumbEvent: '' }); + }, + }, + { + text: ( + <> + + + ), + onClick: () => {}, + }, + ]; + }, [processName, pushToQueryParams]); + const { cubeAssetsForNode } = useResolverTheme(); + const { descriptionText } = useMemo(() => { + if (!processEvent) { + return { descriptionText: '' }; + } + return cubeAssetsForNode(isProcessTerminated, false); + }, [processEvent, cubeAssetsForNode, isProcessTerminated]); + + const titleId = useMemo(() => htmlIdGenerator('resolverTable')(), []); + return ( + <> + + + +

+ + {processName} +

+
+ + + {descriptionText} + + + + + + ); +}); +ProcessDetails.displayName = 'ProcessDetails'; diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_process_list.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_process_list.tsx index 6f9bfad8c08c2..efb96cde431e5 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_process_list.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_process_list.tsx @@ -50,12 +50,8 @@ const StyledLimitWarning = styled(LimitWarning)` */ export const ProcessListWithCounts = memo(function ProcessListWithCounts({ pushToQueryParams, - isProcessTerminated, - isProcessOrigin, }: { pushToQueryParams: (queryStringKeyValuePair: CrumbInfo) => unknown; - isProcessTerminated: boolean; - isProcessOrigin: boolean; }) { interface ProcessTableView { name: string; @@ -65,6 +61,7 @@ export const ProcessListWithCounts = memo(function ProcessListWithCounts({ const dispatch = useResolverDispatch(); const { timestamp } = useContext(SideEffectContext); + const isProcessTerminated = useSelector(selectors.isProcessTerminated); const handleBringIntoViewClick = useCallback( (processTableViewItem) => { dispatch({ @@ -92,6 +89,8 @@ export const ProcessListWithCounts = memo(function ProcessListWithCounts({ sortable: true, truncateText: true, render(name: string, item: ProcessTableView) { + const entityId = event.entityId(item.event); + const isTerminated = isProcessTerminated(entityId); return name === '' ? ( {i18n.translate( @@ -108,10 +107,7 @@ export const ProcessListWithCounts = memo(function ProcessListWithCounts({ pushToQueryParams({ crumbId: event.entityId(item.event), crumbEvent: '' }); }} > - + {name}
); @@ -143,7 +139,7 @@ export const ProcessListWithCounts = memo(function ProcessListWithCounts({ }, }, ], - [pushToQueryParams, handleBringIntoViewClick, isProcessOrigin, isProcessTerminated] + [pushToQueryParams, handleBringIntoViewClick, isProcessTerminated] ); const { processNodePositions } = useSelector(selectors.layout); diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/process_cube_icon.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/process_cube_icon.tsx index 98eea51a011b6..b073324b27f9b 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/process_cube_icon.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/process_cube_icon.tsx @@ -13,13 +13,11 @@ import { useResolverTheme } from '../assets'; */ export const CubeForProcess = memo(function CubeForProcess({ isProcessTerminated, - isProcessOrigin, }: { isProcessTerminated: boolean; - isProcessOrigin: boolean; }) { const { cubeAssetsForNode } = useResolverTheme(); - const { cubeSymbol, descriptionText } = cubeAssetsForNode(isProcessTerminated, isProcessOrigin); + const { cubeSymbol, descriptionText } = cubeAssetsForNode(isProcessTerminated, false); return ( <> diff --git a/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx b/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx index 05f2e0cbfcfa9..24de45ee894dc 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 @@ -195,7 +195,7 @@ const UnstyledProcessEventDot = React.memo( * `beginElement` is by [w3](https://www.w3.org/TR/SVG11/animate.html#__smil__ElementTimeControl__beginElement) * but missing in [TSJS-lib-generator](https://github.com/microsoft/TSJS-lib-generator/blob/15a4678e0ef6de308e79451503e444e9949ee849/inputfiles/addedTypes.json#L1819) */ - beginElement: () => void; + beginElement?: () => void; }) | null; } = React.createRef(); @@ -238,10 +238,8 @@ const UnstyledProcessEventDot = React.memo( const { pushToQueryParams } = useResolverQueryParams(); const handleClick = useCallback(() => { - if (animationTarget.current !== null) { - // This works but the types are missing in the typescript DOM lib - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (animationTarget.current as any).beginElement(); + if (animationTarget.current?.beginElement) { + animationTarget.current.beginElement(); } dispatch({ type: 'userSelectedResolverNode', @@ -297,7 +295,8 @@ const UnstyledProcessEventDot = React.memo( */ return (
{ + handleFocus(); + handleClick(); + } /* a11y note: this is strictly an alternate to the button, so no tabindex is necessary*/ + } + role="img" + aria-labelledby={labelHTMLID} style={{ display: 'block', width: '100%', @@ -320,6 +327,8 @@ const UnstyledProcessEventDot = React.memo( position: 'absolute', top: '0', left: '0', + outline: 'transparent', + border: 'none', }} > 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 new file mode 100644 index 0000000000000..f444d5a25e1ef --- /dev/null +++ b/x-pack/plugins/security_solution/public/resolver/view/resolver_without_providers.tsx @@ -0,0 +1,139 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +/* eslint-disable no-duplicate-imports */ + +/* eslint-disable react/display-name */ + +import React, { useContext, useCallback } from 'react'; +import { useSelector } from 'react-redux'; +import { useEffectOnce } from 'react-use'; +import { EuiLoadingSpinner } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import * as selectors from '../store/selectors'; +import { EdgeLine } from './edge_line'; +import { GraphControls } from './graph_controls'; +import { ProcessEventDot } from './process_event_dot'; +import { useCamera } from './use_camera'; +import { SymbolDefinitions, useResolverTheme } from './assets'; +import { useStateSyncingActions } from './use_state_syncing_actions'; +import { useResolverQueryParams } from './use_resolver_query_params'; +import { StyledMapContainer, StyledPanel, GraphContainer } from './styles'; +import { entityId } from '../../../common/endpoint/models/event'; +import { SideEffectContext } from './side_effect_context'; +import { ResolverProps } from '../types'; + +/** + * The highest level connected Resolver component. Needs a `Provider` in its ancestry to work. + */ +export const ResolverWithoutProviders = React.memo( + /** + * Use `forwardRef` so that the `Simulator` used in testing can access the top level DOM element. + */ + React.forwardRef(function ( + { className, databaseDocumentID, resolverComponentInstanceID }: ResolverProps, + refToForward + ) { + /** + * This is responsible for dispatching actions that include any external data. + * `databaseDocumentID` + */ + useStateSyncingActions({ databaseDocumentID, resolverComponentInstanceID }); + + const { timestamp } = useContext(SideEffectContext); + + // use this for the entire render in order to keep things in sync + const timeAtRender = timestamp(); + + const { processNodePositions, connectingEdgeLineSegments } = useSelector( + selectors.visibleNodesAndEdgeLines + )(timeAtRender); + const terminatedProcesses = useSelector(selectors.terminatedProcesses); + const { projectionMatrix, ref: cameraRef, onMouseDown } = useCamera(); + + const ref = useCallback( + (element: HTMLDivElement | null) => { + // Supply `useCamera` with the ref + cameraRef(element); + + // If a ref is being forwarded, populate that as well. + if (typeof refToForward === 'function') { + refToForward(element); + } else if (refToForward !== null) { + refToForward.current = element; + } + }, + [cameraRef, refToForward] + ); + const isLoading = useSelector(selectors.isLoading); + const hasError = useSelector(selectors.hasError); + const activeDescendantId = useSelector(selectors.ariaActiveDescendant); + const { colorMap } = useResolverTheme(); + const { cleanUpQueryParams } = useResolverQueryParams(); + + useEffectOnce(() => { + return () => cleanUpQueryParams(); + }); + + return ( + + {isLoading ? ( +
+ +
+ ) : hasError ? ( +
+
+ {' '} + +
+
+ ) : ( + + {connectingEdgeLineSegments.map( + ({ points: [startPosition, endPosition], metadata }) => ( + + ) + )} + {[...processNodePositions].map(([processEvent, position]) => { + const processEntityId = entityId(processEvent); + return ( + + ); + })} + + )} + + + +
+ ); + }) +); diff --git a/x-pack/plugins/security_solution/public/resolver/view/side_effect_simulator.ts b/x-pack/plugins/security_solution/public/resolver/view/side_effect_simulator_factory.ts similarity index 95% rename from x-pack/plugins/security_solution/public/resolver/view/side_effect_simulator.ts rename to x-pack/plugins/security_solution/public/resolver/view/side_effect_simulator_factory.ts index 5e9073ba2d3c9..25be222e2fe4a 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/side_effect_simulator.ts +++ b/x-pack/plugins/security_solution/public/resolver/view/side_effect_simulator_factory.ts @@ -11,12 +11,13 @@ import { SideEffectSimulator } from '../types'; * Create mock `SideEffectors` for `SideEffectContext.Provider`. The `control` * object is used to control the mocks. */ -export const sideEffectSimulator: () => SideEffectSimulator = () => { +export const sideEffectSimulatorFactory: () => SideEffectSimulator = () => { // The set of mock `ResizeObserver` instances that currently exist const resizeObserverInstances: Set = new Set(); // A map of `Element`s to their fake `DOMRect`s - const contentRects: Map = new Map(); + // Use a `WeakMap` since elements can be removed from the DOM. + const contentRects: WeakMap = new Map(); /** * Simulate an element's size changing. This will trigger any `ResizeObserverCallback`s which 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 2499a451b9c8c..6a9ab184e9bab 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/submenu.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/submenu.tsx @@ -190,7 +190,7 @@ const NodeSubMenuComponents = React.memo( * then force the popover to reposition itself. */ popoverRef.current && - !projectionMatrixAtLastRender.current && + projectionMatrixAtLastRender.current && projectionMatrixAtLastRender.current !== projectionMatrix ) { popoverRef.current.positionPopoverFixed(); diff --git a/x-pack/plugins/security_solution/public/resolver/view/use_camera.test.tsx b/x-pack/plugins/security_solution/public/resolver/view/use_camera.test.tsx index a27f157bc9364..b32d63283b547 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/use_camera.test.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/use_camera.test.tsx @@ -10,15 +10,16 @@ import { renderHook, act as hooksAct } from '@testing-library/react-hooks'; import { useCamera, useAutoUpdatingClientRect } from './use_camera'; import { Provider } from 'react-redux'; import * as selectors from '../store/selectors'; -import { storeFactory } from '../store'; import { Matrix3, ResolverStore, SideEffectSimulator } from '../types'; import { ResolverEvent } from '../../../common/endpoint/types'; import { SideEffectContext } from './side_effect_context'; import { applyMatrix3 } from '../models/vector2'; -import { sideEffectSimulator } from './side_effect_simulator'; +import { sideEffectSimulatorFactory } from './side_effect_simulator_factory'; import { mockProcessEvent } from '../models/process_event_test_helpers'; import { mock as mockResolverTree } from '../models/resolver_tree'; import { ResolverAction } from '../store/actions'; +import { createStore } from 'redux'; +import { resolverReducer } from '../store/reducer'; describe('useCamera on an unpainted element', () => { let element: HTMLElement; @@ -29,7 +30,7 @@ describe('useCamera on an unpainted element', () => { let simulator: SideEffectSimulator; beforeEach(async () => { - store = storeFactory(); + store = createStore(resolverReducer); const Test = function Test() { const camera = useCamera(); @@ -38,7 +39,7 @@ describe('useCamera on an unpainted element', () => { return
; }; - simulator = sideEffectSimulator(); + simulator = sideEffectSimulatorFactory(); reactRenderResult = render( diff --git a/x-pack/plugins/security_solution/public/resolver/view/use_resolver_query_params.ts b/x-pack/plugins/security_solution/public/resolver/view/use_resolver_query_params.ts index 3c342ae575aa0..ed514a61d4e06 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/use_resolver_query_params.ts +++ b/x-pack/plugins/security_solution/public/resolver/view/use_resolver_query_params.ts @@ -20,12 +20,12 @@ export function useResolverQueryParams() { const history = useHistory(); const urlSearch = useLocation().search; const resolverComponentInstanceID = useSelector(selectors.resolverComponentInstanceID); - const uniqueCrumbIdKey: string = `resolver-id:${resolverComponentInstanceID}`; - const uniqueCrumbEventKey: string = `resolver-event:${resolverComponentInstanceID}`; + const uniqueCrumbIdKey: string = `resolver-${resolverComponentInstanceID}-id`; + const uniqueCrumbEventKey: string = `resolver-${resolverComponentInstanceID}-event`; const pushToQueryParams = useCallback( (newCrumbs: CrumbInfo) => { - // Construct a new set of params from the current set (minus empty params) - // by assigning the new set of params provided in `newCrumbs` + // Construct a new set of parameters from the current set (minus empty parameters) + // by assigning the new set of parameters provided in `newCrumbs` const crumbsToPass = { ...querystring.parse(urlSearch.slice(1)), [uniqueCrumbIdKey]: newCrumbs.crumbId, @@ -63,8 +63,19 @@ export function useResolverQueryParams() { }; }, [urlSearch, uniqueCrumbIdKey, uniqueCrumbEventKey]); + const cleanUpQueryParams = () => { + const crumbsToPass = { + ...querystring.parse(urlSearch.slice(1)), + }; + delete crumbsToPass[uniqueCrumbIdKey]; + delete crumbsToPass[uniqueCrumbEventKey]; + const relativeURL = { search: querystring.stringify(crumbsToPass) }; + history.replace(relativeURL); + }; + return { pushToQueryParams, queryParams, + cleanUpQueryParams, }; } diff --git a/x-pack/plugins/security_solution/public/shared_imports.ts b/x-pack/plugins/security_solution/public/shared_imports.ts index 9939345324f11..b2c7319b94576 100644 --- a/x-pack/plugins/security_solution/public/shared_imports.ts +++ b/x-pack/plugins/security_solution/public/shared_imports.ts @@ -32,6 +32,7 @@ export { useIsMounted, useCursor, useApi, + useAsync, useExceptionList, usePersistExceptionItem, usePersistExceptionList, @@ -50,4 +51,5 @@ export { Pagination, UseExceptionListSuccess, addEndpointExceptionList, + withOptionalSignal, } from '../../lists/public'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_name.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_name.test.tsx index ddd5c6f07e8b5..2e48215a89473 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_name.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_name.test.tsx @@ -28,6 +28,10 @@ const defaultProps = { }; describe('FieldName', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + test('it renders the field name', () => { const wrapper = mount( @@ -48,6 +52,8 @@ describe('FieldName', () => { ); wrapper.find('[data-test-subj="withHoverActionsButton"]').at(0).simulate('mouseenter'); wrapper.update(); + jest.runAllTimers(); + wrapper.update(); expect(wrapper.find('[data-test-subj="copy-to-clipboard"]').exists()).toBe(true); }); 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 54b30aca44a1f..97d1d11395c7f 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 @@ -13,18 +13,14 @@ import { EuiToolTip, } from '@elastic/eui'; import { noop } from 'lodash/fp'; -import React, { useCallback, useMemo, useState } from 'react'; +import React, { useCallback, useMemo } from 'react'; import { connect, ConnectedProps, useDispatch, useSelector } from 'react-redux'; import styled from 'styled-components'; -import { SecurityPageName } from '../../../app/types'; import { FULL_SCREEN } from '../timeline/body/column_headers/translations'; -import { AllCasesModal } from '../../../cases/components/all_cases_modal'; import { EXIT_FULL_SCREEN } from '../../../common/components/exit_full_screen/translations'; -import { APP_ID, FULL_SCREEN_TOGGLED_CLASS_NAME } from '../../../../common/constants'; +import { FULL_SCREEN_TOGGLED_CLASS_NAME } from '../../../../common/constants'; import { useFullScreen } from '../../../common/containers/use_full_screen'; -import { getCaseDetailsUrl, getCreateCaseUrl } from '../../../common/components/link_to'; -import { useKibana } from '../../../common/lib/kibana'; import { State } from '../../../common/store'; import { TimelineId, TimelineType } from '../../../../common/types/timeline'; import { timelineSelectors } from '../../store/timeline'; @@ -32,12 +28,9 @@ import { timelineDefaults } from '../../store/timeline/defaults'; import { TimelineModel } from '../../store/timeline/model'; import { isFullScreen } from '../timeline/body/column_headers'; import { NewCase, ExistingCase } from '../timeline/properties/helpers'; -import { UNTITLED_TIMELINE } from '../timeline/properties/translations'; -import { - setInsertTimeline, - updateTimelineGraphEventId, -} from '../../../timelines/store/timeline/actions'; +import { updateTimelineGraphEventId } from '../../../timelines/store/timeline/actions'; import { Resolver } from '../../../resolver/view'; +import { useAllCasesModal } from '../../../cases/components/use_all_cases_modal'; import * as i18n from './translations'; @@ -112,35 +105,16 @@ const GraphOverlayComponent = ({ timelineType, }: OwnProps & PropsFromRedux) => { const dispatch = useDispatch(); - const { navigateToApp } = useKibana().services.application; const onCloseOverlay = useCallback(() => { dispatch(updateTimelineGraphEventId({ id: timelineId, graphEventId: '' })); }, [dispatch, timelineId]); - const [showCaseModal, setShowCaseModal] = useState(false); - const onOpenCaseModal = useCallback(() => setShowCaseModal(true), []); - const onCloseCaseModal = useCallback(() => setShowCaseModal(false), [setShowCaseModal]); + const currentTimeline = useSelector((state: State) => timelineSelectors.selectTimeline(state, timelineId) ); - const onRowClick = useCallback( - (id?: string) => { - onCloseCaseModal(); - - navigateToApp(`${APP_ID}:${SecurityPageName.case}`, { - path: id != null ? getCaseDetailsUrl({ id }) : getCreateCaseUrl(), - }).then(() => { - dispatch( - setInsertTimeline({ - graphEventId, - timelineId, - timelineSavedObjectId: currentTimeline.savedObjectId, - timelineTitle: title.length > 0 ? title : UNTITLED_TIMELINE, - }) - ); - }); - }, - [currentTimeline, dispatch, graphEventId, navigateToApp, onCloseCaseModal, timelineId, title] - ); + + const { Modal: AllCasesModal, onOpenModal: onOpenCaseModal } = useAllCasesModal({ timelineId }); + const { timelineFullScreen, setTimelineFullScreen, @@ -210,11 +184,7 @@ const GraphOverlayComponent = ({ databaseDocumentID={graphEventId} resolverComponentInstanceID={currentTimeline.id} /> - + ); }; diff --git a/x-pack/plugins/security_solution/public/timelines/components/manage_timeline/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/manage_timeline/index.test.tsx new file mode 100644 index 0000000000000..b918e5abc652b --- /dev/null +++ b/x-pack/plugins/security_solution/public/timelines/components/manage_timeline/index.test.tsx @@ -0,0 +1,145 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { renderHook, act } from '@testing-library/react-hooks'; +import { getTimelineDefaults, useTimelineManager, UseTimelineManager } from './'; +import { FilterManager } from '../../../../../../../src/plugins/data/public/query/filter_manager'; +import { coreMock } from '../../../../../../../src/core/public/mocks'; +import { TimelineRowAction } from '../timeline/body/actions'; + +const isStringifiedComparisonEqual = (a: {}, b: {}): boolean => + JSON.stringify(a) === JSON.stringify(b); + +describe('useTimelineManager', () => { + const setupMock = coreMock.createSetup(); + const testId = 'coolness'; + const timelineDefaults = getTimelineDefaults(testId); + const timelineRowActions = () => []; + const mockFilterManager = new FilterManager(setupMock.uiSettings); + beforeEach(() => { + jest.clearAllMocks(); + jest.restoreAllMocks(); + }); + it('initilizes an undefined timeline', async () => { + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useTimelineManager() + ); + await waitForNextUpdate(); + const uninitializedTimeline = result.current.getManageTimelineById(testId); + expect(isStringifiedComparisonEqual(uninitializedTimeline, timelineDefaults)).toBeTruthy(); + }); + }); + it('getIndexToAddById', async () => { + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useTimelineManager() + ); + await waitForNextUpdate(); + const data = result.current.getIndexToAddById(testId); + expect(data).toEqual(timelineDefaults.indexToAdd); + }); + }); + it('setIndexToAdd', async () => { + await act(async () => { + const indexToAddArgs = { id: testId, indexToAdd: ['example'] }; + const { result, waitForNextUpdate } = renderHook(() => + useTimelineManager() + ); + await waitForNextUpdate(); + result.current.initializeTimeline({ + id: testId, + timelineRowActions, + }); + result.current.setIndexToAdd(indexToAddArgs); + const data = result.current.getIndexToAddById(testId); + expect(data).toEqual(indexToAddArgs.indexToAdd); + }); + }); + it('setIsTimelineLoading', async () => { + await act(async () => { + const isLoadingArgs = { id: testId, isLoading: true }; + const { result, waitForNextUpdate } = renderHook(() => + useTimelineManager() + ); + await waitForNextUpdate(); + result.current.initializeTimeline({ + id: testId, + timelineRowActions, + }); + let timeline = result.current.getManageTimelineById(testId); + expect(timeline.isLoading).toBeFalsy(); + result.current.setIsTimelineLoading(isLoadingArgs); + timeline = result.current.getManageTimelineById(testId); + expect(timeline.isLoading).toBeTruthy(); + }); + }); + it('setTimelineRowActions', async () => { + await act(async () => { + const timelineRowActionsEx = () => [ + { id: 'wow', content: 'hey', displayType: 'icon', onClick: () => {} } as TimelineRowAction, + ]; + const { result, waitForNextUpdate } = renderHook(() => + useTimelineManager() + ); + await waitForNextUpdate(); + result.current.initializeTimeline({ + id: testId, + timelineRowActions, + }); + let timeline = result.current.getManageTimelineById(testId); + expect(timeline.timelineRowActions).toEqual(timelineRowActions); + result.current.setTimelineRowActions({ + id: testId, + timelineRowActions: timelineRowActionsEx, + }); + timeline = result.current.getManageTimelineById(testId); + expect(timeline.timelineRowActions).toEqual(timelineRowActionsEx); + }); + }); + it('getTimelineFilterManager undefined on uninitialized', async () => { + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useTimelineManager() + ); + await waitForNextUpdate(); + const data = result.current.getTimelineFilterManager(testId); + expect(data).toEqual(undefined); + }); + }); + it('getTimelineFilterManager defined at initialize', async () => { + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useTimelineManager() + ); + await waitForNextUpdate(); + result.current.initializeTimeline({ + id: testId, + timelineRowActions, + filterManager: mockFilterManager, + }); + const data = result.current.getTimelineFilterManager(testId); + expect(data).toEqual(mockFilterManager); + }); + }); + it('isManagedTimeline returns false when unset and then true when set', async () => { + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useTimelineManager() + ); + await waitForNextUpdate(); + let data = result.current.isManagedTimeline(testId); + expect(data).toBeFalsy(); + result.current.initializeTimeline({ + id: testId, + timelineRowActions, + filterManager: mockFilterManager, + }); + data = result.current.isManagedTimeline(testId); + expect(data).toBeTruthy(); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/timelines/components/manage_timeline/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/manage_timeline/index.tsx index dba8506add0ad..a425f9b49add0 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/manage_timeline/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/manage_timeline/index.tsx @@ -137,7 +137,7 @@ const reducerManageTimeline = ( } }; -interface UseTimelineManager { +export interface UseTimelineManager { getIndexToAddById: (id: string) => string[] | null; getManageTimelineById: (id: string) => ManageTimeline; getTimelineFilterManager: (id: string) => FilterManager | undefined; @@ -152,7 +152,9 @@ interface UseTimelineManager { }) => void; } -const useTimelineManager = (manageTimelineForTesting?: ManageTimelineById): UseTimelineManager => { +export const useTimelineManager = ( + manageTimelineForTesting?: ManageTimelineById +): UseTimelineManager => { const [state, dispatch] = useReducer< (state: ManageTimelineById, action: ActionManageTimeline) => ManageTimelineById >(reducerManageTimeline, manageTimelineForTesting ?? initManageTimeline); @@ -241,12 +243,12 @@ const useTimelineManager = (manageTimelineForTesting?: ManageTimelineById): UseT }; const init = { - getManageTimelineById: (id: string) => getTimelineDefaults(id), getIndexToAddById: (id: string) => null, + getManageTimelineById: (id: string) => getTimelineDefaults(id), getTimelineFilterManager: () => undefined, - setIndexToAdd: () => undefined, - isManagedTimeline: () => false, initializeTimeline: () => noop, + isManagedTimeline: () => false, + setIndexToAdd: () => undefined, setIsTimelineLoading: () => noop, setTimelineRowActions: () => noop, }; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.test.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.test.ts index 8ba1a999e2b2a..c8adaa891610a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.test.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.test.ts @@ -6,7 +6,13 @@ import { Ecs } from '../../../../graphql/types'; -import { eventHasNotes, eventIsPinned, getPinTooltip, stringifyEvent } from './helpers'; +import { + eventHasNotes, + eventIsPinned, + getPinTooltip, + stringifyEvent, + isInvestigateInResolverActionEnabled, +} from './helpers'; import { TimelineType } from '../../../../../common/types/timeline'; describe('helpers', () => { @@ -242,4 +248,54 @@ describe('helpers', () => { expect(eventIsPinned({ eventId, pinnedEventIds })).toEqual(false); }); }); + + describe('isInvestigateInResolverActionEnabled', () => { + it('returns false if agent.type does not equal endpoint', () => { + const data: Ecs = { _id: '1', agent: { type: ['blah'] } }; + + expect(isInvestigateInResolverActionEnabled(data)).toBeFalsy(); + }); + + it('returns false if agent.type does not have endpoint in first array index', () => { + const data: Ecs = { _id: '1', agent: { type: ['blah', 'endpoint'] } }; + + expect(isInvestigateInResolverActionEnabled(data)).toBeFalsy(); + }); + + it('returns false if process.entity_id is not defined', () => { + const data: Ecs = { _id: '1', agent: { type: ['endpoint'] } }; + + expect(isInvestigateInResolverActionEnabled(data)).toBeFalsy(); + }); + + it('returns true if agent.type has endpoint in first array index', () => { + const data: Ecs = { + _id: '1', + agent: { type: ['endpoint', 'blah'] }, + process: { entity_id: ['5'] }, + }; + + expect(isInvestigateInResolverActionEnabled(data)).toBeTruthy(); + }); + + it('returns false if multiple entity_ids', () => { + const data: Ecs = { + _id: '1', + agent: { type: ['endpoint', 'blah'] }, + process: { entity_id: ['5', '10'] }, + }; + + expect(isInvestigateInResolverActionEnabled(data)).toBeFalsy(); + }); + + it('returns false if entity_id is an empty string', () => { + const data: Ecs = { + _id: '1', + agent: { type: ['endpoint', 'blah'] }, + process: { entity_id: [''] }, + }; + + expect(isInvestigateInResolverActionEnabled(data)).toBeFalsy(); + }); + }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.ts index 067cea175c99b..6a5e25632c29b 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.ts @@ -106,7 +106,8 @@ export const getEventType = (event: Ecs): Omit => { export const isInvestigateInResolverActionEnabled = (ecsData?: Ecs) => { return ( get(['agent', 'type', 0], ecsData) === 'endpoint' && - get(['process', 'entity_id'], ecsData)?.length > 0 + 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/header/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/header/index.test.tsx index 58c213dc884ea..e7b0ce7b7428e 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/header/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/header/index.test.tsx @@ -85,5 +85,100 @@ describe('Header', () => { expect(wrapper.find('[data-test-subj="timelineCallOutUnauthorized"]').exists()).toEqual(true); }); + + test('it renders the unauthorized call out with correct icon', () => { + const testProps = { + ...props, + filterManager: new FilterManager(mockUiSettingsForFilterManager), + showCallOutUnauthorizedMsg: true, + }; + + const wrapper = mount( + + + + ); + + expect( + wrapper.find('[data-test-subj="timelineCallOutUnauthorized"]').first().prop('iconType') + ).toEqual('alert'); + }); + + test('it renders the unauthorized call out with correct message', () => { + const testProps = { + ...props, + filterManager: new FilterManager(mockUiSettingsForFilterManager), + showCallOutUnauthorizedMsg: true, + }; + + const wrapper = mount( + + + + ); + + expect( + wrapper.find('[data-test-subj="timelineCallOutUnauthorized"]').first().prop('title') + ).toEqual( + 'You can use Timeline to investigate events, but you do not have the required permissions to save timelines for future use. If you need to save timelines, contact your Kibana administrator.' + ); + }); + + test('it renders the immutable timeline call out providers', () => { + const testProps = { + ...props, + filterManager: new FilterManager(mockUiSettingsForFilterManager), + showCallOutUnauthorizedMsg: false, + status: TimelineStatus.immutable, + }; + + const wrapper = mount( + + + + ); + + expect(wrapper.find('[data-test-subj="timelineImmutableCallOut"]').exists()).toEqual(true); + }); + + test('it renders the immutable timeline call out with correct icon', () => { + const testProps = { + ...props, + filterManager: new FilterManager(mockUiSettingsForFilterManager), + showCallOutUnauthorizedMsg: false, + status: TimelineStatus.immutable, + }; + + const wrapper = mount( + + + + ); + + expect( + wrapper.find('[data-test-subj="timelineImmutableCallOut"]').first().prop('iconType') + ).toEqual('alert'); + }); + + test('it renders the immutable timeline call out with correct message', () => { + const testProps = { + ...props, + filterManager: new FilterManager(mockUiSettingsForFilterManager), + showCallOutUnauthorizedMsg: false, + status: TimelineStatus.immutable, + }; + + const wrapper = mount( + + + + ); + + expect( + wrapper.find('[data-test-subj="timelineImmutableCallOut"]').first().prop('title') + ).toEqual( + 'This prebuilt timeline template cannot be modified. To make changes, please duplicate this template and make modifications to the duplicate template.' + ); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/header/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/header/index.tsx index aa3ce88acc200..e50a6ed1e45fe 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/header/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/header/index.tsx @@ -73,9 +73,9 @@ const TimelineHeaderComponent: React.FC = ({ {status === TimelineStatus.immutable && ( )} diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/header/translations.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/header/translations.ts index dd945d345aad8..89ad11d75cae1 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/header/translations.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/header/translations.ts @@ -14,10 +14,10 @@ export const CALL_OUT_UNAUTHORIZED_MSG = i18n.translate( } ); -export const CALL_OUT_IMMUTIABLE = i18n.translate( +export const CALL_OUT_IMMUTABLE = i18n.translate( 'xpack.securitySolution.timeline.callOut.immutable.message.description', { defaultMessage: - 'This timeline is immutable, therefore not allowed to save it within the security application, though you may continue to use the timeline to search and filter security events', + 'This prebuilt timeline template cannot be modified. To make changes, please duplicate this template and make modifications to the duplicate template.', } ); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.tsx index 452808e51c096..86334308558b8 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.tsx @@ -17,7 +17,7 @@ import { EuiOverlayMask, EuiToolTip, } from '@elastic/eui'; -import React, { useCallback } from 'react'; +import React, { useCallback, useMemo } from 'react'; import uuid from 'uuid'; import styled from 'styled-components'; import { useDispatch, useSelector } from 'react-redux'; @@ -192,18 +192,28 @@ export const NewCase = React.memo( timelineTitle, ]); - return ( - - {buttonText} - + const button = useMemo( + () => ( + + {buttonText} + + ), + [compact, timelineStatus, handleClick, buttonText] + ); + return timelineStatus === TimelineStatus.draft ? ( + + {button} + + ) : ( + button ); } ); @@ -225,8 +235,8 @@ export const ExistingCase = React.memo( ? i18n.ATTACH_TO_EXISTING_CASE : i18n.ATTACH_TIMELINE_TO_EXISTING_CASE; - return ( - <> + const button = useMemo( + () => ( ( > {buttonText} - + ), + [buttonText, handleClick, timelineStatus, compact] + ); + return timelineStatus === TimelineStatus.draft ? ( + + {button} + + ) : ( + button ); } ); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx index 96a773507a30a..9eea95a0a9b1a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx @@ -6,7 +6,6 @@ import React, { useState, useCallback, useMemo } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; import { TimelineStatusLiteral, TimelineTypeLiteral } from '../../../../../common/types/timeline'; import { useThrottledResizeObserver } from '../../../../common/components/utils'; import { Note } from '../../../../common/lib/note'; @@ -17,15 +16,7 @@ import { AssociateNote, UpdateNote } from '../../notes/helpers'; import { TimelineProperties } from './styles'; import { PropertiesRight } from './properties_right'; import { PropertiesLeft } from './properties_left'; -import { AllCasesModal } from '../../../../cases/components/all_cases_modal'; -import { SecurityPageName } from '../../../../app/types'; -import * as i18n from './translations'; -import { State } from '../../../../common/store'; -import { timelineSelectors } from '../../../store/timeline'; -import { setInsertTimeline } from '../../../store/timeline/actions'; -import { useKibana } from '../../../../common/lib/kibana'; -import { APP_ID } from '../../../../../common/constants'; -import { getCaseDetailsUrl, getCreateCaseUrl } from '../../../../common/components/link_to'; +import { useAllCasesModal } from '../../../../cases/components/use_all_cases_modal'; type UpdateIsFavorite = ({ id, isFavorite }: { id: string; isFavorite: boolean }) => void; type UpdateTitle = ({ id, title }: { id: string; title: string }) => void; @@ -86,12 +77,10 @@ export const Properties = React.memo( updateTitle, usersViewing, }) => { - const { navigateToApp } = useKibana().services.application; const { ref, width = 0 } = useThrottledResizeObserver(300); const [showActions, setShowActions] = useState(false); const [showNotes, setShowNotes] = useState(false); const [showTimelineModal, setShowTimelineModal] = useState(false); - const dispatch = useDispatch(); const onButtonClick = useCallback(() => setShowActions(!showActions), [showActions]); const onToggleShowNotes = useCallback(() => setShowNotes(!showNotes), [showNotes]); @@ -103,32 +92,7 @@ export const Properties = React.memo( setShowTimelineModal(true); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); - const [showCaseModal, setShowCaseModal] = useState(false); - const onCloseCaseModal = useCallback(() => setShowCaseModal(false), []); - const onOpenCaseModal = useCallback(() => setShowCaseModal(true), []); - const currentTimeline = useSelector((state: State) => - timelineSelectors.selectTimeline(state, timelineId) - ); - - const onRowClick = useCallback( - (id?: string) => { - onCloseCaseModal(); - - navigateToApp(`${APP_ID}:${SecurityPageName.case}`, { - path: id != null ? getCaseDetailsUrl({ id }) : getCreateCaseUrl(), - }).then(() => - dispatch( - setInsertTimeline({ - graphEventId, - timelineId, - timelineSavedObjectId: currentTimeline.savedObjectId, - timelineTitle: title.length > 0 ? title : i18n.UNTITLED_TIMELINE, - }) - ) - ); - }, - [currentTimeline, dispatch, graphEventId, navigateToApp, onCloseCaseModal, timelineId, title] - ); + const { Modal: AllCasesModal, onOpenModal: onOpenCaseModal } = useAllCasesModal({ timelineId }); const datePickerWidth = useMemo( () => @@ -195,11 +159,7 @@ export const Properties = React.memo( updateNote={updateNote} usersViewing={usersViewing} /> - + ); } diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/translations.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/translations.ts index 34681d5ed6809..1fc3b7b00f847 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/translations.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/translations.ts @@ -151,6 +151,13 @@ export const ATTACH_TO_EXISTING_CASE = i18n.translate( } ); +export const ATTACH_TIMELINE_TO_CASE_TOOLTIP = i18n.translate( + 'xpack.securitySolution.timeline.properties.attachTimelineToCaseTooltip', + { + defaultMessage: 'Please provide a title for your timeline in order to attach it to a case', + } +); + export const STREAM_LIVE = i18n.translate( 'xpack.securitySolution.timeline.properties.streamLiveButtonLabel', { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/search_super_select/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/search_super_select/index.tsx index 825d4fe3b29b1..3019a8add4e36 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/search_super_select/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/search_super_select/index.tsx @@ -4,19 +4,41 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiInputPopover, EuiSelectableOption, EuiSuperSelect } from '@elastic/eui'; +import { EuiInputPopover, EuiSelectableOption, EuiFieldText } from '@elastic/eui'; import React, { memo, useCallback, useMemo, useState } from 'react'; -import { createGlobalStyle } from 'styled-components'; +import styled from 'styled-components'; import { OpenTimelineResult } from '../../open_timeline/types'; import { SelectableTimeline } from '../selectable_timeline'; import * as i18n from '../translations'; import { TimelineType, TimelineTypeLiteral } from '../../../../../common/types/timeline'; -const SearchTimelineSuperSelectGlobalStyle = createGlobalStyle` - .euiPopover__panel.euiPopover__panel-isOpen.timeline-search-super-select-popover__popoverPanel { - visibility: hidden; - z-index: 0; +const StyledEuiFieldText = styled(EuiFieldText)` + padding-left: 12px; + padding-right: 40px; + + &[readonly] { + cursor: pointer; + background-size: 0 100%; + background-repeat: no-repeat; + + // To match EuiFieldText focus state + &:focus { + background-color: #fff; + background-image: linear-gradient( + to top, + #006bb4, + #006bb4 2px, + transparent 2px, + transparent 100% + ); + background-size: 100% 100%; + } + } + + & + .euiFormControlLayoutIcons { + left: unset; + right: 12px; } `; @@ -29,13 +51,6 @@ interface SearchTimelineSuperSelectProps { onTimelineChange: (timelineTitle: string, timelineId: string | null) => void; } -const basicSuperSelectOptions = [ - { - value: '-1', - inputDisplay: i18n.DEFAULT_TIMELINE_TITLE, - }, -]; - const getBasicSelectableOptions = (timelineId: string) => [ { description: i18n.DEFAULT_TIMELINE_DESCRIPTION, @@ -67,26 +82,15 @@ const SearchTimelineSuperSelectComponent: React.FC ( - ), - [handleOpenPopover, isDisabled, timelineId, timelineTitle] + [handleOpenPopover, isDisabled, timelineTitle] ); const handleGetSelectableOptions = useCallback( @@ -126,7 +130,6 @@ const SearchTimelineSuperSelectComponent: React.FC - ); }; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/selectable_timeline/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/selectable_timeline/index.tsx index ae8bf53090789..7ecbc9a53cb21 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/selectable_timeline/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/selectable_timeline/index.tsx @@ -165,7 +165,7 @@ const SelectableTimelineComponent: React.FC = ({ responsive={false} > - + diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.tsx index c27af94addeab..a2ee1e56306b5 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.tsx @@ -286,6 +286,7 @@ export const TimelineComponent: React.FC = ({ filterQuery={combinedQueries!.filterQuery} sortField={timelineQuerySortField} startDate={start} + queryDeduplication="timeline" > {({ events, 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 510d58dbe6a69..562999108b4b0 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/containers/index.tsx @@ -58,6 +58,7 @@ export interface OwnProps extends QueryTemplateProps { sortField: SortField; fields: string[]; startDate: string; + queryDeduplication: string; } type TimelineQueryProps = OwnProps & PropsFromRedux & WithKibanaProps & CustomReduxProps; @@ -93,6 +94,7 @@ class TimelineQueryComponent extends QueryTemplate< sourceId, sortField, startDate, + queryDeduplication, } = this.props; const defaultKibanaIndex = kibana.services.uiSettings.get(DEFAULT_INDEX_KEY); const defaultIndex = @@ -102,7 +104,11 @@ class TimelineQueryComponent extends QueryTemplate< ...(['all', 'alert', 'signal'].includes(eventType) ? indexToAdd : []), ] : indexPattern?.title.split(',') ?? []; - const variables: GetTimelineQuery.Variables = { + // Fun fact: When using this hook multiple times within a component (e.g. add_exception_modal & edit_exception_modal), + // the apolloClient will perform queryDeduplication and prevent the first query from executing. A deep compare is not + // performed on `indices`, so another field must be passed to circumvent this. + // For details, see https://github.com/apollographql/react-apollo/issues/2202 + const variables: GetTimelineQuery.Variables & { queryDeduplication: string } = { fieldRequested: fields, filterQuery: createFilter(filterQuery), sourceId, @@ -116,6 +122,7 @@ class TimelineQueryComponent extends QueryTemplate< defaultIndex, docValueFields: docValueFields ?? [], inspect: isInspected, + queryDeduplication, }; return ( diff --git a/x-pack/plugins/security_solution/server/config.ts b/x-pack/plugins/security_solution/server/config.ts index f7d961ae3ec5c..e2c06ae9f931f 100644 --- a/x-pack/plugins/security_solution/server/config.ts +++ b/x-pack/plugins/security_solution/server/config.ts @@ -29,6 +29,12 @@ export const configSchema = schema.object({ from: schema.string({ defaultValue: 'now-15m' }), to: schema.string({ defaultValue: 'now' }), }), + + /** + * Artifacts Configuration + */ + packagerTaskInterval: schema.string({ defaultValue: '60s' }), + validateArtifactDownloads: schema.boolean({ defaultValue: true }), }); export const createConfig$ = (context: PluginInitializerContext) => diff --git a/x-pack/plugins/security_solution/server/endpoint/config.ts b/x-pack/plugins/security_solution/server/endpoint/config.ts index 908e14468c5c7..6a3644f7aaf71 100644 --- a/x-pack/plugins/security_solution/server/endpoint/config.ts +++ b/x-pack/plugins/security_solution/server/endpoint/config.ts @@ -27,6 +27,12 @@ export const EndpointConfigSchema = schema.object({ from: schema.string({ defaultValue: 'now-15m' }), to: schema.string({ defaultValue: 'now' }), }), + + /** + * Artifacts Configuration + */ + packagerTaskInterval: schema.string({ defaultValue: '60s' }), + validateArtifactDownloads: schema.boolean({ defaultValue: true }), }); export function createConfig$(context: PluginInitializerContext) { diff --git a/x-pack/plugins/security_solution/server/endpoint/ingest_integration.test.ts b/x-pack/plugins/security_solution/server/endpoint/ingest_integration.test.ts index be749b2ebd25a..03999715dfc71 100644 --- a/x-pack/plugins/security_solution/server/endpoint/ingest_integration.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/ingest_integration.test.ts @@ -12,7 +12,6 @@ import { ManifestManagerMockType, } from './services/artifacts/manifest_manager/manifest_manager.mock'; import { getPackageConfigCreateCallback } from './ingest_integration'; -import { ManifestConstants } from './lib/artifacts'; describe('ingest_integration tests ', () => { describe('ingest_integration sanity checks', () => { @@ -30,16 +29,6 @@ describe('ingest_integration tests ', () => { expect(newPolicyConfig.inputs[0]!.config!.policy.value).toEqual(policyConfigFactory()); expect(newPolicyConfig.inputs[0]!.config!.artifact_manifest.value).toEqual({ artifacts: { - 'endpoint-exceptionlist-linux-v1': { - compression_algorithm: 'zlib', - decoded_sha256: 'd801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658', - decoded_size: 14, - encoded_sha256: 'f8e6afa1d5662f5b37f83337af774b5785b5b7f1daee08b7b00c2d6813874cda', - encoded_size: 22, - encryption_algorithm: 'none', - relative_url: - '/api/endpoint/artifacts/download/endpoint-exceptionlist-linux-v1/d801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658', - }, 'endpoint-exceptionlist-macos-v1': { compression_algorithm: 'zlib', decoded_sha256: 'd801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658', @@ -61,7 +50,7 @@ describe('ingest_integration tests ', () => { '/api/endpoint/artifacts/download/endpoint-exceptionlist-windows-v1/d801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658', }, }, - manifest_version: 'a9b7ef358a363f327f479e31efc4f228b2277a7fb4d1914ca9b4e7ca9ffcf537', + manifest_version: '1.0.0', schema_version: 'v1', }); }); @@ -70,9 +59,7 @@ describe('ingest_integration tests ', () => { const logger = loggingSystemMock.create().get('ingest_integration.test'); const manifestManager = getManifestManagerMock(); manifestManager.pushArtifacts = jest.fn().mockResolvedValue([new Error('error updating')]); - const lastComputed = await manifestManager.getLastComputedManifest( - ManifestConstants.SCHEMA_VERSION - ); + const lastComputed = await manifestManager.getLastComputedManifest(); const callback = getPackageConfigCreateCallback(logger, manifestManager); const policyConfig = createNewPackageConfigMock(); @@ -90,9 +77,7 @@ describe('ingest_integration tests ', () => { const manifestManager = getManifestManagerMock({ mockType: ManifestManagerMockType.InitialSystemState, }); - const lastComputed = await manifestManager.getLastComputedManifest( - ManifestConstants.SCHEMA_VERSION - ); + const lastComputed = await manifestManager.getLastComputedManifest(); expect(lastComputed).toEqual(null); manifestManager.buildNewManifest = jest.fn().mockRejectedValue(new Error('abcd')); @@ -107,9 +92,7 @@ describe('ingest_integration tests ', () => { test('subsequent policy creations succeed', async () => { const logger = loggingSystemMock.create().get('ingest_integration.test'); const manifestManager = getManifestManagerMock(); - const lastComputed = await manifestManager.getLastComputedManifest( - ManifestConstants.SCHEMA_VERSION - ); + const lastComputed = await manifestManager.getLastComputedManifest(); manifestManager.buildNewManifest = jest.fn().mockResolvedValue(lastComputed); // no diffs const callback = getPackageConfigCreateCallback(logger, manifestManager); diff --git a/x-pack/plugins/security_solution/server/endpoint/ingest_integration.ts b/x-pack/plugins/security_solution/server/endpoint/ingest_integration.ts index 11d4b12d0b76a..695267f322857 100644 --- a/x-pack/plugins/security_solution/server/endpoint/ingest_integration.ts +++ b/x-pack/plugins/security_solution/server/endpoint/ingest_integration.ts @@ -10,7 +10,7 @@ import { factory as policyConfigFactory } from '../../common/endpoint/models/pol import { NewPolicyData } from '../../common/endpoint/types'; import { ManifestManager } from './services/artifacts'; import { Manifest } from './lib/artifacts'; -import { reportErrors, ManifestConstants } from './lib/artifacts/common'; +import { reportErrors } from './lib/artifacts/common'; import { InternalArtifactCompleteSchema } from './schemas/artifacts'; import { manifestDispatchSchema } from '../../common/endpoint/schema/manifest'; @@ -18,14 +18,14 @@ const getManifest = async (logger: Logger, manifestManager: ManifestManager): Pr let manifest: Manifest | null = null; try { - manifest = await manifestManager.getLastComputedManifest(ManifestConstants.SCHEMA_VERSION); + manifest = await manifestManager.getLastComputedManifest(); // If we have not yet computed a manifest, then we have to do so now. This should only happen // once. if (manifest == null) { // New computed manifest based on current state of exception list - const newManifest = await manifestManager.buildNewManifest(ManifestConstants.SCHEMA_VERSION); - const diffs = newManifest.diff(Manifest.getDefault(ManifestConstants.SCHEMA_VERSION)); + const newManifest = await manifestManager.buildNewManifest(); + const diffs = newManifest.diff(Manifest.getDefault()); // Compress new artifacts const adds = diffs.filter((diff) => diff.type === 'add').map((diff) => diff.id); @@ -63,7 +63,7 @@ const getManifest = async (logger: Logger, manifestManager: ManifestManager): Pr logger.error(err); } - return manifest ?? Manifest.getDefault(ManifestConstants.SCHEMA_VERSION); + return manifest ?? Manifest.getDefault(); }; /** diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/common.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/common.ts index 7298a9bfa72a6..7f90aa7b91063 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/common.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/common.ts @@ -13,13 +13,11 @@ import { export const ArtifactConstants = { GLOBAL_ALLOWLIST_NAME: 'endpoint-exceptionlist', SAVED_OBJECT_TYPE: 'endpoint:user-artifact', - SUPPORTED_OPERATING_SYSTEMS: ['linux', 'macos', 'windows'], - SCHEMA_VERSION: 'v1', + SUPPORTED_OPERATING_SYSTEMS: ['macos', 'windows'], }; export const ManifestConstants = { SAVED_OBJECT_TYPE: 'endpoint:user-artifact-manifest', - SCHEMA_VERSION: 'v1', }; export const getArtifactId = (artifact: InternalArtifactSchema) => { diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/lists.test.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/lists.test.ts index bb8b4fb3d5ce7..fea3b2b9a4526 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/lists.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/lists.test.ts @@ -314,21 +314,23 @@ describe('buildEventTypeSignal', () => { test('it should convert the exception lists response to the proper endpoint format while paging', async () => { // The first call returns two exceptions const first = getFoundExceptionListItemSchemaMock(); + first.per_page = 2; + first.total = 4; first.data.push(getExceptionListItemSchemaMock()); // The second call returns two exceptions const second = getFoundExceptionListItemSchemaMock(); + second.per_page = 2; + second.total = 4; second.data.push(getExceptionListItemSchemaMock()); - // The third call returns no exceptions, paging stops - const third = getFoundExceptionListItemSchemaMock(); - third.data = []; mockExceptionClient.findExceptionListItem = jest .fn() .mockReturnValueOnce(first) - .mockReturnValueOnce(second) - .mockReturnValueOnce(third); + .mockReturnValueOnce(second); + const resp = await getFullEndpointExceptionList(mockExceptionClient, 'linux', 'v1'); + // Expect 2 exceptions, the first two calls returned the same exception list items expect(resp.entries.length).toEqual(2); }); diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/lists.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/lists.ts index 5998a88527f2f..e41781dd605a0 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/lists.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/lists.ts @@ -79,10 +79,10 @@ export async function getFullEndpointExceptionList( schemaVersion: string ): Promise { const exceptions: WrappedTranslatedExceptionList = { entries: [] }; - let numResponses = 0; let page = 1; + let paging = true; - do { + while (paging) { const response = await eClient.findExceptionListItem({ listId: ENDPOINT_LIST_ID, namespaceType: 'agnostic', @@ -94,17 +94,16 @@ export async function getFullEndpointExceptionList( }); if (response?.data !== undefined) { - numResponses = response.data.length; - exceptions.entries = exceptions.entries.concat( translateToEndpointExceptions(response, schemaVersion) ); + paging = (page - 1) * 100 + response.data.length < response.total; page++; } else { break; } - } while (numResponses > 0); + } const [validated, errors] = validate(exceptions, wrappedTranslatedExceptionList); if (errors != null) { diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/manifest.test.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/manifest.test.ts index 95587c6fc105d..3d70f7266277f 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/manifest.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/manifest.test.ts @@ -6,7 +6,7 @@ import { ManifestSchemaVersion } from '../../../../common/endpoint/schema/common'; import { InternalArtifactCompleteSchema } from '../../schemas'; -import { ManifestConstants, getArtifactId } from './common'; +import { getArtifactId } from './common'; import { Manifest } from './manifest'; import { getMockArtifacts, @@ -30,29 +30,21 @@ describe('manifest', () => { }); test('Can create manifest with valid schema version', () => { - const manifest = new Manifest('v1'); + const manifest = new Manifest(); expect(manifest).toBeInstanceOf(Manifest); }); test('Cannot create manifest with invalid schema version', () => { expect(() => { - new Manifest('abcd' as ManifestSchemaVersion); + new Manifest({ + schemaVersion: 'abcd' as ManifestSchemaVersion, + }); }).toThrow(); }); test('Empty manifest transforms correctly to expected endpoint format', async () => { expect(emptyManifest.toEndpointFormat()).toStrictEqual({ artifacts: { - 'endpoint-exceptionlist-linux-v1': { - compression_algorithm: 'zlib', - encryption_algorithm: 'none', - decoded_sha256: 'd801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658', - encoded_sha256: 'f8e6afa1d5662f5b37f83337af774b5785b5b7f1daee08b7b00c2d6813874cda', - decoded_size: 14, - encoded_size: 22, - relative_url: - '/api/endpoint/artifacts/download/endpoint-exceptionlist-linux-v1/d801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658', - }, 'endpoint-exceptionlist-macos-v1': { compression_algorithm: 'zlib', encryption_algorithm: 'none', @@ -74,7 +66,7 @@ describe('manifest', () => { '/api/endpoint/artifacts/download/endpoint-exceptionlist-windows-v1/d801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658', }, }, - manifest_version: 'a9b7ef358a363f327f479e31efc4f228b2277a7fb4d1914ca9b4e7ca9ffcf537', + manifest_version: '1.0.0', schema_version: 'v1', }); }); @@ -82,16 +74,6 @@ describe('manifest', () => { test('Manifest transforms correctly to expected endpoint format', async () => { expect(manifest1.toEndpointFormat()).toStrictEqual({ artifacts: { - 'endpoint-exceptionlist-linux-v1': { - compression_algorithm: 'zlib', - encryption_algorithm: 'none', - decoded_sha256: '96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', - encoded_sha256: '975382ab55d019cbab0bbac207a54e2a7d489fad6e8f6de34fc6402e5ef37b1e', - decoded_size: 432, - encoded_size: 147, - relative_url: - '/api/endpoint/artifacts/download/endpoint-exceptionlist-linux-v1/96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', - }, 'endpoint-exceptionlist-macos-v1': { compression_algorithm: 'zlib', encryption_algorithm: 'none', @@ -113,15 +95,16 @@ describe('manifest', () => { '/api/endpoint/artifacts/download/endpoint-exceptionlist-windows-v1/96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', }, }, - manifest_version: 'a7f4760bfa2662e85e30fe4fb8c01b4c4a20938c76ab21d3c5a3e781e547cce7', + manifest_version: '1.0.0', schema_version: 'v1', }); }); test('Manifest transforms correctly to expected saved object format', async () => { expect(manifest1.toSavedObject()).toStrictEqual({ + schemaVersion: 'v1', + semanticVersion: '1.0.0', ids: [ - 'endpoint-exceptionlist-linux-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', 'endpoint-exceptionlist-macos-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', 'endpoint-exceptionlist-windows-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', ], @@ -133,12 +116,12 @@ describe('manifest', () => { expect(diffs).toEqual([ { id: - 'endpoint-exceptionlist-linux-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', + 'endpoint-exceptionlist-macos-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', type: 'delete', }, { id: - 'endpoint-exceptionlist-linux-v1-0a5a2013a79f9e60682472284a1be45ab1ff68b9b43426d00d665016612c15c8', + 'endpoint-exceptionlist-macos-v1-0a5a2013a79f9e60682472284a1be45ab1ff68b9b43426d00d665016612c15c8', type: 'add', }, ]); @@ -154,7 +137,6 @@ describe('manifest', () => { const entries = manifest1.getEntries(); const keys = Object.keys(entries); expect(keys).toEqual([ - 'endpoint-exceptionlist-linux-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', 'endpoint-exceptionlist-macos-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', 'endpoint-exceptionlist-windows-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', ]); @@ -168,13 +150,8 @@ describe('manifest', () => { }); test('Manifest can be created from list of artifacts', async () => { - const oldManifest = new Manifest(ManifestConstants.SCHEMA_VERSION); - const manifest = Manifest.fromArtifacts(artifacts, 'v1', oldManifest); - expect( - manifest.contains( - 'endpoint-exceptionlist-linux-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3' - ) - ).toEqual(true); + const oldManifest = new Manifest(); + const manifest = Manifest.fromArtifacts(artifacts, oldManifest); expect( manifest.contains( 'endpoint-exceptionlist-macos-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3' diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/manifest.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/manifest.ts index 6ece2bf0f48e8..9e0e940ea9a1d 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/manifest.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/manifest.ts @@ -3,8 +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 { createHash } from 'crypto'; +import semver from 'semver'; import { validate } from '../../../../common/validate'; import { InternalArtifactSchema, @@ -13,13 +12,15 @@ import { InternalArtifactCompleteSchema, } from '../../schemas/artifacts'; import { - manifestSchemaVersion, ManifestSchemaVersion, + SemanticVersion, + semanticVersion, } from '../../../../common/endpoint/schema/common'; -import { ManifestSchema, manifestSchema } from '../../../../common/endpoint/schema/manifest'; +import { manifestSchema, ManifestSchema } from '../../../../common/endpoint/schema/manifest'; import { ManifestEntry } from './manifest_entry'; import { maybeCompressArtifact, isCompressed } from './lists'; import { getArtifactId } from './common'; +import { ManifestVersion, manifestVersion } from '../../schemas/artifacts/manifest'; export interface ManifestDiff { type: string; @@ -28,37 +29,39 @@ export interface ManifestDiff { export class Manifest { private entries: Record; - private schemaVersion: ManifestSchemaVersion; - - // For concurrency control - private version: string | undefined; + private version: ManifestVersion; - constructor(schemaVersion: string, version?: string) { + constructor(version?: Partial) { this.entries = {}; - this.version = version; - const [validated, errors] = validate( - (schemaVersion as unknown) as object, - manifestSchemaVersion - ); + const decodedVersion = { + schemaVersion: version?.schemaVersion ?? 'v1', + semanticVersion: version?.semanticVersion ?? '1.0.0', + soVersion: version?.soVersion, + }; + const [validated, errors] = validate(decodedVersion, manifestVersion); if (errors != null || validated === null) { - throw new Error(`Invalid manifest schema version: ${schemaVersion}`); + throw new Error(errors ?? 'Invalid version format.'); } - this.schemaVersion = validated; + this.version = validated; } - public static getDefault(schemaVersion: string) { - return new Manifest(schemaVersion); + public static getDefault(schemaVersion?: ManifestSchemaVersion) { + return new Manifest({ schemaVersion, semanticVersion: '1.0.0' }); } public static fromArtifacts( artifacts: InternalArtifactCompleteSchema[], - schemaVersion: string, - oldManifest: Manifest + oldManifest: Manifest, + schemaVersion?: ManifestSchemaVersion ): Manifest { - const manifest = new Manifest(schemaVersion, oldManifest.getSoVersion()); + const manifest = new Manifest({ + schemaVersion, + semanticVersion: oldManifest.getSemanticVersion(), + soVersion: oldManifest.getSavedObjectVersion(), + }); artifacts.forEach((artifact) => { const id = getArtifactId(artifact); const existingArtifact = oldManifest.getArtifact(id); @@ -71,25 +74,12 @@ export class Manifest { return manifest; } - public static fromPkgConfig(manifestPkgConfig: ManifestSchema): Manifest | null { - if (manifestSchema.is(manifestPkgConfig)) { - const manifest = new Manifest(manifestPkgConfig.schema_version); - for (const [identifier, artifactRecord] of Object.entries(manifestPkgConfig.artifacts)) { - const artifact = { - identifier, - compressionAlgorithm: artifactRecord.compression_algorithm, - encryptionAlgorithm: artifactRecord.encryption_algorithm, - decodedSha256: artifactRecord.decoded_sha256, - decodedSize: artifactRecord.decoded_size, - encodedSha256: artifactRecord.encoded_sha256, - encodedSize: artifactRecord.encoded_size, - }; - manifest.addEntry(artifact); - } - return manifest; - } else { - return null; + public bumpSemanticVersion() { + const newSemanticVersion = semver.inc(this.getSemanticVersion(), 'patch'); + if (!semanticVersion.is(newSemanticVersion)) { + throw new Error(`Invalid semver: ${newSemanticVersion}`); } + this.version.semanticVersion = newSemanticVersion; } public async compressArtifact(id: string): Promise { @@ -112,30 +102,16 @@ export class Manifest { return null; } - public equals(manifest: Manifest): boolean { - return this.getSha256() === manifest.getSha256(); - } - - public getSha256(): string { - let sha256 = createHash('sha256'); - Object.keys(this.entries) - .sort() - .forEach((docId) => { - sha256 = sha256.update(docId); - }); - return sha256.digest('hex'); - } - public getSchemaVersion(): ManifestSchemaVersion { - return this.schemaVersion; + return this.version.schemaVersion; } - public getSoVersion(): string | undefined { - return this.version; + public getSavedObjectVersion(): string | undefined { + return this.version.soVersion; } - public setSoVersion(version: string) { - this.version = version; + public getSemanticVersion(): SemanticVersion { + return this.version.semanticVersion; } public addEntry(artifact: InternalArtifactSchema) { @@ -179,8 +155,8 @@ export class Manifest { public toEndpointFormat(): ManifestSchema { const manifestObj: ManifestSchema = { - manifest_version: this.getSha256(), - schema_version: this.schemaVersion, + manifest_version: this.getSemanticVersion(), + schema_version: this.getSchemaVersion(), artifacts: {}, }; @@ -198,7 +174,9 @@ export class Manifest { public toSavedObject(): InternalManifestSchema { return { - ids: Object.keys(this.entries), + ids: Object.keys(this.getEntries()), + schemaVersion: this.getSchemaVersion(), + semanticVersion: this.getSemanticVersion(), }; } } diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/mocks.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/mocks.ts index 0ec6cb2bd61b3..62fff4715b562 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/mocks.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/mocks.ts @@ -29,7 +29,7 @@ export const getMockArtifactsWithDiff = async (opts?: { compress: boolean }) => return Promise.all( ArtifactConstants.SUPPORTED_OPERATING_SYSTEMS.map>( async (os) => { - if (os === 'linux') { + if (os === 'macos') { return getInternalArtifactMockWithDiffs(os, 'v1'); } return getInternalArtifactMock(os, 'v1', opts); @@ -49,21 +49,21 @@ export const getEmptyMockArtifacts = async (opts?: { compress: boolean }) => { }; export const getMockManifest = async (opts?: { compress: boolean }) => { - const manifest = new Manifest('v1'); + const manifest = new Manifest(); const artifacts = await getMockArtifacts(opts); artifacts.forEach((artifact) => manifest.addEntry(artifact)); return manifest; }; export const getMockManifestWithDiffs = async (opts?: { compress: boolean }) => { - const manifest = new Manifest('v1'); + const manifest = new Manifest(); const artifacts = await getMockArtifactsWithDiff(opts); artifacts.forEach((artifact) => manifest.addEntry(artifact)); return manifest; }; export const getEmptyMockManifest = async (opts?: { compress: boolean }) => { - const manifest = new Manifest('v1'); + const manifest = new Manifest(); const artifacts = await getEmptyMockArtifacts(opts); artifacts.forEach((artifact) => manifest.addEntry(artifact)); return manifest; @@ -74,16 +74,6 @@ export const createPackageConfigWithInitialManifestMock = (): PackageConfig => { packageConfig.inputs[0].config!.artifact_manifest = { value: { artifacts: { - 'endpoint-exceptionlist-linux-v1': { - compression_algorithm: 'zlib', - encryption_algorithm: 'none', - decoded_sha256: 'd801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658', - encoded_sha256: 'f8e6afa1d5662f5b37f83337af774b5785b5b7f1daee08b7b00c2d6813874cda', - decoded_size: 14, - encoded_size: 22, - relative_url: - '/api/endpoint/artifacts/download/endpoint-exceptionlist-linux-v1/d801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658', - }, 'endpoint-exceptionlist-macos-v1': { compression_algorithm: 'zlib', encryption_algorithm: 'none', @@ -105,7 +95,7 @@ export const createPackageConfigWithInitialManifestMock = (): PackageConfig => { '/api/endpoint/artifacts/download/endpoint-exceptionlist-windows-v1/d801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658', }, }, - manifest_version: 'a9b7ef358a363f327f479e31efc4f228b2277a7fb4d1914ca9b4e7ca9ffcf537', + manifest_version: '1.0.0', schema_version: 'v1', }, }; @@ -117,16 +107,6 @@ export const createPackageConfigWithManifestMock = (): PackageConfig => { packageConfig.inputs[0].config!.artifact_manifest = { value: { artifacts: { - 'endpoint-exceptionlist-linux-v1': { - compression_algorithm: 'zlib', - encryption_algorithm: 'none', - decoded_sha256: '0a5a2013a79f9e60682472284a1be45ab1ff68b9b43426d00d665016612c15c8', - encoded_sha256: '57941169bb2c5416f9bd7224776c8462cb9a2be0fe8b87e6213e77a1d29be824', - decoded_size: 292, - encoded_size: 131, - relative_url: - '/api/endpoint/artifacts/download/endpoint-exceptionlist-linux-v1/0a5a2013a79f9e60682472284a1be45ab1ff68b9b43426d00d665016612c15c8', - }, 'endpoint-exceptionlist-macos-v1': { compression_algorithm: 'zlib', encryption_algorithm: 'none', @@ -148,7 +128,7 @@ export const createPackageConfigWithManifestMock = (): PackageConfig => { '/api/endpoint/artifacts/download/endpoint-exceptionlist-windows-v1/96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', }, }, - manifest_version: '520f6cf88b3f36a065c6ca81058d5f8690aadadf6fe857f8dec4cc37589e7283', + manifest_version: '1.0.1', schema_version: 'v1', }, }; diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/saved_object_mappings.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/saved_object_mappings.ts index 0fb433df95de3..734304516e37e 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/saved_object_mappings.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/saved_object_mappings.ts @@ -55,7 +55,13 @@ export const manifestSavedObjectMappings: SavedObjectsType['mappings'] = { type: 'date', index: false, }, - // array of doc ids + schemaVersion: { + type: 'keyword', + }, + semanticVersion: { + type: 'keyword', + index: false, + }, ids: { type: 'keyword', index: false, diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.test.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.test.ts index daa8a7dd83ee0..32d58da5c3b78 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.test.ts @@ -38,7 +38,7 @@ describe('task', () => { taskManager: mockTaskManagerSetup, }); const mockTaskManagerStart = taskManagerMock.createStart(); - manifestTask.start({ taskManager: mockTaskManagerStart }); + await manifestTask.start({ taskManager: mockTaskManagerStart }); expect(mockTaskManagerStart.ensureScheduled).toHaveBeenCalled(); }); diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.ts index ba164059866ea..4f2dbdf7644e2 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.ts @@ -3,7 +3,6 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - import { Logger } from 'src/core/server'; import { ConcreteTaskInstance, @@ -11,7 +10,7 @@ import { TaskManagerStartContract, } from '../../../../../task_manager/server'; import { EndpointAppContext } from '../../types'; -import { reportErrors, ManifestConstants } from './common'; +import { reportErrors } from './common'; import { InternalArtifactCompleteSchema } from '../../schemas/artifacts'; export const ManifestTaskConstants = { @@ -45,7 +44,23 @@ export class ManifestTask { createTaskRunner: ({ taskInstance }: { taskInstance: ConcreteTaskInstance }) => { return { run: async () => { + const taskInterval = (await this.endpointAppContext.config()).packagerTaskInterval; await this.runTask(taskInstance.id); + const nextRun = new Date(); + if (taskInterval.endsWith('s')) { + const seconds = parseInt(taskInterval.slice(0, -1), 10); + nextRun.setSeconds(nextRun.getSeconds() + seconds); + } else if (taskInterval.endsWith('m')) { + const minutes = parseInt(taskInterval.slice(0, -1), 10); + nextRun.setMinutes(nextRun.getMinutes() + minutes); + } else { + this.logger.error(`Invalid task interval: ${taskInterval}`); + return; + } + return { + state: {}, + runAt: nextRun, + }; }, cancel: async () => {}, }; @@ -61,7 +76,7 @@ export class ManifestTask { taskType: ManifestTaskConstants.TYPE, scope: ['securitySolution'], schedule: { - interval: '60s', + interval: (await this.endpointAppContext.config()).packagerTaskInterval, }, state: {}, params: { version: ManifestTaskConstants.VERSION }, @@ -92,19 +107,14 @@ export class ManifestTask { try { // Last manifest we computed, which was saved to ES - const oldManifest = await manifestManager.getLastComputedManifest( - ManifestConstants.SCHEMA_VERSION - ); + const oldManifest = await manifestManager.getLastComputedManifest(); if (oldManifest == null) { this.logger.debug('User manifest not available yet.'); return; } // New computed manifest based on current state of exception list - const newManifest = await manifestManager.buildNewManifest( - ManifestConstants.SCHEMA_VERSION, - oldManifest - ); + const newManifest = await manifestManager.buildNewManifest(oldManifest); const diffs = newManifest.diff(oldManifest); // Compress new artifacts @@ -131,6 +141,7 @@ export class ManifestTask { // Commit latest manifest state, if different if (diffs.length) { + newManifest.bumpSemanticVersion(); const error = await manifestManager.commit(newManifest); if (error) { throw error; diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/artifacts/download_exception_list.ts b/x-pack/plugins/security_solution/server/endpoint/routes/artifacts/download_exception_list.ts index 38e900c4d5015..d825841f1e257 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/artifacts/download_exception_list.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/artifacts/download_exception_list.ts @@ -3,7 +3,6 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - import { IRouter, SavedObjectsClientContract, @@ -14,7 +13,6 @@ import { import LRU from 'lru-cache'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { authenticateAgentWithAccessToken } from '../../../../../ingest_manager/server/services/agents/authenticate'; -import { validate } from '../../../../common/validate'; import { LIMITED_CONCURRENCY_ENDPOINT_ROUTE_TAG } from '../../../../common/endpoint/constants'; import { buildRouteValidation } from '../../../utils/build_validation/route_validation'; import { ArtifactConstants } from '../../lib/artifacts'; @@ -63,6 +61,7 @@ export function registerDownloadExceptionListRoute( } } + const validateDownload = (await endpointContext.config()).validateArtifactDownloads; const buildAndValidateResponse = (artName: string, body: Buffer): IKibanaResponse => { const artifact: HttpResponseOptions = { body, @@ -72,11 +71,10 @@ export function registerDownloadExceptionListRoute( }, }; - const [validated, errors] = validate(artifact, downloadArtifactResponseSchema); - if (errors !== null || validated === null) { - return res.internalError({ body: errors! }); + if (validateDownload && !downloadArtifactResponseSchema.is(artifact)) { + return res.internalError({ body: 'Artifact failed to validate.' }); } else { - return res.ok((validated as unknown) as HttpResponseOptions); + return res.ok(artifact); } }; diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts index fe7a8296608d2..084f892369b51 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts @@ -201,7 +201,11 @@ async function findAgent( hostMetadata.elastic.agent.id ); } catch (e) { - if (e.isBoom && e.output.statusCode === 404) { + if ( + metadataRequestContext.requestHandlerContext.core.savedObjects.client.errors.isNotFoundError( + e + ) + ) { metadataRequestContext.logger.warn( `agent with id ${hostMetadata.elastic.agent.id} not found` ); @@ -264,7 +268,11 @@ async function enrichHostMetadata( ); hostStatus = HOST_STATUS_MAPPING.get(status) || HostStatus.ERROR; } catch (e) { - if (e.isBoom && e.output.statusCode === 404) { + if ( + metadataRequestContext.requestHandlerContext.core.savedObjects.client.errors.isNotFoundError( + e + ) + ) { log.warn(`agent with id ${elasticAgentId} not found`); } else { log.error(e); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts index 8d967656065d1..f3b832de9a786 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts @@ -12,6 +12,7 @@ import { RouteConfig, SavedObjectsClientContract, } from 'kibana/server'; +import { SavedObjectsErrorHelpers } from '../../../../../../../src/core/server/'; import { elasticsearchServiceMock, httpServerMock, @@ -31,7 +32,6 @@ import { createMockEndpointAppContextServiceStartContract, createRouteHandlerContext, } from '../../mocks'; -import Boom from 'boom'; import { EndpointAppContextService } from '../../endpoint_app_context_services'; import { createMockConfig } from '../../../lib/detection_engine/routes/__mocks__'; import { EndpointDocGenerator } from '../../../../common/endpoint/generate_data'; @@ -306,11 +306,11 @@ describe('test endpoint route', () => { }); mockAgentService.getAgentStatusById = jest.fn().mockImplementation(() => { - throw Boom.notFound('Agent not found'); + SavedObjectsErrorHelpers.createGenericNotFoundError(); }); mockAgentService.getAgent = jest.fn().mockImplementation(() => { - throw Boom.notFound('Agent not found'); + SavedObjectsErrorHelpers.createGenericNotFoundError(); }); mockScopedClient.callAsCurrentUser.mockImplementationOnce(() => Promise.resolve(response)); 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 ae91201646103..c79bcda71de9b 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 @@ -70,6 +70,13 @@ export function handleEntities(): RequestHandler implements MSearchQuer } private buildQuery(ids: string | string[]): { query: JsonObject; index: string | string[] } { - const idsArray = ResolverQuery.createIdsArray(ids); + // only accept queries for entity_ids that are not an empty string + const idsArray = ResolverQuery.createIdsArray(ids).filter((id) => id !== ''); if (this.endpointID) { return { query: this.legacyQuery(this.endpointID, idsArray), index: legacyEventIndexPattern }; } diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/queries/children.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/queries/children.ts index 7fd3808662baa..d99533e23f2c2 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/queries/children.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/queries/children.ts @@ -74,6 +74,18 @@ export class ChildrenQuery extends ResolverQuery { ], }, }, + { + exists: { + field: 'process.entity_id', + }, + }, + { + bool: { + must_not: { + term: { 'process.entity_id': '' }, + }, + }, + }, { term: { 'event.category': 'process' }, }, diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/utils/children_helper.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/utils/children_helper.test.ts index ca5b5aef0f651..01dd59b2611d9 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/utils/children_helper.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/utils/children_helper.test.ts @@ -10,12 +10,12 @@ import { TreeNode, } from '../../../../../common/endpoint/generate_data'; import { ChildrenNodesHelper } from './children_helper'; -import { eventId, isProcessStart } from '../../../../../common/endpoint/models/event'; +import { eventId, isStart } from '../../../../../common/endpoint/models/event'; function getStartEvents(events: Event[]): Event[] { const startEvents: Event[] = []; for (const event of events) { - if (isProcessStart(event)) { + if (isStart(event)) { startEvents.push(event); } } diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/utils/children_helper.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/utils/children_helper.ts index 01e356682ac47..d3ca7a54c16d2 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/utils/children_helper.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/utils/children_helper.ts @@ -7,7 +7,7 @@ import { entityId, parentEntityId, - isProcessStart, + isStart, getAncestryAsArray, } from '../../../../../common/endpoint/models/event'; import { @@ -99,7 +99,7 @@ export class ChildrenNodesHelper { for (const event of startEvents) { const parentID = parentEntityId(event); const entityID = entityId(event); - if (parentID && entityID && isProcessStart(event)) { + if (parentID && entityID && isStart(event)) { // don't actually add the start event to the node, because that'll be done in // a different call const childNode = this.getOrCreateChildNode(entityID); diff --git a/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/manifest.ts b/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/manifest.ts new file mode 100644 index 0000000000000..707d4c1374fe2 --- /dev/null +++ b/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/manifest.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { manifestSchemaVersion, semanticVersion } from '../../../../common/endpoint/schema/common'; + +const optionalVersions = t.partial({ + soVersion: t.string, +}); + +export const manifestVersion = t.intersection([ + optionalVersions, + t.exact( + t.type({ + schemaVersion: manifestSchemaVersion, + semanticVersion, + }) + ), +]); +export type ManifestVersion = t.TypeOf; diff --git a/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/saved_objects.mock.ts b/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/saved_objects.mock.ts index d95627601a183..ae565f785c399 100644 --- a/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/saved_objects.mock.ts +++ b/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/saved_objects.mock.ts @@ -53,4 +53,6 @@ export const getInternalArtifactMockWithDiffs = async ( export const getInternalManifestMock = (): InternalManifestSchema => ({ ids: [], + schemaVersion: 'v1', + semanticVersion: '1.0.0', }); diff --git a/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/saved_objects.ts b/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/saved_objects.ts index 4dea916dcb436..56f247b65d802 100644 --- a/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/saved_objects.ts +++ b/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/saved_objects.ts @@ -9,8 +9,10 @@ import { compressionAlgorithm, encryptionAlgorithm, identifier, + semanticVersion, sha256, size, + manifestSchemaVersion, } from '../../../../common/endpoint/schema/common'; import { created } from './common'; @@ -58,6 +60,8 @@ export type InternalArtifactCreateSchema = t.TypeOf; diff --git a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_client.ts b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_client.ts index 385f115e6301a..e55243f0650a5 100644 --- a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_client.ts +++ b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_client.ts @@ -3,7 +3,6 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - import { SavedObject, SavedObjectsClientContract, diff --git a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.test.ts b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.test.ts index c838f772fb66b..d99d6a959d7aa 100644 --- a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.test.ts @@ -16,22 +16,17 @@ describe('manifest_manager', () => { describe('ManifestManager sanity checks', () => { test('ManifestManager can retrieve and diff manifests', async () => { const manifestManager = getManifestManagerMock(); - const oldManifest = await manifestManager.getLastComputedManifest( - ManifestConstants.SCHEMA_VERSION - ); - const newManifest = await manifestManager.buildNewManifest( - ManifestConstants.SCHEMA_VERSION, - oldManifest! - ); + const oldManifest = await manifestManager.getLastComputedManifest(); + const newManifest = await manifestManager.buildNewManifest(oldManifest!); expect(newManifest.diff(oldManifest!)).toEqual([ { id: - 'endpoint-exceptionlist-linux-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', + 'endpoint-exceptionlist-macos-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', type: 'delete', }, { id: - 'endpoint-exceptionlist-linux-v1-0a5a2013a79f9e60682472284a1be45ab1ff68b9b43426d00d665016612c15c8', + 'endpoint-exceptionlist-macos-v1-0a5a2013a79f9e60682472284a1be45ab1ff68b9b43426d00d665016612c15c8', type: 'add', }, ]); @@ -40,23 +35,18 @@ describe('manifest_manager', () => { test('ManifestManager populates cache properly', async () => { const cache = new LRU({ max: 10, maxAge: 1000 * 60 * 60 }); const manifestManager = getManifestManagerMock({ cache }); - const oldManifest = await manifestManager.getLastComputedManifest( - ManifestConstants.SCHEMA_VERSION - ); - const newManifest = await manifestManager.buildNewManifest( - ManifestConstants.SCHEMA_VERSION, - oldManifest! - ); + const oldManifest = await manifestManager.getLastComputedManifest(); + const newManifest = await manifestManager.buildNewManifest(oldManifest!); const diffs = newManifest.diff(oldManifest!); expect(diffs).toEqual([ { id: - 'endpoint-exceptionlist-linux-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', + 'endpoint-exceptionlist-macos-v1-96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', type: 'delete', }, { id: - 'endpoint-exceptionlist-linux-v1-0a5a2013a79f9e60682472284a1be45ab1ff68b9b43426d00d665016612c15c8', + 'endpoint-exceptionlist-macos-v1-0a5a2013a79f9e60682472284a1be45ab1ff68b9b43426d00d665016612c15c8', type: 'add', }, ]); @@ -104,13 +94,8 @@ describe('manifest_manager', () => { test('ManifestManager cannot dispatch incomplete (uncompressed) artifact', async () => { const packageConfigService = createPackageConfigServiceMock(); const manifestManager = getManifestManagerMock({ packageConfigService }); - const oldManifest = await manifestManager.getLastComputedManifest( - ManifestConstants.SCHEMA_VERSION - ); - const newManifest = await manifestManager.buildNewManifest( - ManifestConstants.SCHEMA_VERSION, - oldManifest! - ); + const oldManifest = await manifestManager.getLastComputedManifest(); + const newManifest = await manifestManager.buildNewManifest(oldManifest!); const dispatchErrors = await manifestManager.tryDispatch(newManifest); expect(dispatchErrors.length).toEqual(1); expect(dispatchErrors[0].message).toEqual('Invalid manifest'); @@ -119,17 +104,14 @@ describe('manifest_manager', () => { test('ManifestManager can dispatch manifest', async () => { const packageConfigService = createPackageConfigServiceMock(); const manifestManager = getManifestManagerMock({ packageConfigService }); - const oldManifest = await manifestManager.getLastComputedManifest( - ManifestConstants.SCHEMA_VERSION - ); - const newManifest = await manifestManager.buildNewManifest( - ManifestConstants.SCHEMA_VERSION, - oldManifest! - ); + const oldManifest = await manifestManager.getLastComputedManifest(); + const newManifest = await manifestManager.buildNewManifest(oldManifest!); const diffs = newManifest.diff(oldManifest!); const newArtifactId = diffs[1].id; await newManifest.compressArtifact(newArtifactId); + newManifest.bumpSemanticVersion(); + const dispatchErrors = await manifestManager.tryDispatch(newManifest); expect(dispatchErrors).toEqual([]); @@ -140,10 +122,10 @@ describe('manifest_manager', () => { expect( packageConfigService.update.mock.calls[0][2].inputs[0].config!.artifact_manifest.value ).toEqual({ - manifest_version: '520f6cf88b3f36a065c6ca81058d5f8690aadadf6fe857f8dec4cc37589e7283', + manifest_version: '1.0.1', schema_version: 'v1', artifacts: { - 'endpoint-exceptionlist-linux-v1': { + 'endpoint-exceptionlist-macos-v1': { compression_algorithm: 'zlib', encryption_algorithm: 'none', decoded_sha256: '0a5a2013a79f9e60682472284a1be45ab1ff68b9b43426d00d665016612c15c8', @@ -151,17 +133,7 @@ describe('manifest_manager', () => { decoded_size: 292, encoded_size: 131, relative_url: - '/api/endpoint/artifacts/download/endpoint-exceptionlist-linux-v1/0a5a2013a79f9e60682472284a1be45ab1ff68b9b43426d00d665016612c15c8', - }, - 'endpoint-exceptionlist-macos-v1': { - compression_algorithm: 'zlib', - encryption_algorithm: 'none', - decoded_sha256: '96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', - encoded_sha256: '975382ab55d019cbab0bbac207a54e2a7d489fad6e8f6de34fc6402e5ef37b1e', - decoded_size: 432, - encoded_size: 147, - relative_url: - '/api/endpoint/artifacts/download/endpoint-exceptionlist-macos-v1/96b76a1a911662053a1562ac14c4ff1e87c2ff550d6fe52e1e0b3790526597d3', + '/api/endpoint/artifacts/download/endpoint-exceptionlist-macos-v1/0a5a2013a79f9e60682472284a1be45ab1ff68b9b43426d00d665016612c15c8', }, 'endpoint-exceptionlist-windows-v1': { compression_algorithm: 'zlib', @@ -180,17 +152,14 @@ describe('manifest_manager', () => { test('ManifestManager fails to dispatch on conflict', async () => { const packageConfigService = createPackageConfigServiceMock(); const manifestManager = getManifestManagerMock({ packageConfigService }); - const oldManifest = await manifestManager.getLastComputedManifest( - ManifestConstants.SCHEMA_VERSION - ); - const newManifest = await manifestManager.buildNewManifest( - ManifestConstants.SCHEMA_VERSION, - oldManifest! - ); + const oldManifest = await manifestManager.getLastComputedManifest(); + const newManifest = await manifestManager.buildNewManifest(oldManifest!); const diffs = newManifest.diff(oldManifest!); const newArtifactId = diffs[1].id; await newManifest.compressArtifact(newArtifactId); + newManifest.bumpSemanticVersion(); + packageConfigService.update.mockRejectedValueOnce({ status: 409 }); const dispatchErrors = await manifestManager.tryDispatch(newManifest); expect(dispatchErrors).toEqual([{ status: 409 }]); @@ -202,13 +171,8 @@ describe('manifest_manager', () => { savedObjectsClient, }); - const oldManifest = await manifestManager.getLastComputedManifest( - ManifestConstants.SCHEMA_VERSION - ); - const newManifest = await manifestManager.buildNewManifest( - ManifestConstants.SCHEMA_VERSION, - oldManifest! - ); + const oldManifest = await manifestManager.getLastComputedManifest(); + const newManifest = await manifestManager.buildNewManifest(oldManifest!); const diffs = newManifest.diff(oldManifest!); const oldArtifactId = diffs[0].id; const newArtifactId = diffs[1].id; diff --git a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.ts b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.ts index 13ca51e1f2b39..217fd6de2ba68 100644 --- a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.ts +++ b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - +import semver from 'semver'; import { Logger, SavedObjectsClientContract } from 'src/core/server'; import LRU from 'lru-cache'; import { PackageConfigServiceInterface } from '../../../../../../ingest_manager/server'; @@ -13,7 +13,6 @@ import { manifestDispatchSchema } from '../../../../../common/endpoint/schema/ma import { ArtifactConstants, - ManifestConstants, Manifest, buildArtifact, getFullEndpointExceptionList, @@ -52,6 +51,7 @@ export class ManifestManager { protected savedObjectsClient: SavedObjectsClientContract; protected logger: Logger; protected cache: LRU; + protected schemaVersion: ManifestSchemaVersion; constructor(context: ManifestManagerContext) { this.artifactClient = context.artifactClient; @@ -60,28 +60,27 @@ export class ManifestManager { this.savedObjectsClient = context.savedObjectsClient; this.logger = context.logger; this.cache = context.cache; + this.schemaVersion = 'v1'; } /** - * Gets a ManifestClient for the provided schemaVersion. + * Gets a ManifestClient for this manager's schemaVersion. * - * @param schemaVersion The schema version of the manifest. - * @returns {ManifestClient} A ManifestClient scoped to the provided schemaVersion. + * @returns {ManifestClient} A ManifestClient scoped to the appropriate schemaVersion. */ - protected getManifestClient(schemaVersion: string): ManifestClient { - return new ManifestClient(this.savedObjectsClient, schemaVersion as ManifestSchemaVersion); + protected getManifestClient(): ManifestClient { + return new ManifestClient(this.savedObjectsClient, this.schemaVersion); } /** * Builds an array of artifacts (one per supported OS) based on the current * state of exception-list-agnostic SOs. * - * @param schemaVersion The schema version of the artifact * @returns {Promise} An array of uncompressed artifacts built from exception-list-agnostic SOs. * @throws Throws/rejects if there are errors building the list. */ protected async buildExceptionListArtifacts( - schemaVersion: string + artifactSchemaVersion?: string ): Promise { return ArtifactConstants.SUPPORTED_OPERATING_SYSTEMS.reduce< Promise @@ -89,10 +88,10 @@ export class ManifestManager { const exceptionList = await getFullEndpointExceptionList( this.exceptionListClient, os, - schemaVersion + artifactSchemaVersion ?? 'v1' ); const artifacts = await acc; - const artifact = await buildArtifact(exceptionList, os, schemaVersion); + const artifact = await buildArtifact(exceptionList, os, artifactSchemaVersion ?? 'v1'); return Promise.resolve([...artifacts, artifact]); }, Promise.resolve([])); } @@ -112,7 +111,7 @@ export class ManifestManager { // Cache the compressed body of the artifact this.cache.set(artifactId, Buffer.from(artifact.body, 'base64')); } catch (err) { - if (err.status === 409) { + if (this.savedObjectsClient.errors.isConflictError(err)) { this.logger.debug(`Tried to create artifact ${artifactId}, but it already exists.`); } else { return err; @@ -168,20 +167,23 @@ export class ManifestManager { * Returns the last computed manifest based on the state of the * user-artifact-manifest SO. * - * @param schemaVersion The schema version of the manifest. * @returns {Promise} The last computed manifest, or null if does not exist. * @throws Throws/rejects if there is an unexpected error retrieving the manifest. */ - public async getLastComputedManifest(schemaVersion: string): Promise { + public async getLastComputedManifest(): Promise { try { - const manifestClient = this.getManifestClient(schemaVersion); + const manifestClient = this.getManifestClient(); const manifestSo = await manifestClient.getManifest(); if (manifestSo.version === undefined) { throw new Error('No version returned for manifest.'); } - const manifest = new Manifest(schemaVersion, manifestSo.version); + const manifest = new Manifest({ + schemaVersion: this.schemaVersion, + semanticVersion: manifestSo.attributes.semanticVersion, + soVersion: manifestSo.version, + }); for (const id of manifestSo.attributes.ids) { const artifactSo = await this.artifactClient.getArtifact(id); @@ -199,22 +201,17 @@ export class ManifestManager { /** * Builds a new manifest based on the current user exception list. * - * @param schemaVersion The schema version of the manifest. * @param baselineManifest A baseline manifest to use for initializing pre-existing artifacts. * @returns {Promise} A new Manifest object reprenting the current exception list. */ - public async buildNewManifest( - schemaVersion: string, - baselineManifest?: Manifest - ): Promise { + public async buildNewManifest(baselineManifest?: Manifest): Promise { // Build new exception list artifacts - const artifacts = await this.buildExceptionListArtifacts(ArtifactConstants.SCHEMA_VERSION); + const artifacts = await this.buildExceptionListArtifacts(); // Build new manifest const manifest = Manifest.fromArtifacts( artifacts, - ManifestConstants.SCHEMA_VERSION, - baselineManifest ?? Manifest.getDefault(schemaVersion) + baselineManifest ?? Manifest.getDefault(this.schemaVersion) ); return manifest; @@ -247,14 +244,12 @@ export class ManifestManager { for (const packageConfig of items) { const { id, revision, updated_at, updated_by, ...newPackageConfig } = packageConfig; if (newPackageConfig.inputs.length > 0 && newPackageConfig.inputs[0].config !== undefined) { - const artifactManifest = newPackageConfig.inputs[0].config.artifact_manifest ?? { + const oldManifest = newPackageConfig.inputs[0].config.artifact_manifest ?? { value: {}, }; - const oldManifest = - Manifest.fromPkgConfig(artifactManifest.value) ?? - Manifest.getDefault(ManifestConstants.SCHEMA_VERSION); - if (!manifest.equals(oldManifest)) { + const newManifestVersion = manifest.getSemanticVersion(); + if (semver.gt(newManifestVersion, oldManifest.value.manifest_version)) { newPackageConfig.inputs[0].config.artifact_manifest = { value: serializedManifest, }; @@ -262,7 +257,7 @@ export class ManifestManager { try { await this.packageConfigService.update(this.savedObjectsClient, id, newPackageConfig); this.logger.debug( - `Updated package config ${id} with manifest version ${manifest.getSha256()}` + `Updated package config ${id} with manifest version ${manifest.getSemanticVersion()}` ); } catch (err) { errors.push(err); @@ -274,8 +269,7 @@ export class ManifestManager { errors.push(new Error(`Package config ${id} has no config.`)); } } - - paging = page * items.length < total; + paging = (page - 1) * 20 + items.length < total; page++; } @@ -290,11 +284,11 @@ export class ManifestManager { */ public async commit(manifest: Manifest): Promise { try { - const manifestClient = this.getManifestClient(manifest.getSchemaVersion()); + const manifestClient = this.getManifestClient(); // Commit the new manifest const manifestSo = manifest.toSavedObject(); - const version = manifest.getSoVersion(); + const version = manifest.getSavedObjectVersion(); if (version == null) { await manifestClient.createManifest(manifestSo); @@ -304,7 +298,7 @@ export class ManifestManager { }); } - this.logger.info(`Committed manifest ${manifest.getSha256()}`); + this.logger.info(`Committed manifest ${manifest.getSemanticVersion()}`); } catch (err) { return err; } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/create_notifications.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/create_notifications.ts index a472d8a4df4a4..8f6826cec5365 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/create_notifications.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/notifications/create_notifications.ts @@ -5,7 +5,7 @@ */ import { Alert } from '../../../../../alerts/common'; -import { APP_ID, NOTIFICATIONS_ID } from '../../../../common/constants'; +import { SERVER_APP_ID, NOTIFICATIONS_ID } from '../../../../common/constants'; import { CreateNotificationParams } from './types'; import { addTags } from './add_tags'; import { transformRuleToAlertAction } from '../../../../common/detection_engine/transform_actions'; @@ -23,7 +23,7 @@ export const createNotifications = async ({ name, tags: addTags([], ruleAlertId), alertTypeId: NOTIFICATIONS_ID, - consumer: APP_ID, + consumer: SERVER_APP_ID, params: { ruleAlertId, }, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/index.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/index.ts index bfaab096a5013..196d816b6b257 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/index.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/index.ts @@ -25,6 +25,8 @@ export const createMockConfig = () => ({ from: 'now-15m', to: 'now', }, + packagerTaskInterval: '60s', + validateArtifactDownloads: true, }); export const mockGetCurrentUser = { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.test.ts index f8b6f7e3ddcba..fa2a575d3f69f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.test.ts @@ -14,6 +14,11 @@ import { } from '../__mocks__/request_responses'; import { requestContextMock, serverMock, createMockConfig } from '../__mocks__'; import { SecurityPluginSetup } from '../../../../../../security/server'; +import { checkTimelinesStatus } from '../../../timeline/routes/utils/check_timelines_status'; +import { + mockCheckTimelinesStatusBeforeInstallResult, + mockCheckTimelinesStatusAfterInstallResult, +} from '../../../timeline/routes/__mocks__/import_timelines'; jest.mock('../../rules/get_prepackaged_rules', () => { return { @@ -38,6 +43,12 @@ jest.mock('../../rules/get_prepackaged_rules', () => { }; }); +jest.mock('../../../timeline/routes/utils/check_timelines_status', () => { + return { + checkTimelinesStatus: jest.fn(), + }; +}); + describe('get_prepackaged_rule_status_route', () => { const mockGetCurrentUser = { user: { @@ -126,5 +137,45 @@ describe('get_prepackaged_rule_status_route', () => { timelines_not_updated: 0, }); }); + + test('0 timelines installed, 3 timelines not installed, 0 timelines not updated', async () => { + clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + (checkTimelinesStatus as jest.Mock).mockResolvedValue( + mockCheckTimelinesStatusBeforeInstallResult + ); + const request = getPrepackagedRulesStatusRequest(); + const response = await server.inject(request, context); + + expect(response.status).toEqual(200); + expect(response.body).toEqual({ + rules_custom_installed: 0, + rules_installed: 0, + rules_not_installed: 1, + rules_not_updated: 0, + timelines_installed: 0, + timelines_not_installed: 3, + timelines_not_updated: 0, + }); + }); + + test('3 timelines installed, 0 timelines not installed, 0 timelines not updated', async () => { + clients.alertsClient.find.mockResolvedValue(getEmptyFindResult()); + (checkTimelinesStatus as jest.Mock).mockResolvedValue( + mockCheckTimelinesStatusAfterInstallResult + ); + const request = getPrepackagedRulesStatusRequest(); + const response = await server.inject(request, context); + + expect(response.status).toEqual(200); + expect(response.body).toEqual({ + rules_custom_installed: 0, + rules_installed: 0, + rules_not_installed: 1, + rules_not_updated: 0, + timelines_installed: 3, + timelines_not_installed: 0, + timelines_not_updated: 0, + }); + }); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts index ad4038b05dbd3..0c67d9ca77146 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts @@ -6,7 +6,7 @@ import { transformRuleToAlertAction } from '../../../../common/detection_engine/transform_actions'; import { Alert } from '../../../../../alerts/common'; -import { APP_ID, SIGNALS_ID } from '../../../../common/constants'; +import { SERVER_APP_ID, SIGNALS_ID } from '../../../../common/constants'; import { CreateRulesOptions } from './types'; import { addTags } from './add_tags'; @@ -57,7 +57,7 @@ export const createRules = async ({ name, tags: addTags(tags, ruleId, immutable), alertTypeId: SIGNALS_ID, - consumer: APP_ID, + consumer: SERVER_APP_ID, params: { anomalyThreshold, author, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_cloudtrail_logging_created.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_cloudtrail_logging_created.json index 4437612a5056b..ee39661ee9b10 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_cloudtrail_logging_created.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_cloudtrail_logging_created.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS CloudTrail Log Created", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:CreateTrail and event.dataset:aws.cloudtrail and event.provider:cloudtrail.amazonaws.com and event.outcome:success", "references": [ "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_CreateTrail.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_attempted_bypass_of_okta_mfa.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_attempted_bypass_of_okta_mfa.json index e3e4b7b54c3b2..eb8523b797ddf 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_attempted_bypass_of_okta_mfa.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_attempted_bypass_of_okta_mfa.json @@ -9,6 +9,7 @@ "language": "kuery", "license": "Elastic License", "name": "Attempted Bypass of Okta MFA", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:user.mfa.attempt_bypass", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_aws_iam_assume_role_brute_force.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_aws_iam_assume_role_brute_force.json new file mode 100644 index 0000000000000..ddc9e91782136 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_aws_iam_assume_role_brute_force.json @@ -0,0 +1,49 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies a high number of failed attempts to assume an AWS Identity and Access Management (IAM) role. IAM roles are used to delegate access to users or services. An adversary may attempt to enumerate IAM roles in order to determine if a role exists before attempting to assume or hijack the discovered role.", + "from": "now-20m", + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "AWS IAM Brute Force of Assume Role Policy", + "note": "The AWS Filebeat module must be enabled to use this rule.", + "query": "event.module:aws and event.dataset:aws.cloudtrail and event.provider:iam.amazonaws.com and event.action:UpdateAssumeRolePolicy and aws.cloudtrail.error_code:MalformedPolicyDocumentException and event.outcome:failure", + "references": [ + "https://www.praetorian.com/blog/aws-iam-assume-role-vulnerabilities", + "https://rhinosecuritylabs.com/aws/assume-worst-aws-assume-role-enumeration/" + ], + "risk_score": 47, + "rule_id": "ea248a02-bc47-4043-8e94-2885b19b2636", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0006", + "name": "Credential Access", + "reference": "https://attack.mitre.org/tactics/TA0006/" + }, + "technique": [ + { + "id": "T1110", + "name": "Brute Force", + "reference": "https://attack.mitre.org/techniques/T1110/" + } + ] + } + ], + "threshold": { + "field": "", + "value": 25 + }, + "type": "threshold", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_iam_user_addition_to_group.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_iam_user_addition_to_group.json index 1e268d2f6bf06..ecbf268550b6c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_iam_user_addition_to_group.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_iam_user_addition_to_group.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS IAM User Addition to Group", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:AddUserToGroup and event.dataset:aws.cloudtrail and event.provider:iam.amazonaws.com and event.outcome:success", "references": [ "https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddUserToGroup.html" diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_okta_brute_force_or_password_spraying.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_okta_brute_force_or_password_spraying.json new file mode 100644 index 0000000000000..87f20525203f6 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_okta_brute_force_or_password_spraying.json @@ -0,0 +1,51 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies a high number of failed Okta user authentication attempts from a single IP address, which could be indicative of a brute force or password spraying attack. An adversary may attempt a brute force or password spraying attack to obtain unauthorized access to user accounts.", + "false_positives": [ + "Automated processes that attempt to authenticate using expired credentials and unbounded retries may lead to false positives." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Okta Brute Force or Password Spraying Attack", + "note": "The Okta Filebeat module must be enabled to use this rule.", + "query": "event.module:okta and event.dataset:okta.system and event.category:authentication and event.outcome:failure", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 47, + "rule_id": "42bf698b-4738-445b-8231-c834ddefd8a0", + "severity": "medium", + "tags": [ + "Elastic", + "Okta" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0006", + "name": "Credential Access", + "reference": "https://attack.mitre.org/tactics/TA0006/" + }, + "technique": [ + { + "id": "T1110", + "name": "Brute Force", + "reference": "https://attack.mitre.org/techniques/T1110/" + } + ] + } + ], + "threshold": { + "field": "source.ip", + "value": 25 + }, + "type": "threshold", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_secretsmanager_getsecretvalue.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_secretsmanager_getsecretvalue.json index 740805f71a3cd..f570b7fb3e946 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_secretsmanager_getsecretvalue.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_secretsmanager_getsecretvalue.json @@ -15,6 +15,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS Access Secret in Secrets Manager", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.dataset:aws.cloudtrail and event.provider:secretsmanager.amazonaws.com and event.action:GetSecretValue", "references": [ "https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_deleted.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_deleted.json index 2a74b8fecd809..78f4c9e853f64 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_deleted.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_deleted.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS CloudTrail Log Deleted", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:DeleteTrail and event.dataset:aws.cloudtrail and event.provider:cloudtrail.amazonaws.com and event.outcome:success", "references": [ "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_DeleteTrail.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_suspended.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_suspended.json index 5d6c1a93bab1d..f412ad9b2e2fd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_suspended.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_suspended.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS CloudTrail Log Suspended", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:StopLogging and event.dataset:aws.cloudtrail and event.provider:cloudtrail.amazonaws.com and event.outcome:success", "references": [ "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_StopLogging.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudwatch_alarm_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudwatch_alarm_deletion.json index 9ac45ba872809..b76ea0944f855 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudwatch_alarm_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudwatch_alarm_deletion.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS CloudWatch Alarm Deletion", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:DeleteAlarms and event.dataset:aws.cloudtrail and event.provider:monitoring.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-alarms.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_config_service_rule_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_config_service_rule_deletion.json index 9ef37bd4e44e1..353067e6db833 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_config_service_rule_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_config_service_rule_deletion.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS Config Service Tampering", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.dataset: aws.cloudtrail and event.action: DeleteConfigRule and event.provider: config.amazonaws.com", "references": [ "https://docs.aws.amazon.com/config/latest/developerguide/how-does-config-work.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_configuration_recorder_stopped.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_configuration_recorder_stopped.json index 0aed7aa5ad0ca..b70aa5cd11b52 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_configuration_recorder_stopped.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_configuration_recorder_stopped.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS Configuration Recorder Stopped", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:StopConfigurationRecorder and event.dataset:aws.cloudtrail and event.provider:config.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/stop-configuration-recorder.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_flow_log_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_flow_log_deletion.json index b1f6c42f6f61a..a1b0ec0f01d2a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_flow_log_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_flow_log_deletion.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS EC2 Flow Log Deletion", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:DeleteFlowLogs and event.dataset:aws.cloudtrail and event.provider:ec2.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-flow-logs.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_network_acl_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_network_acl_deletion.json index 7dc4e33afcd36..21ce4e498ccaf 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_network_acl_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_network_acl_deletion.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS EC2 Network Access Control List Deletion", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:(DeleteNetworkAcl or DeleteNetworkAclEntry) and event.dataset:aws.cloudtrail and event.provider:ec2.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-acl.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_guardduty_detector_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_guardduty_detector_deletion.json index c456396c85cd8..989eff90aaf02 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_guardduty_detector_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_guardduty_detector_deletion.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS GuardDuty Detector Deletion", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:DeleteDetector and event.dataset:aws.cloudtrail and event.provider:guardduty.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/delete-detector.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_s3_bucket_configuration_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_s3_bucket_configuration_deletion.json index 77f9e0f4a313c..b1e8d0cd0d3e1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_s3_bucket_configuration_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_s3_bucket_configuration_deletion.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS S3 Bucket Configuration Deletion", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:(DeleteBucketPolicy or DeleteBucketReplication or DeleteBucketCors or DeleteBucketEncryption or DeleteBucketLifecycle) and event.dataset:aws.cloudtrail and event.provider:s3.amazonaws.com and event.outcome:success", "references": [ "https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketPolicy.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_acl_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_acl_deletion.json index 708f931a5f8ab..b2092dc78b012 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_acl_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_acl_deletion.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS WAF Access Control List Deletion", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:DeleteWebACL and event.dataset:aws.cloudtrail and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf-regional/delete-web-acl.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_rule_or_rule_group_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_rule_or_rule_group_deletion.json index 37dae51ec3125..ccec76b7f7974 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_rule_or_rule_group_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_rule_or_rule_group_deletion.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS WAF Rule or Rule Group Deletion", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.module:aws and event.dataset:aws.cloudtrail and event.action:(DeleteRule or DeleteRuleGroup) and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf/delete-rule-group.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint.json index 396803086552e..05601ec8ffb4c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint.json @@ -1,24 +1,21 @@ { - "author": [ - "Elastic" - ], - "description": "Generates a detection alert each time an Elastic Endpoint alert is received. Enabling this rule allows you to immediately begin investigating your Elastic Endpoint alerts.", + "author": ["Elastic"], + "description": "Generates a detection alert each time an Elastic Endpoint Security alert is received. Enabling this rule allows you to immediately begin investigating your Elastic Endpoint alerts.", "enabled": true, "exceptions_list": [ { "id": "endpoint_list", + "list_id": "endpoint_list", "namespace_type": "agnostic", "type": "endpoint" } ], "from": "now-10m", - "index": [ - "logs-endpoint.alerts-*" - ], + "index": ["logs-endpoint.alerts-*"], "language": "kuery", "license": "Elastic License", "max_signals": 10000, - "name": "Elastic Endpoint", + "name": "Elastic Endpoint Security", "query": "event.kind:alert and event.module:(endpoint and not endgame)", "risk_score": 47, "risk_score_mapping": [ @@ -57,10 +54,7 @@ "value": "99" } ], - "tags": [ - "Elastic", - "Endpoint" - ], + "tags": ["Elastic", "Endpoint"], "timestamp_override": "event.ingested", "type": "query", "version": 1 diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_adversary_behavior_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_adversary_behavior_detected.json index 5075630e24f29..16584a03a3c91 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_adversary_behavior_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_adversary_behavior_detected.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint detected an Adversary Behavior. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security detected an Adversary Behavior. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Adversary Behavior - Detected - Elastic Endpoint", + "name": "Adversary Behavior - Detected - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and (event.action:rules_engine_event or endgame.event_subtype_full:rules_engine_event)", "risk_score": 47, "rule_id": "77a3c3df-8ec4-4da4-b758-878f551dee69", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_detected.json index 4bf9ba8ec36e1..5717c490114b9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_detected.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint detected Credential Dumping. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security detected Credential Dumping. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Credential Dumping - Detected - Elastic Endpoint", + "name": "Credential Dumping - Detected - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:cred_theft_event or endgame.event_subtype_full:cred_theft_event)", "risk_score": 73, "rule_id": "571afc56-5ed9-465d-a2a9-045f099f6e7e", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_prevented.json index bed473b12b046..5c1b2cb02b841 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_prevented.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint prevented Credential Dumping. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security prevented Credential Dumping. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Credential Dumping - Prevented - Elastic Endpoint", + "name": "Credential Dumping - Prevented - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:cred_theft_event or endgame.event_subtype_full:cred_theft_event)", "risk_score": 47, "rule_id": "db8c33a8-03cd-4988-9e2c-d0a4863adb13", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_detected.json index 02ba20bb59aec..16ad12a94ec40 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_detected.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint detected Credential Manipulation. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security detected Credential Manipulation. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Credential Manipulation - Detected - Elastic Endpoint", + "name": "Credential Manipulation - Detected - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:token_manipulation_event or endgame.event_subtype_full:token_manipulation_event)", "risk_score": 73, "rule_id": "c0be5f31-e180-48ed-aa08-96b36899d48f", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_prevented.json index 128f8d5639d5d..9addcbf2fba30 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_prevented.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint prevented Credential Manipulation. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security prevented Credential Manipulation. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Credential Manipulation - Prevented - Elastic Endpoint", + "name": "Credential Manipulation - Prevented - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:token_manipulation_event or endgame.event_subtype_full:token_manipulation_event)", "risk_score": 47, "rule_id": "c9e38e64-3f4c-4bf3-ad48-0e61a60ea1fa", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_detected.json index a11b839792b79..f51a38781c953 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_detected.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint detected an Exploit. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security detected an Exploit. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Exploit - Detected - Elastic Endpoint", + "name": "Exploit - Detected - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:exploit_event or endgame.event_subtype_full:exploit_event)", "risk_score": 73, "rule_id": "2003cdc8-8d83-4aa5-b132-1f9a8eb48514", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_prevented.json index 2deb7bce3b203..8b96c5a63fbef 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_prevented.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint prevented an Exploit. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security prevented an Exploit. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Exploit - Prevented - Elastic Endpoint", + "name": "Exploit - Prevented - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:exploit_event or endgame.event_subtype_full:exploit_event)", "risk_score": 47, "rule_id": "2863ffeb-bf77-44dd-b7a5-93ef94b72036", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_detected.json index d1389b21f2d7e..28ff73468deb4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_detected.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint detected Malware. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security detected Malware. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Malware - Detected - Elastic Endpoint", + "name": "Malware - Detected - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:file_classification_event or endgame.event_subtype_full:file_classification_event)", "risk_score": 99, "rule_id": "0a97b20f-4144-49ea-be32-b540ecc445de", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_prevented.json index b83bc259175c6..3d32abf2bf8f2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_prevented.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint prevented Malware. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security prevented Malware. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Malware - Prevented - Elastic Endpoint", + "name": "Malware - Prevented - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:file_classification_event or endgame.event_subtype_full:file_classification_event)", "risk_score": 73, "rule_id": "3b382770-efbb-44f4-beed-f5e0a051b895", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_detected.json index b81b9c67644c6..a89a7f7d5918c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_detected.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint detected Permission Theft. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security detected Permission Theft. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Permission Theft - Detected - Elastic Endpoint", + "name": "Permission Theft - Detected - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:token_protection_event or endgame.event_subtype_full:token_protection_event)", "risk_score": 73, "rule_id": "c3167e1b-f73c-41be-b60b-87f4df707fe3", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_prevented.json index b69598cffc230..fb9dbe3dadb17 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_prevented.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint prevented Permission Theft. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security prevented Permission Theft. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Permission Theft - Prevented - Elastic Endpoint", + "name": "Permission Theft - Prevented - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:token_protection_event or endgame.event_subtype_full:token_protection_event)", "risk_score": 47, "rule_id": "453f659e-0429-40b1-bfdb-b6957286e04b", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_detected.json index 8299e11392398..e022d058d7560 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_detected.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint detected Process Injection. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security detected Process Injection. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Process Injection - Detected - Elastic Endpoint", + "name": "Process Injection - Detected - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:kernel_shellcode_event or endgame.event_subtype_full:kernel_shellcode_event)", "risk_score": 73, "rule_id": "80c52164-c82a-402c-9964-852533d58be1", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_prevented.json index 237558ae372a8..2d189707293f1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_prevented.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint prevented Process Injection. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security prevented Process Injection. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Process Injection - Prevented - Elastic Endpoint", + "name": "Process Injection - Prevented - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:kernel_shellcode_event or endgame.event_subtype_full:kernel_shellcode_event)", "risk_score": 47, "rule_id": "990838aa-a953-4f3e-b3cb-6ddf7584de9e", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_detected.json index 4ead850c60e8f..077c20bca5d8e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_detected.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint detected Ransomware. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security detected Ransomware. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Ransomware - Detected - Elastic Endpoint", + "name": "Ransomware - Detected - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:ransomware_event or endgame.event_subtype_full:ransomware_event)", "risk_score": 99, "rule_id": "8cb4f625-7743-4dfb-ae1b-ad92be9df7bd", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_prevented.json index 25d167afa204c..b615fcb04895e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_prevented.json @@ -2,7 +2,7 @@ "author": [ "Elastic" ], - "description": "Elastic Endpoint prevented Ransomware. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", + "description": "Elastic Endpoint Security prevented Ransomware. Click the Elastic Endpoint Security icon in the event.module column or the link in the rule.reference column for additional information.", "from": "now-15m", "index": [ "endgame-*" @@ -10,7 +10,7 @@ "interval": "10m", "language": "kuery", "license": "Elastic License", - "name": "Ransomware - Prevented - Elastic Endpoint", + "name": "Ransomware - Prevented - Elastic Endpoint Security", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:ransomware_event or endgame.event_subtype_full:ransomware_event)", "risk_score": 73, "rule_id": "e3c5d5cb-41d5-4206-805c-f30561eae3ac", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_system_manager.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_system_manager.json index 90338f4460725..a9f8ee1af8bf6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_system_manager.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_system_manager.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS Execution via System Manager", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.module:aws and event.dataset:aws.cloudtrail and event.provider:ssm.amazonaws.com and event.action:SendCommand and event.outcome:success", "references": [ "https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-plugins.html" diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/exfiltration_ec2_snapshot_change_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/exfiltration_ec2_snapshot_change_activity.json index 04cc697cf36f9..25711afbb4c66 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/exfiltration_ec2_snapshot_change_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/exfiltration_ec2_snapshot_change_activity.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS EC2 Snapshot Activity", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.module:aws and event.dataset:aws.cloudtrail and event.provider:ec2.amazonaws.com and event.action:ModifySnapshotAttribute", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-snapshot-attribute.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/external_alerts.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/external_alerts.json index c8ebb2ed0e5d7..8b627c48d2904 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/external_alerts.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/external_alerts.json @@ -1,8 +1,14 @@ { - "author": [ - "Elastic" + "author": ["Elastic"], + "description": "Generates a detection alert for each external alert written to the configured indices. Enabling this rule allows you to immediately begin investigating external alerts in the app.", + "index": [ + "apm-*-transaction*", + "auditbeat-*", + "filebeat-*", + "logs-*", + "packetbeat-*", + "winlogbeat-*" ], - "description": "Generates a detection alert for each external alert written to the configured securitySolution:defaultIndex. Enabling this rule allows you to immediately begin investigating external alerts in the app.", "language": "kuery", "license": "Elastic License", "max_signals": 10000, @@ -45,9 +51,7 @@ "value": "99" } ], - "tags": [ - "Elastic" - ], + "tags": ["Elastic"], "timestamp_override": "event.ingested", "type": "query", "version": 1 diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_attempt_to_revoke_okta_api_token.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_attempt_to_revoke_okta_api_token.json index 0f4ded9fcfe87..27e50313c8f82 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_attempt_to_revoke_okta_api_token.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_attempt_to_revoke_okta_api_token.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Attempt to Revoke Okta API Token", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:system.api_token.revoke", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudtrail_logging_updated.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudtrail_logging_updated.json index d969ef21027f0..0bafa56c9af49 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudtrail_logging_updated.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudtrail_logging_updated.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS CloudTrail Log Updated", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:UpdateTrail and event.dataset:aws.cloudtrail and event.provider:cloudtrail.amazonaws.com and event.outcome:success", "references": [ "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_UpdateTrail.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_group_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_group_deletion.json index d33593d4a44b2..74b5e0d93c441 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_group_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_group_deletion.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS CloudWatch Log Group Deletion", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:DeleteLogGroup and event.dataset:aws.cloudtrail and event.provider:logs.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/delete-log-group.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_stream_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_stream_deletion.json index a1108dd07abdd..59c659117c098 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_stream_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_stream_deletion.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS CloudWatch Log Stream Deletion", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:DeleteLogStream and event.dataset:aws.cloudtrail and event.provider:logs.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/delete-log-stream.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_ec2_disable_ebs_encryption.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_ec2_disable_ebs_encryption.json index 4681b475d92e7..10a1989ad6423 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_ec2_disable_ebs_encryption.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_ec2_disable_ebs_encryption.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS EC2 Encryption Disabled", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:DisableEbsEncryptionByDefault and event.dataset:aws.cloudtrail and event.provider:ec2.amazonaws.com and event.outcome:success", "references": [ "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_deactivate_mfa_device.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_deactivate_mfa_device.json index f873e3483a34f..4aa0b355171fe 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_deactivate_mfa_device.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_deactivate_mfa_device.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS IAM Deactivation of MFA Device", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:DeactivateMFADevice and event.dataset:aws.cloudtrail and event.provider:iam.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/deactivate-mfa-device.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_group_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_group_deletion.json index 23364c8b3aa28..25b300d33cce1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_group_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_group_deletion.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS IAM Group Deletion", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:DeleteGroup and event.dataset:aws.cloudtrail and event.provider:iam.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-group.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_possible_okta_dos_attack.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_possible_okta_dos_attack.json index 8c76f182442a5..9ca8b7ed21acb 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_possible_okta_dos_attack.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_possible_okta_dos_attack.json @@ -9,6 +9,7 @@ "language": "kuery", "license": "Elastic License", "name": "Possible Okta DoS Attack", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:(application.integration.rate_limit_exceeded or system.org.rate_limit.warning or system.org.rate_limit.violation or core.concurrency.org.limit.violation)", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_cluster_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_cluster_deletion.json index 88ec942b0e5e5..e8343f1b7b7c6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_cluster_deletion.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_cluster_deletion.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS RDS Cluster Deletion", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:(DeleteDBCluster or DeleteGlobalCluster) and event.dataset:aws.cloudtrail and event.provider:rds.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-cluster.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_instance_cluster_stoppage.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_instance_cluster_stoppage.json index 2c25781e24d19..8c4387e60d281 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_instance_cluster_stoppage.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_instance_cluster_stoppage.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS RDS Instance/Cluster Stoppage", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:(StopDBCluster or StopDBInstance) and event.dataset:aws.cloudtrail and event.provider:rds.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/stop-db-cluster.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/index.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/index.ts index f2e2137eec41b..685c869630ca3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/index.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/index.ts @@ -210,6 +210,8 @@ import rule198 from './ml_cloudtrail_rare_error_code.json'; import rule199 from './ml_cloudtrail_rare_method_by_city.json'; import rule200 from './ml_cloudtrail_rare_method_by_country.json'; import rule201 from './ml_cloudtrail_rare_method_by_user.json'; +import rule202 from './credential_access_aws_iam_assume_role_brute_force.json'; +import rule203 from './credential_access_okta_brute_force_or_password_spraying.json'; export const rawRules = [ rule1, @@ -413,4 +415,6 @@ export const rawRules = [ rule199, rule200, rule201, + rule202, + rule203, ]; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_console_login_root.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_console_login_root.json index 0f761f0d2a5f5..829d87c1964c9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_console_login_root.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_console_login_root.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS Management Console Root Login", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:ConsoleLogin and event.module:aws and event.dataset:aws.cloudtrail and event.provider:signin.amazonaws.com and aws.cloudtrail.user_identity.type:Root and event.outcome:success", "references": [ "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html" diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_password_recovery.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_password_recovery.json index 1042ce19a14c7..7429c69fc3174 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_password_recovery.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_password_recovery.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS IAM Password Recovery Requested", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:PasswordRecoveryRequested and event.provider:signin.amazonaws.com and event.outcome:success", "references": [ "https://www.cadosecurity.com/2020/06/11/an-ongoing-aws-phishing-campaign/" diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_activity_reported_by_okta_user.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_activity_reported_by_okta_user.json index 5fa8a655c08bf..25bf7dd287d05 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_activity_reported_by_okta_user.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_activity_reported_by_okta_user.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Suspicious Activity Reported by Okta User", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:user.account.report_suspicious_activity_by_enduser", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_deactivate_okta_mfa_rule.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_deactivate_okta_mfa_rule.json index 737044d5a9bdc..1d15db83bb18e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_deactivate_okta_mfa_rule.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_deactivate_okta_mfa_rule.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Attempt to Deactivate Okta MFA Rule", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:policy.rule.deactivate", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_delete_okta_policy.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_delete_okta_policy.json index ea8ba7223095f..6df2ed6cb34a4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_delete_okta_policy.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_delete_okta_policy.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Attempt to Delete Okta Policy", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:policy.lifecycle.delete", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_mfa_rule.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_mfa_rule.json index dfe16f56da0e2..e276166f6130b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_mfa_rule.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_mfa_rule.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Attempt to Modify Okta MFA Rule", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:(policy.rule.update or policy.rule.delete)", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_network_zone.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_network_zone.json index 61c45f8e7d85e..bdfe7d25092ba 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_network_zone.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_network_zone.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Attempt to Modify Okta Network Zone", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:(zone.update or zone.deactivate or zone.delete or network_zone.rule.disabled or zone.remove_blacklist)", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_policy.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_policy.json index a864b900a5998..e3e0d5fef7b2f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_policy.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_policy.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Attempt to Modify Okta Policy", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:policy.lifecycle.update", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_or_delete_application_sign_on_policy.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_or_delete_application_sign_on_policy.json index ff7546ac2f1a6..ad21ebe065f8c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_or_delete_application_sign_on_policy.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_or_delete_application_sign_on_policy.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Modification or Removal of an Okta Application Sign-On Policy", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:(application.policy.sign_on.update or application.policy.sign_on.rule.delete)", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_threat_detected_by_okta_threatinsight.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_threat_detected_by_okta_threatinsight.json index 7a1b6e3d82d7c..e92cf3d67d313 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_threat_detected_by_okta_threatinsight.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_threat_detected_by_okta_threatinsight.json @@ -9,6 +9,7 @@ "language": "kuery", "license": "Elastic License", "name": "Threat Detected by Okta ThreatInsight", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:security.threat.detected", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_administrator_privileges_assigned_to_okta_group.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_administrator_privileges_assigned_to_okta_group.json index 70e7eb1706e1b..d5f3995fb8bcc 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_administrator_privileges_assigned_to_okta_group.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_administrator_privileges_assigned_to_okta_group.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Administrator Privileges Assigned to Okta Group", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:group.privilege.grant", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_create_okta_api_token.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_create_okta_api_token.json index 453580d580344..5f6c006c5d177 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_create_okta_api_token.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_create_okta_api_token.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Attempt to Create Okta API Token", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:system.api_token.create", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_mfa_for_okta_user_account.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_mfa_for_okta_user_account.json index e5648285c5289..d3a66ef8d9c77 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_mfa_for_okta_user_account.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_mfa_for_okta_user_account.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Attempt to Deactivate MFA for Okta User Account", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:user.mfa.factor.deactivate", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_okta_policy.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_okta_policy.json index 53da259042738..7104cace1c5d9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_okta_policy.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_okta_policy.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Attempt to Deactivate Okta Policy", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:policy.lifecycle.deactivate", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_reset_mfa_factors_for_okta_user_account.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_reset_mfa_factors_for_okta_user_account.json index f662c0c0b8eb6..c38f71d8e00a6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_reset_mfa_factors_for_okta_user_account.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_reset_mfa_factors_for_okta_user_account.json @@ -12,6 +12,7 @@ "language": "kuery", "license": "Elastic License", "name": "Attempt to Reset MFA Factors for Okta User Account", + "note": "The Okta Filebeat module must be enabled to use this rule.", "query": "event.module:okta and event.dataset:okta.system and event.action:user.mfa.factor.reset_all", "references": [ "https://developer.okta.com/docs/reference/api/system-log/", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_ec2_network_acl_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_ec2_network_acl_creation.json index 911536d2567f4..99bb07fe9660e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_ec2_network_acl_creation.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_ec2_network_acl_creation.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS EC2 Network Access Control List Creation", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:(CreateNetworkAcl or CreateNetworkAclEntry) and event.dataset:aws.cloudtrail and event.provider:ec2.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-network-acl.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_iam_group_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_iam_group_creation.json index 7c1c4d02737a6..9b2478b97fb38 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_iam_group_creation.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_iam_group_creation.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS IAM Group Creation", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:CreateGroup and event.dataset:aws.cloudtrail and event.provider:iam.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-group.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_rds_cluster_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_rds_cluster_creation.json index c6e23acab0fb5..94a695a97a27a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_rds_cluster_creation.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_rds_cluster_creation.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS RDS Cluster Creation", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.action:(CreateDBCluster or CreateGlobalCluster) and event.dataset:aws.cloudtrail and event.provider:rds.amazonaws.com and event.outcome:success", "references": [ "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-cluster.html", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_root_login_without_mfa.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_root_login_without_mfa.json index 6db9e04edc0cb..74c5376100b2b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_root_login_without_mfa.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_root_login_without_mfa.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS Root Login Without MFA", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.module:aws and event.dataset:aws.cloudtrail and event.provider:signin.amazonaws.com and event.action:ConsoleLogin and aws.cloudtrail.user_identity.type:Root and aws.cloudtrail.console_login.additional_eventdata.mfa_used:false and event.outcome:success", "references": [ "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html" diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_updateassumerolepolicy.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_updateassumerolepolicy.json index 623f90716b2b6..7ce54b00f211c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_updateassumerolepolicy.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_updateassumerolepolicy.json @@ -14,6 +14,7 @@ "language": "kuery", "license": "Elastic License", "name": "AWS IAM Assume Role Policy Update", + "note": "The AWS Filebeat module must be enabled to use this rule.", "query": "event.module:aws and event.dataset:aws.cloudtrail and event.provider:iam.amazonaws.com and event.action:UpdateAssumeRolePolicy and event.outcome:success", "references": [ "https://labs.bishopfox.com/tech-blog/5-privesc-attack-vectors-in-aws" diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/__mocks__/es_results.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/__mocks__/es_results.ts index 19fcf65ec0c5e..513d6a93d1b5b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/__mocks__/es_results.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/__mocks__/es_results.ts @@ -69,7 +69,8 @@ export const sampleDocNoSortIdNoVersion = (someUuid: string = sampleIdGuid): Sig export const sampleDocWithSortId = ( someUuid: string = sampleIdGuid, - ip?: string + ip?: string, + destIp?: string ): SignalSourceHit => ({ _index: 'myFakeSignalIndex', _type: 'doc', @@ -82,6 +83,9 @@ export const sampleDocWithSortId = ( source: { ip: ip ?? '127.0.0.1', }, + destination: { + ip: destIp ?? '127.0.0.1', + }, }, sort: ['1234567891111'], }); @@ -307,7 +311,8 @@ export const repeatedSearchResultsWithSortId = ( total: number, pageSize: number, guids: string[], - ips?: string[] + ips?: string[], + destIps?: string[] ) => ({ took: 10, timed_out: false, @@ -321,7 +326,11 @@ export const repeatedSearchResultsWithSortId = ( total, max_score: 100, hits: Array.from({ length: pageSize }).map((x, index) => ({ - ...sampleDocWithSortId(guids[index], ips ? ips[index] : '127.0.0.1'), + ...sampleDocWithSortId( + guids[index], + ips ? ips[index] : '127.0.0.1', + destIps ? destIps[index] : '127.0.0.1' + ), })), }, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.test.ts index 9eebb91c32652..8c39a254e4261 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.test.ts @@ -44,6 +44,25 @@ describe('filterEventsAgainstList', () => { expect(res.hits.hits.length).toEqual(4); }); + it('should respond with eventSearchResult if exceptionList does not contain value list exceptions', async () => { + const res = await filterEventsAgainstList({ + logger: mockLogger, + listClient, + exceptionsList: [getExceptionListItemSchemaMock()], + eventSearchResult: repeatedSearchResultsWithSortId(4, 4, someGuids.slice(0, 3), [ + '1.1.1.1', + '2.2.2.2', + '3.3.3.3', + '7.7.7.7', + ]), + buildRuleMessage, + }); + expect(res.hits.hits.length).toEqual(4); + expect(((mockLogger.debug as unknown) as jest.Mock).mock.calls[0][0]).toContain( + 'no exception items of type list found - returning original search result' + ); + }); + describe('operator_type is included', () => { it('should respond with same list if no items match value list', async () => { const exceptionItem = getExceptionListItemSchemaMock(); @@ -106,6 +125,280 @@ describe('filterEventsAgainstList', () => { 'ci-badguys.txt' ); expect(res.hits.hits.length).toEqual(2); + + // @ts-ignore + const ipVals = res.hits.hits.map((item) => item._source.source.ip); + expect(['3.3.3.3', '7.7.7.7']).toEqual(ipVals); + }); + + it('should respond with less items in the list given two exception items with entries of type list if some values match', async () => { + const exceptionItem = getExceptionListItemSchemaMock(); + exceptionItem.entries = [ + { + field: 'source.ip', + operator: 'included', + type: 'list', + list: { + id: 'ci-badguys.txt', + type: 'ip', + }, + }, + ]; + + const exceptionItemAgain = getExceptionListItemSchemaMock(); + exceptionItemAgain.entries = [ + { + field: 'source.ip', + operator: 'included', + type: 'list', + list: { + id: 'ci-badguys-again.txt', + type: 'ip', + }, + }, + ]; + + // this call represents an exception list with a value list containing ['2.2.2.2', '4.4.4.4'] + (listClient.getListItemByValues as jest.Mock).mockResolvedValueOnce([ + { ...getListItemResponseMock(), value: '2.2.2.2' }, + { ...getListItemResponseMock(), value: '4.4.4.4' }, + ]); + // this call represents an exception list with a value list containing ['6.6.6.6'] + (listClient.getListItemByValues as jest.Mock).mockResolvedValueOnce([ + { ...getListItemResponseMock(), value: '6.6.6.6' }, + ]); + + const res = await filterEventsAgainstList({ + logger: mockLogger, + listClient, + exceptionsList: [exceptionItem, exceptionItemAgain], + eventSearchResult: repeatedSearchResultsWithSortId(9, 9, someGuids.slice(0, 9), [ + '1.1.1.1', + '2.2.2.2', + '3.3.3.3', + '4.4.4.4', + '5.5.5.5', + '6.6.6.6', + '7.7.7.7', + '8.8.8.8', + '9.9.9.9', + ]), + buildRuleMessage, + }); + expect(listClient.getListItemByValues as jest.Mock).toHaveBeenCalledTimes(2); + expect(res.hits.hits.length).toEqual(6); + + // @ts-ignore + const ipVals = res.hits.hits.map((item) => item._source.source.ip); + expect(['1.1.1.1', '3.3.3.3', '5.5.5.5', '7.7.7.7', '8.8.8.8', '9.9.9.9']).toEqual(ipVals); + }); + + it('should respond with less items in the list given two exception items, each with one entry of type list if some values match', async () => { + const exceptionItem = getExceptionListItemSchemaMock(); + exceptionItem.entries = [ + { + field: 'source.ip', + operator: 'included', + type: 'list', + list: { + id: 'ci-badguys.txt', + type: 'ip', + }, + }, + ]; + + const exceptionItemAgain = getExceptionListItemSchemaMock(); + exceptionItemAgain.entries = [ + { + field: 'source.ip', + operator: 'included', + type: 'list', + list: { + id: 'ci-badguys-again.txt', + type: 'ip', + }, + }, + ]; + + // this call represents an exception list with a value list containing ['2.2.2.2', '4.4.4.4'] + (listClient.getListItemByValues as jest.Mock).mockResolvedValueOnce([ + { ...getListItemResponseMock(), value: '2.2.2.2' }, + ]); + // this call represents an exception list with a value list containing ['6.6.6.6'] + (listClient.getListItemByValues as jest.Mock).mockResolvedValueOnce([ + { ...getListItemResponseMock(), value: '6.6.6.6' }, + ]); + + const res = await filterEventsAgainstList({ + logger: mockLogger, + listClient, + exceptionsList: [exceptionItem, exceptionItemAgain], + eventSearchResult: repeatedSearchResultsWithSortId(9, 9, someGuids.slice(0, 9), [ + '1.1.1.1', + '2.2.2.2', + '3.3.3.3', + '4.4.4.4', + '5.5.5.5', + '6.6.6.6', + '7.7.7.7', + '8.8.8.8', + '9.9.9.9', + ]), + buildRuleMessage, + }); + expect(listClient.getListItemByValues as jest.Mock).toHaveBeenCalledTimes(2); + // @ts-ignore + const ipVals = res.hits.hits.map((item) => item._source.source.ip); + expect(res.hits.hits.length).toEqual(7); + + expect(['1.1.1.1', '3.3.3.3', '4.4.4.4', '5.5.5.5', '7.7.7.7', '8.8.8.8', '9.9.9.9']).toEqual( + ipVals + ); + }); + + it('should respond with less items in the list given one exception item with two entries of type list only if source.ip and destination.ip are in the events', async () => { + const exceptionItem = getExceptionListItemSchemaMock(); + exceptionItem.entries = [ + { + field: 'source.ip', + operator: 'included', + type: 'list', + list: { + id: 'ci-badguys.txt', + type: 'ip', + }, + }, + { + field: 'destination.ip', + operator: 'included', + type: 'list', + list: { + id: 'ci-badguys-again.txt', + type: 'ip', + }, + }, + ]; + + // this call represents an exception list with a value list containing ['2.2.2.2'] + (listClient.getListItemByValues as jest.Mock).mockResolvedValueOnce([ + { ...getListItemResponseMock(), value: '2.2.2.2' }, + ]); + // this call represents an exception list with a value list containing ['4.4.4.4'] + (listClient.getListItemByValues as jest.Mock).mockResolvedValueOnce([ + { ...getListItemResponseMock(), value: '4.4.4.4' }, + ]); + + const res = await filterEventsAgainstList({ + logger: mockLogger, + listClient, + exceptionsList: [exceptionItem], + eventSearchResult: repeatedSearchResultsWithSortId( + 9, + 9, + someGuids.slice(0, 9), + [ + '1.1.1.1', + '2.2.2.2', + '3.3.3.3', + '4.4.4.4', + '5.5.5.5', + '6.6.6.6', + '2.2.2.2', + '8.8.8.8', + '9.9.9.9', + ], + [ + '2.2.2.2', + '2.2.2.2', + '2.2.2.2', + '2.2.2.2', + '2.2.2.2', + '2.2.2.2', + '4.4.4.4', + '2.2.2.2', + '2.2.2.2', + ] + ), + buildRuleMessage, + }); + expect(listClient.getListItemByValues as jest.Mock).toHaveBeenCalledTimes(2); + expect(res.hits.hits.length).toEqual(8); + + // @ts-ignore + const ipVals = res.hits.hits.map((item) => item._source.source.ip); + expect([ + '1.1.1.1', + '2.2.2.2', + '3.3.3.3', + '4.4.4.4', + '5.5.5.5', + '6.6.6.6', + '8.8.8.8', + '9.9.9.9', + ]).toEqual(ipVals); + }); + + it('should respond with the same items in the list given one exception item with two entries of type list where the entries are included and excluded', async () => { + const exceptionItem = getExceptionListItemSchemaMock(); + exceptionItem.entries = [ + { + field: 'source.ip', + operator: 'included', + type: 'list', + list: { + id: 'ci-badguys.txt', + type: 'ip', + }, + }, + { + field: 'source.ip', + operator: 'excluded', + type: 'list', + list: { + id: 'ci-badguys-again.txt', + type: 'ip', + }, + }, + ]; + + // this call represents an exception list with a value list containing ['2.2.2.2', '4.4.4.4'] + (listClient.getListItemByValues as jest.Mock).mockResolvedValue([ + { ...getListItemResponseMock(), value: '2.2.2.2' }, + ]); + + const res = await filterEventsAgainstList({ + logger: mockLogger, + listClient, + exceptionsList: [exceptionItem], + eventSearchResult: repeatedSearchResultsWithSortId(9, 9, someGuids.slice(0, 9), [ + '1.1.1.1', + '2.2.2.2', + '3.3.3.3', + '4.4.4.4', + '5.5.5.5', + '6.6.6.6', + '7.7.7.7', + '8.8.8.8', + '9.9.9.9', + ]), + buildRuleMessage, + }); + expect(listClient.getListItemByValues as jest.Mock).toHaveBeenCalledTimes(2); + expect(res.hits.hits.length).toEqual(9); + + // @ts-ignore + const ipVals = res.hits.hits.map((item) => item._source.source.ip); + expect([ + '1.1.1.1', + '2.2.2.2', + '3.3.3.3', + '4.4.4.4', + '5.5.5.5', + '6.6.6.6', + '7.7.7.7', + '8.8.8.8', + '9.9.9.9', + ]).toEqual(ipVals); }); }); describe('operator type is excluded', () => { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts index ea52aecb379fa..262af5d88e227 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts @@ -10,9 +10,10 @@ import { ListClient } from '../../../../../lists/server'; import { SignalSearchResponse, SearchTypes } from './types'; import { BuildRuleMessage } from './rule_messages'; import { - entriesList, EntryList, ExceptionListItemSchema, + entriesList, + Type, } from '../../../../../lists/common/schemas'; import { hasLargeValueList } from '../../../../common/detection_engine/utils'; @@ -24,6 +25,51 @@ interface FilterEventsAgainstList { buildRuleMessage: BuildRuleMessage; } +export const createSetToFilterAgainst = async ({ + events, + field, + listId, + listType, + listClient, + logger, + buildRuleMessage, +}: { + events: SignalSearchResponse['hits']['hits']; + field: string; + listId: string; + listType: Type; + listClient: ListClient; + logger: Logger; + buildRuleMessage: BuildRuleMessage; +}): Promise> => { + // narrow unioned type to be single + const isStringableType = (val: SearchTypes) => + ['string', 'number', 'boolean'].includes(typeof val); + const valuesFromSearchResultField = events.reduce((acc, searchResultItem) => { + const valueField = get(field, searchResultItem._source); + if (valueField != null && isStringableType(valueField)) { + acc.add(valueField.toString()); + } + return acc; + }, new Set()); + logger.debug( + `number of distinct values from ${field}: ${[...valuesFromSearchResultField].length}` + ); + + // matched will contain any list items that matched with the + // values passed in from the Set. + const matchedListItems = await listClient.getListItemByValues({ + listId, + type: listType, + value: [...valuesFromSearchResultField], + }); + + logger.debug(`number of matched items from list with id ${listId}: ${matchedListItems.length}`); + // create a set of list values that were a hit - easier to work with + const matchedListItemsSet = new Set(matchedListItems.map((item) => item.value)); + return matchedListItemsSet; +}; + export const filterEventsAgainstList = async ({ listClient, exceptionsList, @@ -32,7 +78,6 @@ export const filterEventsAgainstList = async ({ buildRuleMessage, }: FilterEventsAgainstList): Promise => { try { - logger.debug(buildRuleMessage(`exceptionsList: ${JSON.stringify(exceptionsList, null, 2)}`)); if (exceptionsList == null || exceptionsList.length === 0) { logger.debug(buildRuleMessage('about to return original search result')); return eventSearchResult; @@ -51,87 +96,97 @@ export const filterEventsAgainstList = async ({ ); if (exceptionItemsWithLargeValueLists.length === 0) { - logger.debug(buildRuleMessage('about to return original search result')); + logger.debug( + buildRuleMessage('no exception items of type list found - returning original search result') + ); return eventSearchResult; } - // narrow unioned type to be single - const isStringableType = (val: SearchTypes) => - ['string', 'number', 'boolean'].includes(typeof val); - // grab the signals with values found in the given exception lists. - const filteredHitsPromises = exceptionItemsWithLargeValueLists.map( - async (exceptionItem: ExceptionListItemSchema) => { - const { entries } = exceptionItem; - - const filteredHitsEntries = entries - .filter((t): t is EntryList => entriesList.is(t)) - .map(async (entry) => { + const valueListExceptionItems = exceptionsList.filter((listItem: ExceptionListItemSchema) => { + return listItem.entries.every((entry) => entriesList.is(entry)); + }); + + // now that we have all the exception items which are value lists (whether single entry or have multiple entries) + const res = await valueListExceptionItems.reduce>( + async ( + filteredAccum: Promise, + exceptionItem: ExceptionListItemSchema + ) => { + // 1. acquire the values from the specified fields to check + // e.g. if the value list is checking against source.ip, gather + // all the values for source.ip from the search response events. + + // 2. search against the value list with the values found in the search result + // and see if there are any matches. For every match, add that value to a set + // that represents the "matched" values + + // 3. filter the search result against the set from step 2 using the + // given operator (included vs excluded). + // acquire the list values we are checking for in the field. + const filtered = await filteredAccum; + const typedEntries = exceptionItem.entries.filter((entry): entry is EntryList => + entriesList.is(entry) + ); + const fieldAndSetTuples = await Promise.all( + typedEntries.map(async (entry) => { const { list, field, operator } = entry; const { id, type } = list; - - // acquire the list values we are checking for. - const valuesOfGivenType = eventSearchResult.hits.hits.reduce( - (acc, searchResultItem) => { - const valueField = get(field, searchResultItem._source); - - if (valueField != null && isStringableType(valueField)) { - acc.add(valueField.toString()); - } - return acc; - }, - new Set() - ); - - // matched will contain any list items that matched with the - // values passed in from the Set. - const matchedListItems = await listClient.getListItemByValues({ + const matchedSet = await createSetToFilterAgainst({ + events: filtered, + field, listId: id, - type, - value: [...valuesOfGivenType], + listType: type, + listClient, + logger, + buildRuleMessage, }); - // create a set of list values that were a hit - easier to work with - const matchedListItemsSet = new Set( - matchedListItems.map((item) => item.value) - ); - - // do a single search after with these values. - // painless script to do nested query in elasticsearch - // filter out the search results that match with the values found in the list. - const filteredEvents = eventSearchResult.hits.hits.filter((item) => { - const eventItem = get(entry.field, item._source); - if (operator === 'included') { - if (eventItem != null) { - return !matchedListItemsSet.has(eventItem); - } - } else if (operator === 'excluded') { - if (eventItem != null) { - return matchedListItemsSet.has(eventItem); - } + return Promise.resolve({ field, operator, matchedSet }); + }) + ); + + // check if for each tuple, the entry is not in both for when two value list entries exist. + // need to re-write this as a reduce. + const filteredEvents = filtered.filter((item) => { + const vals = fieldAndSetTuples.map((tuple) => { + const eventItem = get(tuple.field, item._source); + if (tuple.operator === 'included') { + // only create a signal if the event is not in the value list + if (eventItem != null) { + return !tuple.matchedSet.has(eventItem); } - return false; - }); - const diff = eventSearchResult.hits.hits.length - filteredEvents.length; - logger.debug(buildRuleMessage(`Lists filtered out ${diff} events`)); - return filteredEvents; + return true; + } else if (tuple.operator === 'excluded') { + // only create a signal if the event is in the value list + if (eventItem != null) { + return tuple.matchedSet.has(eventItem); + } + return true; + } + return false; }); - - return (await Promise.all(filteredHitsEntries)).flat(); - } + return vals.some((value) => value); + }); + const diff = eventSearchResult.hits.hits.length - filteredEvents.length; + logger.debug( + buildRuleMessage(`Exception with id ${exceptionItem.id} filtered out ${diff} events`) + ); + const toReturn = filteredEvents; + return toReturn; + }, + Promise.resolve(eventSearchResult.hits.hits) ); - const filteredHits = await Promise.all(filteredHitsPromises); const toReturn: SignalSearchResponse = { took: eventSearchResult.took, timed_out: eventSearchResult.timed_out, _shards: eventSearchResult._shards, hits: { - total: filteredHits.length, + total: res.length, max_score: eventSearchResult.hits.max_score, - hits: filteredHits.flat(), + hits: res, }, }; - return toReturn; } catch (exc) { throw new Error(`Failed to query lists index. Reason: ${exc.message}`); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.test.ts index a5740d7719f47..56768ec78745d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.test.ts @@ -209,49 +209,52 @@ describe('get_filter', () => { minimum_should_match: 1, }, }, + ], + must_not: [ { bool: { - must_not: { - bool: { - filter: [ - { - nested: { - path: 'some.parentField', - query: { - bool: { - should: [ - { - match_phrase: { - 'some.parentField.nested.field': 'some value', + should: [ + { + bool: { + filter: [ + { + nested: { + path: 'some.parentField', + query: { + bool: { + should: [ + { + match_phrase: { + 'some.parentField.nested.field': 'some value', + }, }, - }, - ], - minimum_should_match: 1, + ], + minimum_should_match: 1, + }, }, + score_mode: 'none', }, - score_mode: 'none', }, - }, - { - bool: { - should: [ - { - match_phrase: { - 'some.not.nested.field': 'some value', + { + bool: { + should: [ + { + match_phrase: { + 'some.not.nested.field': 'some value', + }, }, - }, - ], - minimum_should_match: 1, + ], + minimum_should_match: 1, + }, }, - }, - ], + ], + }, }, - }, + ], }, }, ], should: [], - must_not: [], }, }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.ts index 356cf95fc0d24..888642f77af60 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.ts @@ -10,7 +10,6 @@ import { RiskScoreMappingOrUndefined, } from '../../../../../common/detection_engine/schemas/common/schemas'; import { SignalSourceHit } from '../types'; -import { RiskScore as RiskScoreIOTS } from '../../../../../common/detection_engine/schemas/types'; interface BuildRiskScoreFromMappingProps { doc: SignalSourceHit; @@ -33,8 +32,12 @@ export const buildRiskScoreFromMapping = ({ const mappedField = riskScoreMapping[0].field; // TODO: Expand by verifying fieldType from index via doc._index const mappedValue = get(mappedField, doc._source); - // TODO: This doesn't seem to validate...identified riskScore > 100 😬 - if (RiskScoreIOTS.is(mappedValue)) { + if ( + typeof mappedValue === 'number' && + Number.isSafeInteger(mappedValue) && + mappedValue >= 0 && + mappedValue <= 100 + ) { return { riskScore: mappedValue, riskScoreMeta: { riskScoreOverridden: true } }; } } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.test.ts index 3312191c3b41b..58dcd7f6bd1c1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.test.ts @@ -475,7 +475,7 @@ describe('searchAfterAndBulkCreate', () => { expect(lastLookBackDate).toEqual(new Date('2020-04-20T21:27:45+0000')); // I don't like testing log statements since logs change but this is the best // way I can think of to ensure this section is getting hit with this test case. - expect(((mockLogger.debug as unknown) as jest.Mock).mock.calls[7][0]).toContain( + expect(((mockLogger.debug as unknown) as jest.Mock).mock.calls[8][0]).toContain( 'sortIds was empty on searchResult' ); }); @@ -558,7 +558,7 @@ describe('searchAfterAndBulkCreate', () => { expect(lastLookBackDate).toEqual(new Date('2020-04-20T21:27:45+0000')); // I don't like testing log statements since logs change but this is the best // way I can think of to ensure this section is getting hit with this test case. - expect(((mockLogger.debug as unknown) as jest.Mock).mock.calls[12][0]).toContain( + expect(((mockLogger.debug as unknown) as jest.Mock).mock.calls[15][0]).toContain( 'sortIds was empty on filteredEvents' ); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_bulk_create.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_bulk_create.ts index 3d4e7384714eb..74709f31563ee 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_bulk_create.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_bulk_create.ts @@ -83,6 +83,7 @@ export const singleBulkCreate = async ({ throttle, }: SingleBulkCreateParams): Promise => { filteredEvents.hits.hits = filterDuplicateRules(id, filteredEvents); + logger.debug(`about to bulk create ${filteredEvents.hits.hits.length} events`); if (filteredEvents.hits.hits.length === 0) { logger.debug(`all events were duplicates`); return { success: true, createdItemsCount: 0 }; @@ -135,6 +136,8 @@ export const singleBulkCreate = async ({ logger.debug(`took property says bulk took: ${response.took} milliseconds`); if (response.errors) { + const duplicateSignalsCount = countBy(response.items, 'create.status')['409']; + logger.debug(`ignored ${duplicateSignalsCount} duplicate signals`); const errorCountByMessage = errorAggregator(response, [409]); if (!isEmpty(errorCountByMessage)) { logger.error( @@ -144,6 +147,6 @@ export const singleBulkCreate = async ({ } const createdItemsCount = countBy(response.items, 'create.status')['201'] ?? 0; - + logger.debug(`bulk created ${createdItemsCount} signals`); return { success: true, bulkCreateDuration: makeFloatString(end - start), createdItemsCount }; }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts index a610970907bf8..3c41f29625a51 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts @@ -716,26 +716,31 @@ describe('utils', () => { describe('#getExceptions', () => { test('it successfully returns array of exception list items', async () => { + listMock.getExceptionListClient = () => + (({ + findExceptionListsItem: jest.fn().mockResolvedValue({ + data: [getExceptionListItemSchemaMock()], + page: 1, + per_page: 10000, + total: 1, + }), + } as unknown) as ExceptionListClient); const client = listMock.getExceptionListClient(); const exceptions = await getExceptions({ client, lists: getListArrayMock(), }); - expect(client.getExceptionList).toHaveBeenNthCalledWith(1, { - id: 'some_uuid', - listId: undefined, - namespaceType: 'single', - }); - expect(client.getExceptionList).toHaveBeenNthCalledWith(2, { - id: 'some_uuid', - listId: undefined, - namespaceType: 'agnostic', + expect(client.findExceptionListsItem).toHaveBeenCalledWith({ + listId: ['list_id_single', 'endpoint_list'], + namespaceType: ['single', 'agnostic'], + page: 1, + perPage: 10000, + filter: [], + sortOrder: undefined, + sortField: undefined, }); - expect(exceptions).toEqual([ - getExceptionListItemSchemaMock(), - getExceptionListItemSchemaMock(), - ]); + expect(exceptions).toEqual([getExceptionListItemSchemaMock()]); }); test('it throws if "client" is undefined', async () => { @@ -747,7 +752,7 @@ describe('utils', () => { ).rejects.toThrowError('lists plugin unavailable during rule execution'); }); - test('it returns empty array if no "lists" is undefined', async () => { + test('it returns empty array if "lists" is undefined', async () => { const exceptions = await getExceptions({ client: listMock.getExceptionListClient(), lists: undefined, @@ -771,11 +776,11 @@ describe('utils', () => { ).rejects.toThrowError('unable to fetch exception list items'); }); - test('it throws if "findExceptionListItem" fails', async () => { + test('it throws if "findExceptionListsItem" fails', async () => { const err = new Error('error fetching list'); listMock.getExceptionListClient = () => (({ - findExceptionListItem: jest.fn().mockRejectedValue(err), + findExceptionListsItem: jest.fn().mockRejectedValue(err), } as unknown) as ExceptionListClient); await expect(() => @@ -786,24 +791,10 @@ describe('utils', () => { ).rejects.toThrowError('unable to fetch exception list items'); }); - test('it returns empty array if "getExceptionList" returns null', async () => { - listMock.getExceptionListClient = () => - (({ - getExceptionList: jest.fn().mockResolvedValue(null), - } as unknown) as ExceptionListClient); - - const exceptions = await getExceptions({ - client: listMock.getExceptionListClient(), - lists: undefined, - }); - - expect(exceptions).toEqual([]); - }); - - test('it returns empty array if "findExceptionListItem" returns null', async () => { + test('it returns empty array if "findExceptionListsItem" returns null', async () => { listMock.getExceptionListClient = () => (({ - findExceptionListItem: jest.fn().mockResolvedValue(null), + findExceptionListsItem: jest.fn().mockResolvedValue(null), } as unknown) as ExceptionListClient); const exceptions = await getExceptions({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts index 1c59a4b7ea5d0..9519720d0bbec 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts @@ -15,6 +15,7 @@ import { ListArrayOrUndefined } from '../../../../common/detection_engine/schema import { BulkResponse, BulkResponseErrorAggregation, isValidUnit } from './types'; import { BuildRuleMessage } from './rule_messages'; import { hasLargeValueList } from '../../../../common/detection_engine/utils'; +import { MAX_EXCEPTION_LIST_SIZE } from '../../../../../lists/common/constants'; interface SortExceptionsReturn { exceptionsWithValueLists: ExceptionListItemSchema[]; @@ -160,43 +161,20 @@ export const getExceptions = async ({ throw new Error('lists plugin unavailable during rule execution'); } - if (lists != null) { + if (lists != null && lists.length > 0) { try { - // Gather all exception items of all exception lists linked to rule - const exceptions = await Promise.all( - lists - .map(async (list) => { - const { id, namespace_type: namespaceType } = list; - try { - // TODO update once exceptions client `findExceptionListItem` - // accepts an array of list ids - const foundList = await client.getExceptionList({ - id, - namespaceType, - listId: undefined, - }); - - if (foundList == null) { - return []; - } else { - const items = await client.findExceptionListItem({ - listId: foundList.list_id, - namespaceType, - page: 1, - perPage: 5000, - filter: undefined, - sortOrder: undefined, - sortField: undefined, - }); - return items != null ? items.data : []; - } - } catch { - throw new Error('unable to fetch exception list items'); - } - }) - .flat() - ); - return exceptions.flat(); + const listIds = lists.map(({ list_id: listId }) => listId); + const namespaceTypes = lists.map(({ namespace_type: namespaceType }) => namespaceType); + const items = await client.findExceptionListsItem({ + listId: listIds, + namespaceType: namespaceTypes, + page: 1, + perPage: MAX_EXCEPTION_LIST_SIZE, + filter: [], + sortOrder: undefined, + sortField: undefined, + }); + return items != null ? items.data : []; } catch { throw new Error('unable to fetch exception list items'); } diff --git a/x-pack/plugins/security_solution/server/lib/overview/query.dsl.ts b/x-pack/plugins/security_solution/server/lib/overview/query.dsl.ts index 8ac8233a86b82..b6b1cfea394fd 100644 --- a/x-pack/plugins/security_solution/server/lib/overview/query.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/overview/query.dsl.ts @@ -142,57 +142,167 @@ export const buildOverviewHostQuery = ({ }, endgame_module: { filter: { - term: { - 'event.module': 'endgame', + bool: { + should: [ + { + term: { 'event.module': 'endpoint' }, + }, + { + term: { + 'event.module': 'endgame', + }, + }, + ], }, }, aggs: { dns_event_count: { filter: { - term: { - 'endgame.event_type_full': 'dns_event', + bool: { + should: [ + { + bool: { + filter: [ + { term: { 'network.protocol': 'dns' } }, + { term: { 'event.category': 'network' } }, + ], + }, + }, + { + term: { + 'endgame.event_type_full': 'dns_event', + }, + }, + ], }, }, }, file_event_count: { filter: { - term: { - 'endgame.event_type_full': 'file_event', + bool: { + should: [ + { + term: { + 'event.category': 'file', + }, + }, + { + term: { + 'endgame.event_type_full': 'file_event', + }, + }, + ], }, }, }, image_load_event_count: { filter: { - term: { - 'endgame.event_type_full': 'image_load_event', + bool: { + should: [ + { + bool: { + should: [ + { + term: { + 'event.category': 'library', + }, + }, + { + term: { + 'event.category': 'driver', + }, + }, + ], + }, + }, + { + term: { + 'endgame.event_type_full': 'image_load_event', + }, + }, + ], }, }, }, network_event_count: { filter: { - term: { - 'endgame.event_type_full': 'network_event', + bool: { + should: [ + { + bool: { + filter: [ + { + bool: { + must_not: { + term: { 'network.protocol': 'dns' }, + }, + }, + }, + { + term: { 'event.category': 'network' }, + }, + ], + }, + }, + { + term: { + 'endgame.event_type_full': 'network_event', + }, + }, + ], }, }, }, process_event_count: { filter: { - term: { - 'endgame.event_type_full': 'process_event', + bool: { + should: [ + { + term: { 'event.category': 'process' }, + }, + { + term: { + 'endgame.event_type_full': 'process_event', + }, + }, + ], }, }, }, registry_event: { filter: { - term: { - 'endgame.event_type_full': 'registry_event', + bool: { + should: [ + { + term: { 'event.category': 'registry' }, + }, + { + term: { + 'endgame.event_type_full': 'registry_event', + }, + }, + ], }, }, }, security_event_count: { filter: { - term: { - 'endgame.event_type_full': 'security_event', + bool: { + should: [ + { + bool: { + filter: [ + { term: { 'event.category': 'session' } }, + { term: { 'event.category': 'authentication' } }, + ], + }, + }, + { + term: { + 'endgame.event_type_full': 'security_event', + }, + }, + ], }, }, }, diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/import_timelines_route.test.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/import_timelines_route.test.ts index fe5993cb0161d..b817896e901c1 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/import_timelines_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/import_timelines_route.test.ts @@ -598,6 +598,28 @@ describe('import timeline templates', () => { mockNewTemplateTimelineId ); }); + + test('should return 200 if create via import without a templateTimelineId or templateTimelineVersion', async () => { + mockGetTupleDuplicateErrorsAndUniqueTimeline.mockReturnValue([ + mockDuplicateIdErrors, + [ + { + ...mockUniqueParsedTemplateTimelineObjects[0], + templateTimelineId: null, + templateTimelineVersion: null, + }, + ], + ]); + const mockRequest = getImportTimelinesRequest(); + const result = await server.inject(mockRequest, context); + expect(result.body).toEqual({ + errors: [], + success: true, + success_count: 1, + timelines_installed: 1, + timelines_updated: 0, + }); + }); }); describe('Import a timeline template already exist', () => { diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/compare_timelines_status.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/compare_timelines_status.ts index d61d217a4cf49..f9515741d1250 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/compare_timelines_status.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/compare_timelines_status.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { isEmpty } from 'lodash/fp'; +import { isEmpty, isInteger } from 'lodash/fp'; import { TimelineTypeLiteralWithNull, TimelineType, @@ -71,13 +71,28 @@ export class CompareTimelinesStatus { } public get isCreatable() { + const noExistingTimeline = this.timelineObject.isCreatable && !this.isHandlingTemplateTimeline; + + const templateCreatable = + this.isHandlingTemplateTimeline && this.templateTimelineObject.isCreatable; + + const noExistingTimelineOrTemplate = templateCreatable && this.timelineObject.isCreatable; + + // From Line 87-91 is the condition for creating a template via import without given a templateTimelineId or templateTimelineVersion, + // but keep the existing savedObjectId and version there. + // Therefore even the timeline exists, we still allow it to create a new timeline template by assigning a templateTimelineId and templateTimelineVersion. + // https://github.com/elastic/kibana/pull/67496#discussion_r454337222 + // Line 90-91 means that we want to make sure the existing timeline retrieved by savedObjectId is atemplate. + // If it is not a template, we show an error this timeline is already exist instead. + const retriveTemplateViaSavedObjectId = + templateCreatable && + !this.timelineObject.isCreatable && + this.timelineObject.getData?.timelineType === this.timelineType; + return ( this.isTitleValid && !this.isSavedObjectVersionConflict && - ((this.timelineObject.isCreatable && !this.isHandlingTemplateTimeline) || - (this.templateTimelineObject.isCreatable && - this.timelineObject.isCreatable && - this.isHandlingTemplateTimeline)) + (noExistingTimeline || noExistingTimelineOrTemplate || retriveTemplateViaSavedObjectId) ); } @@ -195,24 +210,27 @@ export class CompareTimelinesStatus { } private get isTemplateVersionConflict() { - const version = this.templateTimelineObject?.getVersion; + const templateTimelineVersion = this.templateTimelineObject?.getVersion; const existingTemplateTimelineVersion = this.templateTimelineObject?.data ?.templateTimelineVersion; if ( - version != null && + templateTimelineVersion != null && this.templateTimelineObject.isExists && existingTemplateTimelineVersion != null ) { - return version <= existingTemplateTimelineVersion; - } else if (this.templateTimelineObject.isExists && version == null) { + return templateTimelineVersion <= existingTemplateTimelineVersion; + } else if (this.templateTimelineObject.isExists && templateTimelineVersion == null) { return true; } return false; } private get isTemplateVersionValid() { - const version = this.templateTimelineObject?.getVersion; - return typeof version === 'number' && !this.isTemplateVersionConflict; + const templateTimelineVersion = this.templateTimelineObject?.getVersion; + return ( + templateTimelineVersion == null || + (isInteger(templateTimelineVersion) && !this.isTemplateVersionConflict) + ); } private get isUpdatedTimelineStatusValid() { diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/failure_cases.test.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/failure_cases.test.ts new file mode 100644 index 0000000000000..3c3ad1cf2d7f8 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/failure_cases.test.ts @@ -0,0 +1,542 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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 { + commonFailureChecker, + checkIsCreateFailureCases, + checkIsUpdateFailureCases, + checkIsCreateViaImportFailureCases, + EMPTY_TITLE_ERROR_MESSAGE, + UPDATE_STATUS_ERROR_MESSAGE, + CREATE_TIMELINE_ERROR_MESSAGE, + CREATE_TEMPLATE_TIMELINE_ERROR_MESSAGE, + CREATE_TEMPLATE_TIMELINE_WITHOUT_VERSION_ERROR_MESSAGE, + NO_MATCH_ID_ERROR_MESSAGE, + NO_MATCH_VERSION_ERROR_MESSAGE, + NOT_ALLOW_UPDATE_TIMELINE_TYPE_ERROR_MESSAGE, + UPDATE_TEMPLATE_TIMELINE_ERROR_MESSAGE, + CREATE_WITH_INVALID_STATUS_ERROR_MESSAGE, + getImportExistingTimelineError, + checkIsUpdateViaImportFailureCases, + NOT_ALLOW_UPDATE_STATUS_ERROR_MESSAGE, + TEMPLATE_TIMELINE_VERSION_CONFLICT_MESSAGE, +} from './failure_cases'; +import { + TimelineStatus, + TimelineType, + TimelineSavedObject, +} from '../../../../../common/types/timeline'; +import { mockGetTimelineValue, mockGetTemplateTimelineValue } from '../__mocks__/import_timelines'; + +describe('failure cases', () => { + describe('commonFailureChecker', () => { + test('If timeline type is draft, it should not return error if title is not given', () => { + const result = commonFailureChecker(TimelineStatus.draft, null); + + expect(result).toBeNull(); + }); + + test('If timeline type is active, it should return error if title is not given', () => { + const result = commonFailureChecker(TimelineStatus.active, null); + + expect(result).toEqual({ + body: EMPTY_TITLE_ERROR_MESSAGE, + statusCode: 405, + }); + }); + + test('If timeline type is immutable, it should return error if title is not given', () => { + const result = commonFailureChecker(TimelineStatus.immutable, null); + + expect(result).toEqual({ + body: EMPTY_TITLE_ERROR_MESSAGE, + statusCode: 405, + }); + }); + + test('If timeline type is not a draft, it should return no error if title is given', () => { + const result = commonFailureChecker(TimelineStatus.active, 'title'); + + expect(result).toBeNull(); + }); + }); + + describe('checkIsCreateFailureCases', () => { + test('Should return error if trying to create a timeline that is already exist', () => { + const isHandlingTemplateTimeline = false; + const version = null; + const templateTimelineVersion = null; + const templateTimelineId = null; + const existTimeline = mockGetTimelineValue as TimelineSavedObject; + const existTemplateTimeline = null; + const result = checkIsCreateFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.default, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: CREATE_TIMELINE_ERROR_MESSAGE, + statusCode: 405, + }); + }); + + test('Should return error if trying to create a timeline template that is already exist', () => { + const isHandlingTemplateTimeline = true; + const version = null; + const templateTimelineVersion = 1; + const templateTimelineId = 'template-timeline-id-one'; + const existTimeline = null; + const existTemplateTimeline = mockGetTemplateTimelineValue as TimelineSavedObject; + const result = checkIsCreateFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.template, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: CREATE_TEMPLATE_TIMELINE_ERROR_MESSAGE, + statusCode: 405, + }); + }); + + test('Should return error if trying to create a timeline template without providing templateTimelineVersion', () => { + const isHandlingTemplateTimeline = true; + const version = null; + const templateTimelineVersion = null; + const templateTimelineId = 'template-timeline-id-one'; + const existTimeline = null; + const existTemplateTimeline = null; + const result = checkIsCreateFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.template, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: CREATE_TEMPLATE_TIMELINE_WITHOUT_VERSION_ERROR_MESSAGE, + statusCode: 403, + }); + }); + }); + + describe('checkIsUpdateFailureCases', () => { + test('Should return error if trying to update status field of an existing immutable timeline', () => { + const isHandlingTemplateTimeline = false; + const version = mockGetTimelineValue.version; + const templateTimelineVersion = null; + const templateTimelineId = null; + const existTimeline = { + ...(mockGetTimelineValue as TimelineSavedObject), + status: TimelineStatus.immutable, + }; + const existTemplateTimeline = null; + const result = checkIsUpdateFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.default, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: UPDATE_STATUS_ERROR_MESSAGE, + statusCode: 403, + }); + }); + + test('Should return error if trying to update status field of an existing immutable timeline template', () => { + const isHandlingTemplateTimeline = true; + const version = mockGetTemplateTimelineValue.version; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = null; + const existTemplateTimeline = { + ...(mockGetTemplateTimelineValue as TimelineSavedObject), + status: TimelineStatus.immutable, + }; + const result = checkIsUpdateFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.template, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: UPDATE_STATUS_ERROR_MESSAGE, + statusCode: 403, + }); + }); + + test('should return error if trying to update timelineType field of an existing timeline template', () => { + const isHandlingTemplateTimeline = true; + const version = mockGetTemplateTimelineValue.version; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = null; + const existTemplateTimeline = mockGetTemplateTimelineValue as TimelineSavedObject; + const result = checkIsUpdateFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.default, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: NOT_ALLOW_UPDATE_TIMELINE_TYPE_ERROR_MESSAGE, + statusCode: 403, + }); + }); + + test('should return error if trying to update a timeline template that does not exist', () => { + const isHandlingTemplateTimeline = true; + const version = mockGetTemplateTimelineValue.version; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = null; + const existTemplateTimeline = null; + const result = checkIsUpdateFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.default, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: UPDATE_TEMPLATE_TIMELINE_ERROR_MESSAGE, + statusCode: 405, + }); + }); + + test('should return error if there is no matched timeline found by given templateTimelineId', () => { + const isHandlingTemplateTimeline = true; + const version = mockGetTemplateTimelineValue.version; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = { + ...(mockGetTemplateTimelineValue as TimelineSavedObject), + savedObjectId: 'someOtherId', + }; + const existTemplateTimeline = mockGetTemplateTimelineValue as TimelineSavedObject; + const result = checkIsUpdateFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.template, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: NO_MATCH_ID_ERROR_MESSAGE, + statusCode: 409, + }); + }); + + test('should return error if given version field is defferent from existing version of timelin template', () => { + const isHandlingTemplateTimeline = true; + const version = 'xxx'; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = null; + const existTemplateTimeline = mockGetTemplateTimelineValue as TimelineSavedObject; + const result = checkIsUpdateFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.template, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: NO_MATCH_VERSION_ERROR_MESSAGE, + statusCode: 409, + }); + }); + }); + + describe('checkIsCreateViaImportFailureCases', () => { + test('should return error if trying to create a draft timeline', () => { + const isHandlingTemplateTimeline = true; + const version = mockGetTemplateTimelineValue.version; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = null; + const existTemplateTimeline = mockGetTemplateTimelineValue as TimelineSavedObject; + const result = checkIsCreateViaImportFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.draft, + TimelineType.template, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: CREATE_WITH_INVALID_STATUS_ERROR_MESSAGE, + statusCode: 405, + }); + }); + + test('should return error if trying to create a timeline template which is already exist', () => { + const isHandlingTemplateTimeline = true; + const version = mockGetTemplateTimelineValue.version; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = null; + const existTemplateTimeline = mockGetTemplateTimelineValue as TimelineSavedObject; + const result = checkIsCreateViaImportFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.template, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: getImportExistingTimelineError(mockGetTimelineValue.savedObjectId), + statusCode: 405, + }); + }); + + test('should return error if importe a timeline which is already exists', () => { + const isHandlingTemplateTimeline = false; + const version = mockGetTimelineValue.version; + const templateTimelineVersion = null; + const templateTimelineId = null; + const existTimeline = mockGetTimelineValue as TimelineSavedObject; + const existTemplateTimeline = null; + const result = checkIsCreateViaImportFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.default, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: getImportExistingTimelineError(mockGetTimelineValue.savedObjectId), + statusCode: 405, + }); + }); + }); + + describe('checkIsUpdateViaImportFailureCases', () => { + test('should return error if trying to update a timeline which does not exist', () => { + const isHandlingTemplateTimeline = false; + const version = mockGetTimelineValue.version; + const templateTimelineVersion = null; + const templateTimelineId = null; + const existTimeline = mockGetTimelineValue as TimelineSavedObject; + const existTemplateTimeline = null; + const result = checkIsUpdateViaImportFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.default, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: getImportExistingTimelineError(mockGetTimelineValue.savedObjectId), + statusCode: 405, + }); + }); + + test('should return error if trying to update timelineType field of an existing timeline template', () => { + const isHandlingTemplateTimeline = true; + const version = mockGetTemplateTimelineValue.version; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = null; + const existTemplateTimeline = mockGetTemplateTimelineValue as TimelineSavedObject; + const result = checkIsUpdateViaImportFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.default, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: NOT_ALLOW_UPDATE_TIMELINE_TYPE_ERROR_MESSAGE, + statusCode: 403, + }); + }); + + test('should return error if trying to update status field of an existing timeline template', () => { + const isHandlingTemplateTimeline = true; + const version = mockGetTemplateTimelineValue.version; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = null; + const existTemplateTimeline = mockGetTemplateTimelineValue as TimelineSavedObject; + const result = checkIsUpdateViaImportFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.immutable, + TimelineType.template, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: NOT_ALLOW_UPDATE_STATUS_ERROR_MESSAGE, + statusCode: 405, + }); + }); + + test('should return error if trying to update a timeline template that does not exist', () => { + const isHandlingTemplateTimeline = true; + const version = mockGetTemplateTimelineValue.version; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = null; + const existTemplateTimeline = null; + const result = checkIsUpdateViaImportFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.default, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: UPDATE_TEMPLATE_TIMELINE_ERROR_MESSAGE, + statusCode: 405, + }); + }); + + test('should return error if there is no matched timeline found by given templateTimelineId', () => { + const isHandlingTemplateTimeline = true; + const version = mockGetTemplateTimelineValue.version; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = { + ...(mockGetTemplateTimelineValue as TimelineSavedObject), + savedObjectId: 'someOtherId', + }; + const existTemplateTimeline = mockGetTemplateTimelineValue as TimelineSavedObject; + const result = checkIsUpdateViaImportFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.template, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: NO_MATCH_ID_ERROR_MESSAGE, + statusCode: 409, + }); + }); + + test('should return error if given version field is defferent from existing version of timelin template', () => { + const isHandlingTemplateTimeline = true; + const version = 'xxx'; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = null; + const existTemplateTimeline = mockGetTemplateTimelineValue as TimelineSavedObject; + const result = checkIsUpdateViaImportFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.template, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: NO_MATCH_VERSION_ERROR_MESSAGE, + statusCode: 409, + }); + }); + + test('should return error if given templateTimelineVersion field is less or equal to existing templateTimelineVersion of timelin template', () => { + const isHandlingTemplateTimeline = true; + const version = mockGetTemplateTimelineValue.version; + const templateTimelineVersion = mockGetTemplateTimelineValue.templateTimelineVersion; + const templateTimelineId = mockGetTemplateTimelineValue.templateTimelineId; + const existTimeline = null; + const existTemplateTimeline = mockGetTemplateTimelineValue as TimelineSavedObject; + const result = checkIsUpdateViaImportFailureCases( + isHandlingTemplateTimeline, + TimelineStatus.active, + TimelineType.template, + version, + templateTimelineVersion, + templateTimelineId, + existTimeline, + existTemplateTimeline + ); + + expect(result).toEqual({ + body: TEMPLATE_TIMELINE_VERSION_CONFLICT_MESSAGE, + statusCode: 409, + }); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/failure_cases.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/failure_cases.ts index d41e8fc190983..b926819d66c92 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/failure_cases.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/failure_cases.ts @@ -78,7 +78,10 @@ const commonUpdateTemplateTimelineCheck = ( existTemplateTimeline: TimelineSavedObject | null ) => { if (isHandlingTemplateTimeline) { - if (existTimeline != null && timelineType !== existTimeline.timelineType) { + if ( + (existTimeline != null && timelineType !== existTimeline.timelineType) || + (existTemplateTimeline != null && timelineType !== existTemplateTimeline.timelineType) + ) { return { body: NOT_ALLOW_UPDATE_TIMELINE_TYPE_ERROR_MESSAGE, statusCode: 403, @@ -106,11 +109,7 @@ const commonUpdateTemplateTimelineCheck = ( }; } - if ( - existTemplateTimeline != null && - existTemplateTimeline.templateTimelineVersion == null && - existTemplateTimeline.version !== version - ) { + if (existTemplateTimeline != null && existTemplateTimeline.version !== version) { // throw error 409 conflict timeline return { body: NO_MATCH_VERSION_ERROR_MESSAGE, @@ -231,12 +230,6 @@ export const checkIsUpdateViaImportFailureCases = ( }; } } else { - if (existTemplateTimeline != null && timelineType !== existTemplateTimeline?.timelineType) { - return { - body: NOT_ALLOW_UPDATE_TIMELINE_TYPE_ERROR_MESSAGE, - statusCode: 403, - }; - } const isStatusValid = ((existTemplateTimeline?.status == null || existTemplateTimeline?.status === TimelineStatus.active) && diff --git a/x-pack/plugins/security_solution/server/plugin.ts b/x-pack/plugins/security_solution/server/plugin.ts index 611f35c6d402a..f2fad16d80414 100644 --- a/x-pack/plugins/security_solution/server/plugin.ts +++ b/x-pack/plugins/security_solution/server/plugin.ts @@ -40,7 +40,14 @@ import { initSavedObjects, savedObjectTypes } from './saved_objects'; import { AppClientFactory } from './client'; import { createConfig$, ConfigType } from './config'; import { initUiSettings } from './ui_settings'; -import { APP_ID, APP_ICON, SERVER_APP_ID, SecurityPageName } from '../common/constants'; +import { + APP_ID, + APP_ICON, + SERVER_APP_ID, + SecurityPageName, + SIGNALS_ID, + NOTIFICATIONS_ID, +} from '../common/constants'; import { registerEndpointRoutes } from './endpoint/routes/metadata'; import { registerLimitedConcurrencyRoutes } from './endpoint/routes/limited_concurrency'; import { registerResolverRoutes } from './endpoint/routes/resolver'; @@ -167,23 +174,18 @@ export class Plugin implements IPlugin module.jobs); - const jobs = await ml.jobServiceProvider(internalMlClient, fakeRequest).jobsSummary(['siem']); + const jobs = await ml + .jobServiceProvider(internalMlClient, fakeRequest) + .jobsSummary(['siem', 'security']); jobsUsage = jobs.reduce((usage, job) => { const isElastic = moduleJobs.some((moduleJob) => moduleJob.id === job.id); diff --git a/x-pack/plugins/spaces/server/capabilities/capabilities_switcher.test.ts b/x-pack/plugins/spaces/server/capabilities/capabilities_switcher.test.ts index 797d7fd1bdcc4..c9ea1b44e723d 100644 --- a/x-pack/plugins/spaces/server/capabilities/capabilities_switcher.test.ts +++ b/x-pack/plugins/spaces/server/capabilities/capabilities_switcher.test.ts @@ -23,7 +23,7 @@ const features = ([ id: 'feature_2', name: 'Feature 2', navLinkId: 'feature2', - app: [], + app: ['feature2'], catalogue: ['feature2Entry'], management: { kibana: ['somethingElse'], diff --git a/x-pack/plugins/spaces/server/capabilities/capabilities_switcher.ts b/x-pack/plugins/spaces/server/capabilities/capabilities_switcher.ts index 00e2419136f48..e8d964b22010c 100644 --- a/x-pack/plugins/spaces/server/capabilities/capabilities_switcher.ts +++ b/x-pack/plugins/spaces/server/capabilities/capabilities_switcher.ts @@ -83,8 +83,7 @@ function toggleDisabledFeatures( for (const feature of disabledFeatures) { // Disable associated navLink, if one exists - const featureNavLinks = feature.navLinkId ? [feature.navLinkId, ...feature.app] : feature.app; - featureNavLinks.forEach((app) => { + feature.app.forEach((app) => { if (navLinks.hasOwnProperty(app) && !enabledAppEntries.has(app)) { navLinks[app] = false; } diff --git a/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.test.ts b/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.test.ts index 1994e5f749371..f32a755515a95 100644 --- a/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.test.ts +++ b/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.test.ts @@ -33,7 +33,7 @@ function errorAttempts(task: TaskInstance): Err { +describe('Bulk Operation Buffer', () => { describe('createBuffer()', () => { test('batches up multiple Operation calls', async () => { const bulkUpdate: jest.Mocked> = jest.fn( @@ -54,19 +54,18 @@ describe.skip('Bulk Operation Buffer', () => { expect(bulkUpdate).toHaveBeenCalledWith([task1, task2]); }); - test('batch updates are executed at most by the next Event Loop tick by default', async () => { + test('batch updates can be customised to execute after a certain period', async () => { const bulkUpdate: jest.Mocked> = jest.fn((tasks) => { return Promise.resolve(tasks.map(incrementAttempts)); }); - const bufferedUpdate = createBuffer(bulkUpdate); + const bufferMaxDuration = 50; + const bufferedUpdate = createBuffer(bulkUpdate, { bufferMaxDuration }); const task1 = createTask(); const task2 = createTask(); const task3 = createTask(); const task4 = createTask(); - const task5 = createTask(); - const task6 = createTask(); return new Promise((resolve) => { Promise.all([bufferedUpdate(task1), bufferedUpdate(task2)]).then((_) => { @@ -77,65 +76,18 @@ describe.skip('Bulk Operation Buffer', () => { setTimeout(() => { // on next tick - setTimeout(() => { - // on next tick - expect(bulkUpdate).toHaveBeenCalledTimes(2); - Promise.all([bufferedUpdate(task5), bufferedUpdate(task6)]).then((_) => { - expect(bulkUpdate).toHaveBeenCalledTimes(3); - expect(bulkUpdate).toHaveBeenCalledWith([task5, task6]); - resolve(); - }); - }, 0); - expect(bulkUpdate).toHaveBeenCalledTimes(1); Promise.all([bufferedUpdate(task3), bufferedUpdate(task4)]).then((_) => { expect(bulkUpdate).toHaveBeenCalledTimes(2); expect(bulkUpdate).toHaveBeenCalledWith([task3, task4]); }); - }, 0); - }); - }); - - test('batch updates can be customised to execute after a certain period', async () => { - const bulkUpdate: jest.Mocked> = jest.fn((tasks) => { - return Promise.resolve(tasks.map(incrementAttempts)); - }); - - const bufferMaxDuration = 50; - const bufferedUpdate = createBuffer(bulkUpdate, { bufferMaxDuration }); - - const task1 = createTask(); - const task2 = createTask(); - const task3 = createTask(); - const task4 = createTask(); - const task5 = createTask(); - const task6 = createTask(); - - return new Promise((resolve) => { - Promise.all([bufferedUpdate(task1), bufferedUpdate(task2)]).then((_) => { - expect(bulkUpdate).toHaveBeenCalledTimes(1); - expect(bulkUpdate).toHaveBeenCalledWith([task1, task2]); - expect(bulkUpdate).not.toHaveBeenCalledWith([task3, task4]); - }); - setTimeout(() => { - // on next tick setTimeout(() => { // on next tick expect(bulkUpdate).toHaveBeenCalledTimes(2); - Promise.all([bufferedUpdate(task5), bufferedUpdate(task6)]).then((_) => { - expect(bulkUpdate).toHaveBeenCalledTimes(3); - expect(bulkUpdate).toHaveBeenCalledWith([task5, task6]); - resolve(); - }); - }, bufferMaxDuration + 1); - - expect(bulkUpdate).toHaveBeenCalledTimes(1); - Promise.all([bufferedUpdate(task3), bufferedUpdate(task4)]).then((_) => { - expect(bulkUpdate).toHaveBeenCalledTimes(2); - expect(bulkUpdate).toHaveBeenCalledWith([task3, task4]); - }); - }, bufferMaxDuration + 1); + resolve(); + }, bufferMaxDuration * 1.1); + }, bufferMaxDuration * 1.1); }); }); @@ -144,8 +96,9 @@ describe.skip('Bulk Operation Buffer', () => { return Promise.resolve(tasks.map(incrementAttempts)); }); + const bufferMaxDuration = 1000; const bufferedUpdate = createBuffer(bulkUpdate, { - bufferMaxDuration: 100, + bufferMaxDuration, bufferMaxOperations: 2, }); @@ -155,26 +108,19 @@ describe.skip('Bulk Operation Buffer', () => { const task4 = createTask(); const task5 = createTask(); - return new Promise((resolve) => { - bufferedUpdate(task1); - bufferedUpdate(task2); - bufferedUpdate(task3); - bufferedUpdate(task4); - - setTimeout(() => { - expect(bulkUpdate).toHaveBeenCalledTimes(2); - expect(bulkUpdate).toHaveBeenCalledWith([task1, task2]); - expect(bulkUpdate).toHaveBeenCalledWith([task3, task4]); - - setTimeout(() => { - expect(bulkUpdate).toHaveBeenCalledTimes(2); - bufferedUpdate(task5).then((_) => { - expect(bulkUpdate).toHaveBeenCalledTimes(3); - expect(bulkUpdate).toHaveBeenCalledWith([task5]); - resolve(); - }); - }, 50); - }, 50); + return Promise.all([ + bufferedUpdate(task1), + bufferedUpdate(task2), + bufferedUpdate(task3), + bufferedUpdate(task4), + ]).then(() => { + expect(bulkUpdate).toHaveBeenCalledTimes(2); + expect(bulkUpdate).toHaveBeenCalledWith([task1, task2]); + expect(bulkUpdate).toHaveBeenCalledWith([task3, task4]); + return bufferedUpdate(task5).then((_) => { + expect(bulkUpdate).toHaveBeenCalledTimes(3); + expect(bulkUpdate).toHaveBeenCalledWith([task5]); + }); }); }); @@ -194,29 +140,26 @@ describe.skip('Bulk Operation Buffer', () => { const task3 = createTask(); const task4 = createTask(); - return new Promise((resolve) => { - bufferedUpdate(task1); - bufferedUpdate(task2); - - setTimeout(() => { - expect(bulkUpdate).toHaveBeenCalledTimes(1); - expect(bulkUpdate).toHaveBeenCalledWith([task1, task2]); + return Promise.all([bufferedUpdate(task1), bufferedUpdate(task2)]).then(() => { + expect(bulkUpdate).toHaveBeenCalledTimes(1); + expect(bulkUpdate).toHaveBeenCalledWith([task1, task2]); - bufferedUpdate(task3); - bufferedUpdate(task4); + return new Promise((resolve) => { + const futureUpdates = Promise.all([bufferedUpdate(task3), bufferedUpdate(task4)]); setTimeout(() => { expect(bulkUpdate).toHaveBeenCalledTimes(1); - setTimeout(() => { + futureUpdates.then(() => { expect(bulkUpdate).toHaveBeenCalledTimes(2); expect(bulkUpdate).toHaveBeenCalledWith([task3, task4]); resolve(); - }, bufferMaxDuration / 2); + }); }, bufferMaxDuration / 2); - }, bufferMaxDuration + 1); + }); }); }); + test('handles both resolutions and rejections at individual task level', async (done) => { const bulkUpdate: jest.Mocked> = jest.fn( ([task1, task2, task3]) => { diff --git a/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.ts b/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.ts index fca7ce02e0cd7..c8e5b837fa36c 100644 --- a/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.ts +++ b/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.ts @@ -93,11 +93,8 @@ export function createBuffer { setTimeout(resolve, ms); diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 451557ff93092..a87e92bb33d50 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -360,6 +360,21 @@ "core.fatalErrors.tryRefreshingPageDescription": "ページを更新してみてください。うまくいかない場合は、前のページに戻るか、セッションデータを消去してください。", "core.notifications.errorToast.closeModal": "閉じる", "core.notifications.unableUpdateUISettingNotificationMessageTitle": "UI 設定を更新できません", + "core.statusPage.loadStatus.serverIsDownErrorMessage": "サーバーステータスのリクエストに失敗しました。サーバーがダウンしている可能性があります。", + "core.statusPage.loadStatus.serverStatusCodeErrorMessage": "サーバーステータスのリクエストに失敗しました。ステータスコード: {responseStatus}", + "core.statusPage.metricsTiles.columns.heapTotalHeader": "ヒープ合計", + "core.statusPage.metricsTiles.columns.heapUsedHeader": "使用ヒープ", + "core.statusPage.metricsTiles.columns.loadHeader": "読み込み", + "core.statusPage.metricsTiles.columns.requestsPerSecHeader": "1 秒あたりのリクエスト", + "core.statusPage.metricsTiles.columns.resTimeAvgHeader": "平均応答時間", + "core.statusPage.metricsTiles.columns.resTimeMaxHeader": "最長応答時間", + "core.statusPage.serverStatus.statusTitle": "Kibana のステータス: {kibanaStatus}", + "core.statusPage.statusApp.loadingErrorText": "ステータスの読み込み中にエラーが発生しました", + "core.statusPage.statusApp.statusActions.buildText": "{buildNum} を作成", + "core.statusPage.statusApp.statusActions.commitText": "{buildSha} を確定", + "core.statusPage.statusApp.statusTitle": "プラグインステータス", + "core.statusPage.statusTable.columns.idHeader": "ID", + "core.statusPage.statusTable.columns.statusHeader": "ステータス", "core.toasts.errorToast.seeFullError": "完全なエラーを表示", "core.ui.chrome.headerGlobalNav.goHomePageIconAriaLabel": "ホームページに移動", "core.ui.chrome.headerGlobalNav.helpMenuAskElasticTitle": "Elasticに確認する", @@ -2470,21 +2485,6 @@ "server.status.redTitle": "赤", "server.status.uninitializedTitle": "アンインストールしました", "server.status.yellowTitle": "黄色", - "statusPage.loadStatus.serverIsDownErrorMessage": "サーバーステータスのリクエストに失敗しました。サーバーがダウンしている可能性があります。", - "statusPage.loadStatus.serverStatusCodeErrorMessage": "サーバーステータスのリクエストに失敗しました。ステータスコード: {responseStatus}", - "statusPage.metricsTiles.columns.heapTotalHeader": "ヒープ合計", - "statusPage.metricsTiles.columns.heapUsedHeader": "使用ヒープ", - "statusPage.metricsTiles.columns.loadHeader": "読み込み", - "statusPage.metricsTiles.columns.requestsPerSecHeader": "1 秒あたりのリクエスト", - "statusPage.metricsTiles.columns.resTimeAvgHeader": "平均応答時間", - "statusPage.metricsTiles.columns.resTimeMaxHeader": "最長応答時間", - "statusPage.serverStatus.statusTitle": "Kibana のステータス: {kibanaStatus}", - "statusPage.statusApp.loadingErrorText": "ステータスの読み込み中にエラーが発生しました", - "statusPage.statusApp.statusActions.buildText": "{buildNum} を作成", - "statusPage.statusApp.statusActions.commitText": "{buildSha} を確定", - "statusPage.statusApp.statusTitle": "プラグインステータス", - "statusPage.statusTable.columns.idHeader": "ID", - "statusPage.statusTable.columns.statusHeader": "ステータス", "telemetry.callout.appliesSettingTitle": "この設定に加えた変更は {allOfKibanaText} に適用され、自動的に保存されます。", "telemetry.callout.appliesSettingTitle.allOfKibanaText": "Kibana のすべて", "telemetry.callout.clusterStatisticsDescription": "これは収集される基本的なクラスター統計の例です。インデックス、シャード、ノードの数が含まれます。監視がオンになっているかどうかなどのハイレベルの使用統計も含まれます。", @@ -4257,7 +4257,7 @@ "xpack.apm.metrics.transactionChart.transactionDurationLabel": "トランザクション時間", "xpack.apm.metrics.transactionChart.transactionsPerMinuteLabel": "1 分あたりのトランザクション数", "xpack.apm.notAvailableLabel": "N/A", - "xpack.apm.percentOfParent": "({parentType, select, transaction { 件中 {value} 件のトランザクション} トレース {trace} })", + "xpack.apm.percentOfParent": "({value} {parentType, select, transaction {トランザクション} trace {トレース} })", "xpack.apm.propertiesTable.agentFeature.noDataAvailableLabel": "利用可能なデータがありません", "xpack.apm.propertiesTable.agentFeature.noResultFound": "\"{value}\"に対する結果が見つかりませんでした。", "xpack.apm.propertiesTable.tabs.exceptionStacktraceLabel": "例外のスタックトレース", @@ -7415,10 +7415,6 @@ "xpack.infra.logs.analysis.anomalySectionNoDataTitle": "表示するデータがありません。", "xpack.infra.logs.analysis.jobStoppedCalloutMessage": "ML ジョブが手動またはリソース不足により停止しました。新しいログエントリーはジョブが再起動するまで処理されません。", "xpack.infra.logs.analysis.jobStoppedCalloutTitle": "ML ジョブが停止しました", - "xpack.infra.logs.analysis.missingMlResultsPrivilegesBody": "本機能は機械学習ジョブを利用し、そのステータスと結果にアクセスするためには、少なくとも{machineLearningUserRole}ロールが必要です。", - "xpack.infra.logs.analysis.missingMlResultsPrivilegesTitle": "追加の機械学習の権限が必要です", - "xpack.infra.logs.analysis.missingMlSetupPrivilegesBody": "本機能は機械学習ジョブを利用し、設定には{machineLearningAdminRole}ロールが必要です。", - "xpack.infra.logs.analysis.missingMlSetupPrivilegesTitle": "追加の機械学習の権限が必要です", "xpack.infra.logs.analysis.mlAppButton": "機械学習を開く", "xpack.infra.logs.analysis.mlUnavailableBody": "詳細は{machineLearningAppLink}をご覧ください。", "xpack.infra.logs.analysis.mlUnavailableTitle": "この機能には機械学習が必要です", @@ -7434,7 +7430,7 @@ "xpack.infra.logs.customizeLogs.customizeButtonLabel": "カスタマイズ", "xpack.infra.logs.customizeLogs.lineWrappingFormRowLabel": "改行", "xpack.infra.logs.customizeLogs.textSizeFormRowLabel": "テキストサイズ", - "xpack.infra.logs.customizeLogs.textSizeRadioGroup": "{textScale, select, small {小さい} 中くらい {Medium} 大きい {Large} その他の {{textScale}} }", + "xpack.infra.logs.customizeLogs.textSizeRadioGroup": "{textScale, select, small {小さい} medium {中くらい} large {大きい} other {{textScale}}}", "xpack.infra.logs.customizeLogs.wrapLongLinesSwitchLabel": "長い行を改行", "xpack.infra.logs.emptyView.checkForNewDataButtonLabel": "新規データを確認", "xpack.infra.logs.emptyView.noLogMessageDescription": "フィルターを調整してみてください。", @@ -8112,7 +8108,6 @@ "xpack.ingestManager.createPackageConfig.StepSelectConfig.errorLoadingAgentConfigsTitle": "エージェント構成の読み込みエラー", "xpack.ingestManager.createPackageConfig.StepSelectConfig.errorLoadingPackageTitle": "パッケージ情報の読み込みエラー", "xpack.ingestManager.createPackageConfig.StepSelectConfig.errorLoadingSelectedAgentConfigTitle": "選択したエージェント構成の読み込みエラー", - "xpack.ingestManager.createPackageConfig.StepSelectConfig.filterAgentConfigsInputPlaceholder": "エージェント構成の検索", "xpack.ingestManager.createPackageConfig.stepSelectPackage.errorLoadingConfigTitle": "エージェント構成情報の読み込みエラー", "xpack.ingestManager.createPackageConfig.stepSelectPackage.errorLoadingPackagesTitle": "統合の読み込みエラー", "xpack.ingestManager.createPackageConfig.stepSelectPackage.errorLoadingSelectedPackageTitle": "選択した統合の読み込みエラー", @@ -8182,8 +8177,6 @@ "xpack.ingestManager.editPackageConfig.updatedNotificationTitle": "正常に'{packageConfigName}'を更新しました", "xpack.ingestManager.enrollemntAPIKeyList.emptyMessage": "登録トークンが見つかりません。", "xpack.ingestManager.enrollemntAPIKeyList.loadingTokensMessage": "登録トークンを読み込んでいます...", - "xpack.ingestManager.enrollmentInstructions.copyButton": "コマンドをコピー", - "xpack.ingestManager.enrollmentInstructions.descriptionText": "エージェントのディレクトリから、これらのコマンドを実行して、Elasticエージェントを登録して起動します。{enrollCommand}はエージェントの構成ファイルに書き込み、正しい設定になるようにします。このコマンドを使用すると、複数のホストでエージェントを設定できます。", "xpack.ingestManager.enrollmentStepAgentConfig.configSelectAriaLabel": "エージェント構成", "xpack.ingestManager.enrollmentStepAgentConfig.configSelectLabel": "エージェント構成", "xpack.ingestManager.enrollmentStepAgentConfig.enrollmentTokenSelectLabel": "登録トークン", @@ -8569,15 +8562,15 @@ "xpack.lens.pie.treemaplabel": "ツリーマップ", "xpack.lens.pie.treemapSuggestionLabel": "ツリーマップとして", "xpack.lens.pie.visualizationName": "パイ", - "xpack.lens.pieChart.alwaysShowLegendLabel": "表示", "xpack.lens.pieChart.categoriesInLegendLabel": "ラベルを非表示", - "xpack.lens.pieChart.defaultLegendLabel": "自動", "xpack.lens.pieChart.fitInsideOnlyLabel": "内部のみ", "xpack.lens.pieChart.hiddenNumbersLabel": "グラフから非表示", - "xpack.lens.pieChart.hideLegendLabel": "非表示", "xpack.lens.pieChart.labelPositionLabel": "ラベル位置", "xpack.lens.pieChart.legendDisplayLabel": "凡例表示", "xpack.lens.pieChart.legendDisplayLegend": "凡例表示", + "xpack.lens.pieChart.legendVisibility.auto": "自動", + "xpack.lens.pieChart.legendVisibility.hide": "非表示", + "xpack.lens.pieChart.legendVisibility.show": "表示", "xpack.lens.pieChart.nestedLegendLabel": "ネストされた凡例", "xpack.lens.pieChart.numberLabels": "ラベル値", "xpack.lens.pieChart.percentDecimalsLabel": "割合の小数点桁数", @@ -10243,7 +10236,6 @@ "xpack.ml.newJob.recognize.advancedLabel": "高度な設定", "xpack.ml.newJob.recognize.advancedSettingsAriaLabel": "高度な設定", "xpack.ml.newJob.recognize.alreadyExistsLabel": "(既に存在します)", - "xpack.ml.newJob.recognize.analysisRunningLabel": "分析を実行中", "xpack.ml.newJob.recognize.cancelJobOverrideLabel": "閉じる", "xpack.ml.newJob.recognize.createJobButtonAriaLabel": "ジョブを作成", "xpack.ml.newJob.recognize.createJobButtonLabel": "{numberOfJobs, plural, zero {Job} one {Job} other {Jobs}} を作成", @@ -13580,7 +13572,7 @@ "xpack.securitySolution.detectionEngine.editRule.errorMsgDescription": "申し訳ありません", "xpack.securitySolution.detectionEngine.editRule.pageTitle": "ルール設定の編集", "xpack.securitySolution.detectionEngine.editRule.saveChangeTitle": "変更を保存", - "xpack.securitySolution.detectionEngine.emptyActionPrimary": "セットアップの手順を表示", + "xpack.securitySolution.detectionEngine.emptyActionBeats": "セットアップの手順を表示", "xpack.securitySolution.detectionEngine.emptyActionSecondary": "ドキュメントに移動", "xpack.securitySolution.detectionEngine.emptyTitle": "Securityアプリケーションの検出エンジンに関連したインデックスがないようです", "xpack.securitySolution.detectionEngine.goToDocumentationButton": "ドキュメンテーションを表示", @@ -13873,7 +13865,6 @@ "xpack.securitySolution.detectionEngine.mlUnavailableTitle": "{totalRules} {totalRules, plural, =1 {個のルール} other {個のルール}}で機械学習を有効にする必要があります。", "xpack.securitySolution.detectionEngine.noApiIntegrationKeyCallOutMsg": "Kibanaを起動するごとに保存されたオブジェクトの新しい暗号化キーを作成します。永続キーがないと、Kibanaの再起動後にルールを削除または修正することができません。永続キーを設定するには、kibana.ymlファイルに32文字以上のテキスト値を付けてxpack.encryptedSavedObjects.encryptionKey設定を追加してください。", "xpack.securitySolution.detectionEngine.noApiIntegrationKeyCallOutTitle": "API統合キーが必要です", - "xpack.securitySolution.detectionEngine.noIndexMsgBody": "検出エンジンを使用するには、必要なクラスターとインデックス権限のユーザーが最初にこのページにアクセスする必要があります。ヘルプについては、管理者にお問い合わせください。", "xpack.securitySolution.detectionEngine.noIndexTitle": "検出エンジンを設定しましょう", "xpack.securitySolution.detectionEngine.pageTitle": "検出エンジン", "xpack.securitySolution.detectionEngine.panelSubtitleShowing": "表示中", @@ -14357,7 +14348,7 @@ "xpack.securitySolution.overview.viewEventsButtonLabel": "イベントを表示", "xpack.securitySolution.overview.winlogbeatMWSysmonOperational": "Microsoft-Windows-Sysmon/Operational", "xpack.securitySolution.overview.winlogbeatSecurityTitle": "セキュリティ", - "xpack.securitySolution.pages.common.emptyActionPrimary": "Beatsでデータを表示", + "xpack.securitySolution.pages.common.emptyActionBeats": "Beatsでデータを表示", "xpack.securitySolution.pages.common.emptyActionSecondary": "入門ガイドを表示", "xpack.securitySolution.pages.common.emptyTitle": "SIEMへようこそ。始めましょう。", "xpack.securitySolution.pages.fourohfour.noContentFoundDescription": "コンテンツがありません", @@ -16288,7 +16279,6 @@ "xpack.uptime.ml.enableAnomalyDetectionPanel.manageMLJobDescription.noteText": "注:ジョブが結果の計算を開始するまでに少し時間がかかる場合があります。", "xpack.uptime.ml.enableAnomalyDetectionPanel.startTrial": "無料の 14 日トライアルを開始", "xpack.uptime.ml.enableAnomalyDetectionPanel.startTrialDesc": "期間異常検知機能を利用するには、Elastic Platinum ライセンスが必要です。", - "xpack.uptime.monitorCharts.durationChart.bottomAxis.title": "タイムスタンプ", "xpack.uptime.monitorCharts.durationChart.leftAxis.title": "期間ms", "xpack.uptime.monitorCharts.monitorDuration.titleLabel": "監視期間", "xpack.uptime.monitorCharts.monitorDuration.titleLabelWithAnomaly": "監視期間 (異常: {noOfAnomalies})", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 3a2ef39d49ece..250bf78fe8db2 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -360,6 +360,21 @@ "core.fatalErrors.tryRefreshingPageDescription": "请尝试刷新页面。如果无效,请返回上一页或清除您的会话数据。", "core.notifications.errorToast.closeModal": "关闭", "core.notifications.unableUpdateUISettingNotificationMessageTitle": "无法更新 UI 设置", + "core.statusPage.loadStatus.serverIsDownErrorMessage": "无法请求服务器状态。也许您的服务器已关闭?", + "core.statusPage.loadStatus.serverStatusCodeErrorMessage": "无法使用状态代码 {responseStatus} 请求服务器状态", + "core.statusPage.metricsTiles.columns.heapTotalHeader": "堆总计", + "core.statusPage.metricsTiles.columns.heapUsedHeader": "已使用堆", + "core.statusPage.metricsTiles.columns.loadHeader": "负载", + "core.statusPage.metricsTiles.columns.requestsPerSecHeader": "每秒请求数", + "core.statusPage.metricsTiles.columns.resTimeAvgHeader": "响应时间平均值", + "core.statusPage.metricsTiles.columns.resTimeMaxHeader": "响应时间最大值", + "core.statusPage.serverStatus.statusTitle": "Kibana 状态为“{kibanaStatus}”", + "core.statusPage.statusApp.loadingErrorText": "加载状态时出错", + "core.statusPage.statusApp.statusActions.buildText": "BUILD {buildNum}", + "core.statusPage.statusApp.statusActions.commitText": "COMMIT {buildSha}", + "core.statusPage.statusApp.statusTitle": "插件状态", + "core.statusPage.statusTable.columns.idHeader": "ID", + "core.statusPage.statusTable.columns.statusHeader": "状态", "core.toasts.errorToast.seeFullError": "请参阅完整的错误信息", "core.ui.chrome.headerGlobalNav.goHomePageIconAriaLabel": "前往主页", "core.ui.chrome.headerGlobalNav.helpMenuAskElasticTitle": "问询 Elastic", @@ -2473,21 +2488,6 @@ "server.status.redTitle": "红", "server.status.uninitializedTitle": "未初始化", "server.status.yellowTitle": "黄", - "statusPage.loadStatus.serverIsDownErrorMessage": "无法请求服务器状态。也许您的服务器已关闭?", - "statusPage.loadStatus.serverStatusCodeErrorMessage": "无法使用状态代码 {responseStatus} 请求服务器状态", - "statusPage.metricsTiles.columns.heapTotalHeader": "堆总计", - "statusPage.metricsTiles.columns.heapUsedHeader": "已使用堆", - "statusPage.metricsTiles.columns.loadHeader": "负载", - "statusPage.metricsTiles.columns.requestsPerSecHeader": "每秒请求数", - "statusPage.metricsTiles.columns.resTimeAvgHeader": "响应时间平均值", - "statusPage.metricsTiles.columns.resTimeMaxHeader": "响应时间最大值", - "statusPage.serverStatus.statusTitle": "Kibana 状态为“{kibanaStatus}”", - "statusPage.statusApp.loadingErrorText": "加载状态时出错", - "statusPage.statusApp.statusActions.buildText": "BUILD {buildNum}", - "statusPage.statusApp.statusActions.commitText": "COMMIT {buildSha}", - "statusPage.statusApp.statusTitle": "插件状态", - "statusPage.statusTable.columns.idHeader": "ID", - "statusPage.statusTable.columns.statusHeader": "状态", "telemetry.callout.appliesSettingTitle": "对此设置的更改将应用到{allOfKibanaText} 且会自动保存。", "telemetry.callout.appliesSettingTitle.allOfKibanaText": "整个 Kibana", "telemetry.callout.clusterStatisticsDescription": "这是我们将收集的基本集群统计信息的示例。其包括索引、分片和节点的数目。还包括概括性的使用情况统计信息,例如监测是否打开。", @@ -7420,10 +7420,6 @@ "xpack.infra.logs.analysis.anomalySectionNoDataTitle": "没有可显示的数据。", "xpack.infra.logs.analysis.jobStoppedCalloutMessage": "ML 作业已手动停止或由于缺乏资源而停止。作业重新启动后,才会处理新的日志条目。", "xpack.infra.logs.analysis.jobStoppedCalloutTitle": "ML 作业已停止", - "xpack.infra.logs.analysis.missingMlResultsPrivilegesBody": "此功能使用 Machine Learning 作业,要访问这些作业的状态和结果,至少需要 {machineLearningUserRole} 角色。", - "xpack.infra.logs.analysis.missingMlResultsPrivilegesTitle": "需要额外的 Machine Learning 权限", - "xpack.infra.logs.analysis.missingMlSetupPrivilegesBody": "此功能使用 Machine Learning 作业,这需要 {machineLearningAdminRole} 角色才能设置。", - "xpack.infra.logs.analysis.missingMlSetupPrivilegesTitle": "需要额外的 Machine Learning 权限", "xpack.infra.logs.analysis.mlAppButton": "打开 Machine Learning", "xpack.infra.logs.analysis.mlUnavailableBody": "查看 {machineLearningAppLink} 以获取更多信息。", "xpack.infra.logs.analysis.mlUnavailableTitle": "此功能需要 Machine Learning", @@ -8117,7 +8113,6 @@ "xpack.ingestManager.createPackageConfig.StepSelectConfig.errorLoadingAgentConfigsTitle": "加载代理配置时出错", "xpack.ingestManager.createPackageConfig.StepSelectConfig.errorLoadingPackageTitle": "加载软件包信息时出错", "xpack.ingestManager.createPackageConfig.StepSelectConfig.errorLoadingSelectedAgentConfigTitle": "加载选定代理配置时出错", - "xpack.ingestManager.createPackageConfig.StepSelectConfig.filterAgentConfigsInputPlaceholder": "搜索代理配置", "xpack.ingestManager.createPackageConfig.stepSelectPackage.errorLoadingConfigTitle": "加载代理配置信息时出错", "xpack.ingestManager.createPackageConfig.stepSelectPackage.errorLoadingPackagesTitle": "加载集成时出错", "xpack.ingestManager.createPackageConfig.stepSelectPackage.errorLoadingSelectedPackageTitle": "加载选定集成时出错", @@ -8187,8 +8182,6 @@ "xpack.ingestManager.editPackageConfig.updatedNotificationTitle": "已成功更新“{packageConfigName}”", "xpack.ingestManager.enrollemntAPIKeyList.emptyMessage": "未找到任何注册令牌。", "xpack.ingestManager.enrollemntAPIKeyList.loadingTokensMessage": "正在加载注册令牌......", - "xpack.ingestManager.enrollmentInstructions.copyButton": "复制命令", - "xpack.ingestManager.enrollmentInstructions.descriptionText": "从代理的目录,运行这些命令以注册并启动 Elastic 代理。{enrollCommand} 将写入代理的配置文件,以便其具有正确的设置。可以使用此命令在多个主机上设置代理。", "xpack.ingestManager.enrollmentStepAgentConfig.configSelectAriaLabel": "代理配置", "xpack.ingestManager.enrollmentStepAgentConfig.configSelectLabel": "代理配置", "xpack.ingestManager.enrollmentStepAgentConfig.enrollmentTokenSelectLabel": "注册令牌", @@ -8574,15 +8567,15 @@ "xpack.lens.pie.treemaplabel": "树状图", "xpack.lens.pie.treemapSuggestionLabel": "为树状图", "xpack.lens.pie.visualizationName": "饼图", - "xpack.lens.pieChart.alwaysShowLegendLabel": "显示", "xpack.lens.pieChart.categoriesInLegendLabel": "隐藏标签", - "xpack.lens.pieChart.defaultLegendLabel": "自动", "xpack.lens.pieChart.fitInsideOnlyLabel": "仅内部", "xpack.lens.pieChart.hiddenNumbersLabel": "在图表中隐藏", - "xpack.lens.pieChart.hideLegendLabel": "隐藏", "xpack.lens.pieChart.labelPositionLabel": "标签位置", "xpack.lens.pieChart.legendDisplayLabel": "图例显示", "xpack.lens.pieChart.legendDisplayLegend": "图例显示", + "xpack.lens.pieChart.legendVisibility.auto": "自动", + "xpack.lens.pieChart.legendVisibility.hide": "隐藏", + "xpack.lens.pieChart.legendVisibility.show": "显示", "xpack.lens.pieChart.nestedLegendLabel": "嵌套图例", "xpack.lens.pieChart.numberLabels": "标签值", "xpack.lens.pieChart.percentDecimalsLabel": "百分比的小数位数", @@ -10248,7 +10241,6 @@ "xpack.ml.newJob.recognize.advancedLabel": "高级", "xpack.ml.newJob.recognize.advancedSettingsAriaLabel": "高级设置", "xpack.ml.newJob.recognize.alreadyExistsLabel": "(已存在)", - "xpack.ml.newJob.recognize.analysisRunningLabel": "分析正在运行", "xpack.ml.newJob.recognize.cancelJobOverrideLabel": "关闭", "xpack.ml.newJob.recognize.createJobButtonAriaLabel": "创建作业", "xpack.ml.newJob.recognize.createJobButtonLabel": "创建{numberOfJobs, plural, zero {作业} one {Job} other {Jobs}}", @@ -13586,7 +13578,7 @@ "xpack.securitySolution.detectionEngine.editRule.errorMsgDescription": "抱歉", "xpack.securitySolution.detectionEngine.editRule.pageTitle": "编辑规则设置", "xpack.securitySolution.detectionEngine.editRule.saveChangeTitle": "保存更改", - "xpack.securitySolution.detectionEngine.emptyActionPrimary": "查看设置说明", + "xpack.securitySolution.detectionEngine.emptyActionBeats": "查看设置说明", "xpack.securitySolution.detectionEngine.emptyActionSecondary": "前往文档", "xpack.securitySolution.detectionEngine.emptyTitle": "似乎您没有与 Security 应用程序的检测引擎相关的索引", "xpack.securitySolution.detectionEngine.goToDocumentationButton": "查看文档", @@ -13879,7 +13871,6 @@ "xpack.securitySolution.detectionEngine.mlUnavailableTitle": "{totalRules} 个 {totalRules, plural, =1 {规则需要} other {规则需要}}启用 Machine Learning。", "xpack.securitySolution.detectionEngine.noApiIntegrationKeyCallOutMsg": "每次启动 Kibana,都会为已保存对象生成新的加密密钥。没有持久性密钥,在 Kibana 重新启动后,将无法删除或修改规则。要设置持久性密钥,请将文本值为 32 个或更多任意字符的 xpack.encryptedSavedObjects.encryptionKey 设置添加到 kibana.yml 文件。", "xpack.securitySolution.detectionEngine.noApiIntegrationKeyCallOutTitle": "需要 API 集成密钥", - "xpack.securitySolution.detectionEngine.noIndexMsgBody": "要使用检测引擎,具有所需集群和索引权限的用户必须首先访问此页面。若需要更多帮助,请联系您的管理员。", "xpack.securitySolution.detectionEngine.noIndexTitle": "让我们来设置您的检测引擎", "xpack.securitySolution.detectionEngine.pageTitle": "检测引擎", "xpack.securitySolution.detectionEngine.panelSubtitleShowing": "正在显示", @@ -14363,7 +14354,7 @@ "xpack.securitySolution.overview.viewEventsButtonLabel": "查看事件", "xpack.securitySolution.overview.winlogbeatMWSysmonOperational": "Microsoft-Windows-Sysmon/Operational", "xpack.securitySolution.overview.winlogbeatSecurityTitle": "安全", - "xpack.securitySolution.pages.common.emptyActionPrimary": "使用 Beats 添加数据", + "xpack.securitySolution.pages.common.emptyActionBeats": "使用 Beats 添加数据", "xpack.securitySolution.pages.common.emptyActionSecondary": "查看入门指南", "xpack.securitySolution.pages.common.emptyTitle": "欢迎使用 SIEM。让我们教您如何入门。", "xpack.securitySolution.pages.fourohfour.noContentFoundDescription": "未找到任何内容", @@ -16295,7 +16286,6 @@ "xpack.uptime.ml.enableAnomalyDetectionPanel.manageMLJobDescription.noteText": "注意:可能要过几分钟后,作业才会开始计算结果。", "xpack.uptime.ml.enableAnomalyDetectionPanel.startTrial": "开始为期 14 天的免费试用", "xpack.uptime.ml.enableAnomalyDetectionPanel.startTrialDesc": "要访问持续时间异常检测,必须订阅 Elastic 白金级许可证。", - "xpack.uptime.monitorCharts.durationChart.bottomAxis.title": "鏃堕棿鎴", "xpack.uptime.monitorCharts.durationChart.leftAxis.title": "持续时间 (ms)", "xpack.uptime.monitorCharts.monitorDuration.titleLabel": "监测持续时间(毫秒)", "xpack.uptime.monitorCharts.monitorDuration.titleLabelWithAnomaly": "监测持续时间(异常:{noOfAnomalies})", diff --git a/x-pack/plugins/triggers_actions_ui/README.md b/x-pack/plugins/triggers_actions_ui/README.md index 0dd2d100401f0..b8e765c9ea635 100644 --- a/x-pack/plugins/triggers_actions_ui/README.md +++ b/x-pack/plugins/triggers_actions_ui/README.md @@ -1294,7 +1294,7 @@ Then this dependencies will be used to embed Actions form or register your own a return ( { initialAlert.actions[index].id = id; @@ -1329,7 +1329,7 @@ interface ActionAccordionFormProps { 'get$' | 'add' | 'remove' | 'addSuccess' | 'addWarning' | 'addDanger' | 'addError' >; actionTypes?: ActionType[]; - messageVariables?: string[]; + messageVariables?: ActionVariable[]; defaultActionMessage?: string; consumer: string; } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/app.tsx b/x-pack/plugins/triggers_actions_ui/public/application/app.tsx index 80f8e4a3a2c77..1f9352d8405d2 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/app.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/app.tsx @@ -17,8 +17,7 @@ import { ScopedHistory, } from 'kibana/public'; import { Section, routeToAlertDetails } from './constants'; -import { AppContextProvider, useAppDependencies } from './app_context'; -import { hasShowAlertsCapability } from './lib/capabilities'; +import { AppContextProvider } from './app_context'; import { ActionTypeModel, AlertTypeModel } from '../types'; import { TypeRegistry } from './type_registry'; import { ChartsPluginStart } from '../../../../../src/plugins/charts/public'; @@ -63,22 +62,17 @@ export const App = (appDeps: AppDeps) => { }; export const AppWithoutRouter = ({ sectionsRegex }: { sectionsRegex: string }) => { - const { capabilities } = useAppDependencies(); - const canShowAlerts = hasShowAlertsCapability(capabilities); - const DEFAULT_SECTION: Section = canShowAlerts ? 'alerts' : 'connectors'; return ( - {canShowAlerts && ( - - )} - + + ); }; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/add_message_variables.scss b/x-pack/plugins/triggers_actions_ui/public/application/components/add_message_variables.scss index 996f21c4b6b09..521d0f399b19b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/add_message_variables.scss +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/add_message_variables.scss @@ -1,4 +1,5 @@ .messageVariablesPanel { @include euiYScrollWithShadows; max-height: $euiSize * 20; + max-width: $euiSize * 20; } \ No newline at end of file diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/add_message_variables.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/add_message_variables.tsx index 655f64995d147..0742ed8a778ef 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/add_message_variables.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/add_message_variables.tsx @@ -5,11 +5,18 @@ */ import React, { useState } from 'react'; import { i18n } from '@kbn/i18n'; -import { EuiPopover, EuiButtonIcon, EuiContextMenuPanel, EuiContextMenuItem } from '@elastic/eui'; +import { + EuiPopover, + EuiButtonIcon, + EuiContextMenuPanel, + EuiContextMenuItem, + EuiText, +} from '@elastic/eui'; import './add_message_variables.scss'; +import { ActionVariable } from '../../types'; interface Props { - messageVariables: string[] | undefined; + messageVariables?: ActionVariable[]; paramsProperty: string; onSelectEventHandler: (variable: string) => void; } @@ -22,17 +29,22 @@ export const AddMessageVariables: React.FunctionComponent = ({ const [isVariablesPopoverOpen, setIsVariablesPopoverOpen] = useState(false); const getMessageVariables = () => - messageVariables?.map((variable: string, i: number) => ( + messageVariables?.map((variable: ActionVariable, i: number) => ( { - onSelectEventHandler(variable); + onSelectEventHandler(variable.name); setIsVariablesPopoverOpen(false); }} > - {`{{${variable}}}`} + <> + {`{{${variable.name}}}`} + +
{variable.description}
+
+
)); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.test.tsx index 8ee953c00795e..6856e553ab400 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.test.tsx @@ -30,6 +30,7 @@ describe('EmailActionConnectorFields renders', () => { editActionConfig={() => {}} editActionSecrets={() => {}} docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} + readOnly={false} /> ); expect(wrapper.find('[data-test-subj="emailFromInput"]').length > 0).toBeTruthy(); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.tsx index 8a15320d5de16..4ef9c2e0d4d2e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_connector.tsx @@ -21,7 +21,7 @@ import { EmailActionConnector } from '../types'; export const EmailActionConnectorFields: React.FunctionComponent> = ({ action, editActionConfig, editActionSecrets, errors, docLinks }) => { +>> = ({ action, editActionConfig, editActionSecrets, errors, readOnly, docLinks }) => { const { from, host, port, secure } = action.config; const { user, password } = action.secrets; @@ -54,6 +54,7 @@ export const EmailActionConnectorFields: React.FunctionComponent 0 && from !== undefined} name="from" value={from || ''} @@ -86,6 +87,7 @@ export const EmailActionConnectorFields: React.FunctionComponent 0 && host !== undefined} name="host" value={host || ''} @@ -121,6 +123,7 @@ export const EmailActionConnectorFields: React.FunctionComponent 0 && port !== undefined} fullWidth + readOnly={readOnly} name="port" value={port || ''} data-test-subj="emailPortInput" @@ -145,6 +148,7 @@ export const EmailActionConnectorFields: React.FunctionComponent { editActionConfig('secure', e.target.checked); @@ -174,6 +178,7 @@ export const EmailActionConnectorFields: React.FunctionComponent 0} name="user" + readOnly={readOnly} value={user || ''} data-test-subj="emailUserInput" onChange={(e) => { @@ -197,6 +202,7 @@ export const EmailActionConnectorFields: React.FunctionComponent 0} name="password" value={password || ''} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.test.tsx index 4cb397927b53e..f5f14cb041335 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.test.tsx @@ -88,6 +88,7 @@ describe('IndexActionConnectorFields renders', () => { editActionSecrets={() => {}} http={deps!.http} docLinks={deps!.docLinks} + readOnly={false} /> ); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.tsx index 6fb078f3c808f..9cfb9f1dc25b2 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.tsx @@ -29,7 +29,7 @@ import { const IndexActionConnectorFields: React.FunctionComponent> = ({ action, editActionConfig, errors, http, docLinks }) => { +>> = ({ action, editActionConfig, errors, http, readOnly, docLinks }) => { const { index, refresh, executionTimeField } = action.config; const [hasTimeFieldCheckbox, setTimeFieldCheckboxState] = useState( executionTimeField != null @@ -115,6 +115,7 @@ const IndexActionConnectorFields: React.FunctionComponent { editActionConfig('index', selected.length > 0 ? selected[0].value : ''); const indices = selected.map((s) => s.value as string); @@ -145,6 +146,7 @@ const IndexActionConnectorFields: React.FunctionComponent { editActionConfig('refresh', e.target.checked); }} @@ -172,6 +174,7 @@ const IndexActionConnectorFields: React.FunctionComponent { setTimeFieldCheckboxState(!hasTimeFieldCheckbox); // if changing from checked to not checked (hasTimeField === true), diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.test.tsx index 86730c0ab4ac7..53e68e6453690 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.test.tsx @@ -34,6 +34,7 @@ describe('PagerDutyActionConnectorFields renders', () => { editActionConfig={() => {}} editActionSecrets={() => {}} docLinks={deps!.docLinks} + readOnly={false} /> ); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.tsx index 48da3f1778b48..6399e1f80984c 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_connectors.tsx @@ -12,7 +12,7 @@ import { PagerDutyActionConnector } from '.././types'; const PagerDutyActionConnectorFields: React.FunctionComponent> = ({ errors, action, editActionConfig, editActionSecrets, docLinks }) => { +>> = ({ errors, action, editActionConfig, editActionSecrets, docLinks, readOnly }) => { const { apiUrl } = action.config; const { routingKey } = action.secrets; return ( @@ -31,6 +31,7 @@ const PagerDutyActionConnectorFields: React.FunctionComponent) => { editActionConfig('apiUrl', e.target.value); @@ -69,6 +70,7 @@ const PagerDutyActionConnectorFields: React.FunctionComponent 0 && routingKey !== undefined} name="routingKey" + readOnly={readOnly} value={routingKey || ''} data-test-subj="pagerdutyRoutingKeyInput" onChange={(e: React.ChangeEvent) => { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.test.tsx index 25381614a6c07..216e6967833b2 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.test.tsx @@ -34,6 +34,7 @@ describe('ServiceNowActionConnectorFields renders', () => { editActionConfig={() => {}} editActionSecrets={() => {}} docLinks={deps!.docLinks} + readOnly={false} /> ); expect( @@ -72,6 +73,7 @@ describe('ServiceNowActionConnectorFields renders', () => { editActionConfig={() => {}} editActionSecrets={() => {}} docLinks={deps!.docLinks} + readOnly={false} consumer={'case'} /> ); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.tsx index 139ef8fa58ff3..f99a276305d75 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_connectors.tsx @@ -25,7 +25,7 @@ import { FieldMapping } from './case_mappings/field_mapping'; const ServiceNowConnectorFields: React.FC> = ({ action, editActionSecrets, editActionConfig, errors, consumer, docLinks }) => { +>> = ({ action, editActionSecrets, editActionConfig, errors, consumer, readOnly, docLinks }) => { // TODO: remove incidentConfiguration later, when Case ServiceNow will move their fields to the level of action execution const { apiUrl, incidentConfiguration, isCaseOwned } = action.config; const mapping = incidentConfiguration ? incidentConfiguration.mapping : []; @@ -97,6 +97,7 @@ const ServiceNowConnectorFields: React.FC variable === 'alertId')) { + if (!savedObjectId && messageVariables?.find((variable) => variable.name === 'alertId')) { editSubActionProperty('savedObjectId', '{{alertId}}'); } if (!urgency) { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.test.tsx index bd905c1c95650..5bc778830b6e6 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.test.tsx @@ -31,6 +31,7 @@ describe('SlackActionFields renders', () => { editActionConfig={() => {}} editActionSecrets={() => {}} docLinks={deps!.docLinks} + readOnly={false} /> ); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.tsx index b6efd9fa93266..aa3a1932eacdb 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.tsx @@ -12,7 +12,7 @@ import { SlackActionConnector } from '../types'; const SlackActionFields: React.FunctionComponent> = ({ action, editActionSecrets, errors, docLinks }) => { +>> = ({ action, editActionSecrets, errors, readOnly, docLinks }) => { const { webhookUrl } = action.secrets; return ( @@ -44,6 +44,7 @@ const SlackActionFields: React.FunctionComponent 0 && webhookUrl !== undefined} name="webhookUrl" + readOnly={readOnly} placeholder="Example: https://hooks.slack.com/services" value={webhookUrl || ''} data-test-subj="slackWebhookUrlInput" diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.test.tsx index 3a2afff03c58f..7f2bed6c41f3b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.test.tsx @@ -33,6 +33,7 @@ describe('WebhookActionConnectorFields renders', () => { editActionConfig={() => {}} editActionSecrets={() => {}} docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} + readOnly={false} /> ); expect(wrapper.find('[data-test-subj="webhookViewHeadersSwitch"]').length > 0).toBeTruthy(); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.tsx index 2321d5b4b5479..52160441adb5b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_connectors.tsx @@ -30,7 +30,7 @@ const HTTP_VERBS = ['post', 'put']; const WebhookActionConnectorFields: React.FunctionComponent> = ({ action, editActionConfig, editActionSecrets, errors }) => { +>> = ({ action, editActionConfig, editActionSecrets, errors, readOnly }) => { const { user, password } = action.secrets; const { method, url, headers } = action.config; @@ -128,6 +128,7 @@ const WebhookActionConnectorFields: React.FunctionComponent { @@ -153,6 +154,7 @@ const WebhookActionConnectorFields: React.FunctionComponent { @@ -222,6 +224,7 @@ const WebhookActionConnectorFields: React.FunctionComponent ({ text: verb.toUpperCase(), value: verb }))} onChange={(e) => { @@ -247,6 +250,7 @@ const WebhookActionConnectorFields: React.FunctionComponent 0 && url !== undefined} fullWidth + readOnly={readOnly} value={url || ''} placeholder="https:// or http://" data-test-subj="webhookUrlText" @@ -280,6 +284,7 @@ const WebhookActionConnectorFields: React.FunctionComponent 0 && user !== undefined} name="user" + readOnly={readOnly} value={user || ''} data-test-subj="webhookUserInput" onChange={(e) => { @@ -309,6 +314,7 @@ const WebhookActionConnectorFields: React.FunctionComponent 0 && password !== undefined} value={password || ''} data-test-subj="webhookPasswordInput" @@ -328,6 +334,7 @@ const WebhookActionConnectorFields: React.FunctionComponent = []; - if (canShowAlerts) { - tabs.push({ - id: 'alerts', - name: ( - - ), - }); - } + tabs.push({ + id: 'alerts', + name: ( + + ), + }); if (canShowActions) { tabs.push({ @@ -151,17 +145,15 @@ export const TriggersActionsUIHome: React.FunctionComponent )} - {canShowAlerts && ( - ( - - - - )} - /> - )} + ( + + + + )} + /> diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/action_variables.test.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/action_variables.test.ts index 578c93fc4cba8..c5009fad32942 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/lib/action_variables.test.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/action_variables.test.ts @@ -6,12 +6,13 @@ import { AlertType, ActionVariables } from '../../types'; import { actionVariablesFromAlertType } from './action_variables'; +import { ALERTS_FEATURE_ID } from '../../../../alerts/common'; beforeEach(() => jest.resetAllMocks()); describe('actionVariablesFromAlertType', () => { test('should return correct variables when no state or context provided', async () => { - const alertType = getAlertType({ context: [], state: [] }); + const alertType = getAlertType({ context: [], state: [], params: [] }); expect(actionVariablesFromAlertType(alertType)).toMatchInlineSnapshot(` Array [ Object { @@ -45,6 +46,7 @@ describe('actionVariablesFromAlertType', () => { { name: 'bar', description: 'bar-description' }, ], state: [], + params: [], }); expect(actionVariablesFromAlertType(alertType)).toMatchInlineSnapshot(` Array [ @@ -87,6 +89,7 @@ describe('actionVariablesFromAlertType', () => { { name: 'foo', description: 'foo-description' }, { name: 'bar', description: 'bar-description' }, ], + params: [], }); expect(actionVariablesFromAlertType(alertType)).toMatchInlineSnapshot(` Array [ @@ -132,6 +135,7 @@ describe('actionVariablesFromAlertType', () => { { name: 'fooS', description: 'fooS-description' }, { name: 'barS', description: 'barS-description' }, ], + params: [{ name: 'fooP', description: 'fooP-description' }], }); expect(actionVariablesFromAlertType(alertType)).toMatchInlineSnapshot(` Array [ @@ -163,6 +167,10 @@ describe('actionVariablesFromAlertType', () => { "description": "barC-description", "name": "context.barC", }, + Object { + "description": "fooP-description", + "name": "params.fooP", + }, Object { "description": "fooS-description", "name": "state.fooS", @@ -183,6 +191,7 @@ function getAlertType(actionVariables: ActionVariables): AlertType { actionVariables, actionGroups: [{ id: 'default', name: 'Default' }], defaultActionGroupId: 'default', - producer: 'alerting', + authorizedConsumers: {}, + producer: ALERTS_FEATURE_ID, }; } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/action_variables.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/action_variables.ts index 714dc5210e390..8bbe34847016d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/lib/action_variables.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/action_variables.ts @@ -11,9 +11,10 @@ import { AlertType, ActionVariable } from '../../types'; export function actionVariablesFromAlertType(alertType: AlertType): ActionVariable[] { const alwaysProvidedVars = getAlwaysProvidedActionVariables(); const contextVars = prefixKeys(alertType.actionVariables.context, 'context.'); + const paramsVars = prefixKeys(alertType.actionVariables.params, 'params.'); const stateVars = prefixKeys(alertType.actionVariables.state, 'state.'); - return alwaysProvidedVars.concat(contextVars, stateVars); + return alwaysProvidedVars.concat(contextVars, paramsVars, stateVars); } function prefixKeys(actionVariables: ActionVariable[], prefix: string): ActionVariable[] { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/alert_api.test.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/alert_api.test.ts index 94d9166b40909..fc5d301cb7cd0 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/lib/alert_api.test.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/alert_api.test.ts @@ -27,6 +27,7 @@ import { health, } from './alert_api'; import uuid from 'uuid'; +import { ALERTS_FEATURE_ID } from '../../../../alerts/common'; const http = httpServiceMock.createStartContract(); @@ -41,10 +42,12 @@ describe('loadAlertTypes', () => { actionVariables: { context: [{ name: 'var1', description: 'val1' }], state: [{ name: 'var2', description: 'val2' }], + params: [{ name: 'var3', description: 'val3' }], }, - producer: 'alerting', + producer: ALERTS_FEATURE_ID, actionGroups: [{ id: 'default', name: 'Default' }], defaultActionGroupId: 'default', + authorizedConsumers: {}, }, ]; http.get.mockResolvedValueOnce(resolvedValue); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/capabilities.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/capabilities.ts index 82d03be41e1aa..9e89a38377a4d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/lib/capabilities.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/capabilities.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +import { Alert, AlertType } from '../../types'; + /** * NOTE: Applications that want to show the alerting UIs will need to add * check against their features here until we have a better solution. This @@ -12,19 +14,16 @@ type Capabilities = Record; -const apps = ['apm', 'siem', 'uptime', 'infrastructure']; +export const hasShowActionsCapability = (capabilities: Capabilities) => capabilities?.actions?.show; +export const hasSaveActionsCapability = (capabilities: Capabilities) => capabilities?.actions?.save; +export const hasExecuteActionsCapability = (capabilities: Capabilities) => + capabilities?.actions?.execute; +export const hasDeleteActionsCapability = (capabilities: Capabilities) => + capabilities?.actions?.delete; -function hasCapability(capabilities: Capabilities, capability: string) { - return apps.some((app) => capabilities[app]?.[capability]); +export function hasAllPrivilege(alert: Alert, alertType?: AlertType): boolean { + return alertType?.authorizedConsumers[alert.consumer]?.all ?? false; } - -function createCapabilityCheck(capability: string) { - return (capabilities: Capabilities) => hasCapability(capabilities, capability); +export function hasReadPrivilege(alert: Alert, alertType?: AlertType): boolean { + return alertType?.authorizedConsumers[alert.consumer]?.read ?? false; } - -export const hasShowAlertsCapability = createCapabilityCheck('alerting:show'); -export const hasShowActionsCapability = createCapabilityCheck('actions:show'); -export const hasSaveAlertsCapability = createCapabilityCheck('alerting:save'); -export const hasSaveActionsCapability = createCapabilityCheck('actions:save'); -export const hasDeleteAlertsCapability = createCapabilityCheck('alerting:delete'); -export const hasDeleteActionsCapability = createCapabilityCheck('actions:delete'); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_connector_form.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_connector_form.test.tsx index 17a1d929a0def..b7c9865cbd9d0 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_connector_form.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_connector_form.test.tsx @@ -15,10 +15,16 @@ describe('action_connector_form', () => { let deps: any; beforeAll(async () => { const mocks = coreMock.createSetup(); + const [ + { + application: { capabilities }, + }, + ] = await mocks.getStartServices(); deps = { http: mocks.http, actionTypeRegistry: actionTypeRegistry as any, docLinks: { ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' }, + capabilities, }; }); @@ -56,6 +62,7 @@ describe('action_connector_form', () => { http={deps!.http} actionTypeRegistry={deps!.actionTypeRegistry} docLinks={deps!.docLinks} + capabilities={deps!.capabilities} /> ); } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_connector_form.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_connector_form.tsx index 794f5548c4b44..ed4edb0229c2b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_connector_form.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_connector_form.tsx @@ -18,10 +18,11 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { HttpSetup, DocLinksStart } from 'kibana/public'; +import { HttpSetup, ApplicationStart, DocLinksStart } from 'kibana/public'; import { ReducerAction } from './connector_reducer'; import { ActionConnector, IErrorObject, ActionTypeModel } from '../../../types'; import { TypeRegistry } from '../../type_registry'; +import { hasSaveActionsCapability } from '../../lib/capabilities'; export function validateBaseProperties(actionObject: ActionConnector) { const validationResult = { errors: {} }; @@ -53,6 +54,7 @@ interface ActionConnectorProps { http: HttpSetup; actionTypeRegistry: TypeRegistry; docLinks: DocLinksStart; + capabilities: ApplicationStart['capabilities']; consumer?: string; } @@ -65,8 +67,11 @@ export const ActionConnectorForm = ({ http, actionTypeRegistry, docLinks, + capabilities, consumer, }: ActionConnectorProps) => { + const canSave = hasSaveActionsCapability(capabilities); + const setActionProperty = (key: string, value: any) => { dispatch({ command: { type: 'setProperty' }, payload: { key, value } }); }; @@ -138,6 +143,7 @@ export const ActionConnectorForm = ({ > 0 && connector.name !== undefined} name="name" placeholder="Untitled" @@ -167,6 +173,7 @@ export const ActionConnectorForm = ({ { wrapper = mountWithIntl( { initialAlert.actions[index].id = id; 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 67c7ca91156da..2d4507ca93078 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 @@ -38,6 +38,7 @@ import { ActionTypeIndex, ActionConnector, ActionType, + ActionVariable, } from '../../../types'; import { SectionLoading } from '../../components/section_loading'; import { ConnectorAddModal } from './connector_add_modal'; @@ -45,6 +46,7 @@ import { TypeRegistry } from '../../type_registry'; import { actionTypeCompare } from '../../lib/action_type_compare'; import { checkActionFormActionTypeEnabled } from '../../lib/check_action_type_enabled'; import { VIEW_LICENSE_OPTIONS_LINK } from '../../../common/constants'; +import { hasSaveActionsCapability } from '../../lib/capabilities'; interface ActionAccordionFormProps { actions: AlertAction[]; @@ -60,7 +62,7 @@ interface ActionAccordionFormProps { >; docLinks: DocLinksStart; actionTypes?: ActionType[]; - messageVariables?: string[]; + messageVariables?: ActionVariable[]; defaultActionMessage?: string; setHasActionsDisabled?: (value: boolean) => void; capabilities: ApplicationStart['capabilities']; @@ -87,6 +89,8 @@ export const ActionForm = ({ capabilities, docLinks, }: ActionAccordionFormProps) => { + const canSave = hasSaveActionsCapability(capabilities); + const [addModalVisible, setAddModalVisibility] = useState(false); const [activeActionItem, setActiveActionItem] = useState( undefined @@ -254,6 +258,7 @@ export const ActionForm = ({ /> } labelAppend={ + canSave && actionTypesIndex && actionTypesIndex[actionConnector.actionTypeId].enabledInConfig ? ( + ); return ( - actionItem.id === emptyId) ? ( - actionItem.id === emptyId) ? ( + noConnectorsLabel + ) : ( + + ) + } + actions={[ + { + setActiveActionItem({ actionTypeId: actionItem.actionTypeId, index }); + setAddModalVisibility(true); }} - /> - ) : ( - - ) - } - actions={[ - { - setActiveActionItem({ actionTypeId: actionItem.actionTypeId, index }); - setAddModalVisibility(true); - }} - > + > + + , + ]} + /> + ) : ( + +

- , - ]} - /> +

+
+ )}
diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_flyout.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_flyout.tsx index 60ec0cfa6955e..19ce653e465f1 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_flyout.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_flyout.tsx @@ -118,6 +118,7 @@ export const ConnectorAddFlyout = ({ actionTypeRegistry={actionTypeRegistry} http={http} docLinks={docLinks} + capabilities={capabilities} consumer={consumer} /> ); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.test.tsx index 1b35b5636872d..3d621367fc40a 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.test.tsx @@ -26,10 +26,10 @@ describe('connector_add_modal', () => { http: mocks.http, capabilities: { ...capabilities, - siem: { - 'actions:show': true, - 'actions:save': true, - 'actions:delete': true, + actions: { + show: true, + save: true, + delete: true, }, }, actionTypeRegistry: actionTypeRegistry as any, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.tsx index 67c836fc12cf7..90abb986517d4 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.tsx @@ -166,6 +166,7 @@ export const ConnectorAddModal = ({ actionTypeRegistry={actionTypeRegistry} docLinks={docLinks} http={http} + capabilities={capabilities} consumer={consumer} /> diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_edit_flyout.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_edit_flyout.tsx index 52425a616aad4..ca75e730062ab 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_edit_flyout.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_edit_flyout.tsx @@ -195,6 +195,7 @@ export const ConnectorEditFlyout = ({ actionTypeRegistry={actionTypeRegistry} http={http} docLinks={docLinks} + capabilities={capabilities} consumer={consumer} /> ) : ( diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.test.tsx index 23a7223f9c21b..c96e62df71ce4 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.test.tsx @@ -61,10 +61,10 @@ describe('actions_connectors_list component empty', () => { navigateToApp, capabilities: { ...capabilities, - siem: { - 'actions:show': true, - 'actions:save': true, - 'actions:delete': true, + actions: { + show: true, + save: true, + delete: true, }, }, history: scopedHistoryMock.create(), @@ -168,10 +168,10 @@ describe('actions_connectors_list component with items', () => { navigateToApp, capabilities: { ...capabilities, - securitySolution: { - 'actions:show': true, - 'actions:save': true, - 'actions:delete': true, + actions: { + show: true, + save: true, + delete: true, }, }, history: scopedHistoryMock.create(), @@ -256,10 +256,10 @@ describe('actions_connectors_list component empty with show only capability', () navigateToApp, capabilities: { ...capabilities, - securitySolution: { - 'actions:show': true, - 'actions:save': false, - 'actions:delete': false, + actions: { + show: true, + save: false, + delete: false, }, }, history: scopedHistoryMock.create(), @@ -287,7 +287,7 @@ describe('actions_connectors_list component empty with show only capability', () it('renders no permissions to create connector', async () => { await setup(); - expect(wrapper.find('[defaultMessage="No permissions to create connector"]')).toHaveLength(1); + expect(wrapper.find('[defaultMessage="No permissions to create connectors"]')).toHaveLength(1); expect(wrapper.find('[data-test-subj="createActionButton"]')).toHaveLength(0); }); }); @@ -345,10 +345,10 @@ describe('actions_connectors_list with show only capability', () => { navigateToApp, capabilities: { ...capabilities, - securitySolution: { - 'actions:show': true, - 'actions:save': false, - 'actions:delete': false, + actions: { + show: true, + save: false, + delete: false, }, }, history: scopedHistoryMock.create(), @@ -446,10 +446,10 @@ describe('actions_connectors_list component with disabled items', () => { navigateToApp, capabilities: { ...capabilities, - securitySolution: { - 'actions:show': true, - 'actions:save': true, - 'actions:delete': true, + actions: { + show: true, + save: true, + delete: true, }, }, history: scopedHistoryMock.create(), 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 5d52896cc628f..837529bfc938d 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 @@ -17,6 +17,7 @@ import { EuiBetaBadge, EuiToolTip, EuiButtonIcon, + EuiEmptyPrompt, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -324,30 +325,45 @@ export const ActionsConnectorsList: React.FunctionComponent = () => { /> , ], - toolsRight: [ - setAddFlyoutVisibility(true)} - > - - , - ], + toolsRight: canSave + ? [ + setAddFlyoutVisibility(true)} + > + + , + ] + : [], }} /> ); const noPermissionPrompt = ( -

- -

+ + + + } + body={ +

+ +

+ } + /> ); return ( diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_details.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_details.test.tsx index d8f0d0b6b20a0..16d1a5c7c9c65 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_details.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_details.test.tsx @@ -20,6 +20,8 @@ import { i18n } from '@kbn/i18n'; import { ViewInApp } from './view_in_app'; import { PLUGIN } from '../../../constants/plugin'; import { coreMock } from 'src/core/public/mocks'; +import { ALERTS_FEATURE_ID } from '../../../../../../alerts/common'; + const mockes = coreMock.createSetup(); jest.mock('../../../app_context', () => ({ @@ -27,11 +29,6 @@ jest.mock('../../../app_context', () => ({ http: jest.fn(), capabilities: { get: jest.fn(() => ({})), - securitySolution: { - 'alerting:show': true, - 'alerting:save': true, - 'alerting:delete': true, - }, }, actionTypeRegistry: jest.fn(), alertTypeRegistry: { @@ -66,7 +63,9 @@ jest.mock('react-router-dom', () => ({ })); jest.mock('../../../lib/capabilities', () => ({ + hasAllPrivilege: jest.fn(() => true), hasSaveAlertsCapability: jest.fn(() => true), + hasExecuteActionsCapability: jest.fn(() => true), })); const mockAlertApis = { @@ -77,6 +76,10 @@ const mockAlertApis = { requestRefresh: jest.fn(), }; +const authorizedConsumers = { + [ALERTS_FEATURE_ID]: { read: true, all: true }, +}; + // const AlertDetails = withBulkAlertOperations(RawAlertDetails); describe('alert_details', () => { // mock Api handlers @@ -87,9 +90,10 @@ describe('alert_details', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; expect( @@ -125,9 +129,10 @@ describe('alert_details', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; expect( @@ -154,9 +159,10 @@ describe('alert_details', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; const actionTypes: ActionType[] = [ @@ -207,9 +213,10 @@ describe('alert_details', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; const actionTypes: ActionType[] = [ { @@ -265,9 +272,10 @@ describe('alert_details', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; expect( @@ -284,9 +292,10 @@ describe('alert_details', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; expect( @@ -312,9 +321,10 @@ describe('disable button', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; const enableButton = shallow( @@ -339,9 +349,10 @@ describe('disable button', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; const enableButton = shallow( @@ -366,9 +377,10 @@ describe('disable button', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; const disableAlert = jest.fn(); @@ -402,9 +414,10 @@ describe('disable button', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; const enableAlert = jest.fn(); @@ -441,9 +454,10 @@ describe('mute button', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; const enableButton = shallow( @@ -469,9 +483,10 @@ describe('mute button', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; const enableButton = shallow( @@ -497,9 +512,10 @@ describe('mute button', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; const muteAlert = jest.fn(); @@ -534,9 +550,10 @@ describe('mute button', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; const unmuteAlert = jest.fn(); @@ -571,9 +588,10 @@ describe('mute button', () => { id: '.noop', name: 'No Op', actionGroups: [{ id: 'default', name: 'Default' }], - actionVariables: { context: [], state: [] }, + actionVariables: { context: [], state: [], params: [] }, defaultActionGroupId: 'default', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers, }; const enableButton = shallow( @@ -590,6 +608,136 @@ describe('mute button', () => { }); }); +describe('edit button', () => { + const actionTypes: ActionType[] = [ + { + id: '.server-log', + name: 'Server log', + enabled: true, + enabledInConfig: true, + enabledInLicense: true, + minimumLicenseRequired: 'basic', + }, + ]; + + it('should render an edit button when alert and actions are editable', () => { + const alert = mockAlert({ + enabled: true, + muteAll: false, + actions: [ + { + group: 'default', + id: uuid.v4(), + params: {}, + actionTypeId: '.server-log', + }, + ], + }); + + const alertType = { + id: '.noop', + name: 'No Op', + actionGroups: [{ id: 'default', name: 'Default' }], + actionVariables: { context: [], state: [], params: [] }, + defaultActionGroupId: 'default', + producer: 'alerting', + authorizedConsumers, + }; + + expect( + shallow( + + ) + .find(EuiButtonEmpty) + .find('[name="edit"]') + .first() + .exists() + ).toBeTruthy(); + }); + + it('should not render an edit button when alert editable but actions arent', () => { + const { hasExecuteActionsCapability } = jest.requireMock('../../../lib/capabilities'); + hasExecuteActionsCapability.mockReturnValue(false); + const alert = mockAlert({ + enabled: true, + muteAll: false, + actions: [ + { + group: 'default', + id: uuid.v4(), + params: {}, + actionTypeId: '.server-log', + }, + ], + }); + + const alertType = { + id: '.noop', + name: 'No Op', + actionGroups: [{ id: 'default', name: 'Default' }], + actionVariables: { context: [], state: [], params: [] }, + defaultActionGroupId: 'default', + producer: 'alerting', + authorizedConsumers, + }; + + expect( + shallow( + + ) + .find(EuiButtonEmpty) + .find('[name="edit"]') + .first() + .exists() + ).toBeFalsy(); + }); + + it('should render an edit button when alert editable but actions arent when there are no actions on the alert', () => { + const { hasExecuteActionsCapability } = jest.requireMock('../../../lib/capabilities'); + hasExecuteActionsCapability.mockReturnValue(false); + const alert = mockAlert({ + enabled: true, + muteAll: false, + actions: [], + }); + + const alertType = { + id: '.noop', + name: 'No Op', + actionGroups: [{ id: 'default', name: 'Default' }], + actionVariables: { context: [], state: [], params: [] }, + defaultActionGroupId: 'default', + producer: 'alerting', + authorizedConsumers, + }; + + expect( + shallow( + + ) + .find(EuiButtonEmpty) + .find('[name="edit"]') + .first() + .exists() + ).toBeTruthy(); + }); +}); + function mockAlert(overloads: Partial = {}): Alert { return { id: uuid.v4(), @@ -597,7 +745,7 @@ function mockAlert(overloads: Partial = {}): Alert { name: `alert-${uuid.v4()}`, tags: [], alertTypeId: '.noop', - consumer: 'consumer', + consumer: ALERTS_FEATURE_ID, schedule: { interval: '1m' }, actions: [], params: {}, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_details.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_details.tsx index 66a7ac25d4a70..b1dd78ff59f34 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_details.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_details.tsx @@ -28,7 +28,7 @@ import { import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; import { useAppDependencies } from '../../../app_context'; -import { hasSaveAlertsCapability } from '../../../lib/capabilities'; +import { hasAllPrivilege, hasExecuteActionsCapability } from '../../../lib/capabilities'; import { Alert, AlertType, ActionType } from '../../../../types'; import { ComponentOpts as BulkOperationsComponentOpts, @@ -71,12 +71,20 @@ export const AlertDetails: React.FunctionComponent = ({ dataPlugin, } = useAppDependencies(); - const canSave = hasSaveAlertsCapability(capabilities); + const canExecuteActions = hasExecuteActionsCapability(capabilities); + const canSaveAlert = + hasAllPrivilege(alert, alertType) && + // if the alert has actions, can the user save the alert's action params + (canExecuteActions || (!canExecuteActions && alert.actions.length === 0)); + const actionTypesByTypeId = keyBy(actionTypes, 'id'); const hasEditButton = - canSave && alertTypeRegistry.has(alert.alertTypeId) + // can the user save the alert + canSaveAlert && + // is this alert type editable from within Alerts Management + (alertTypeRegistry.has(alert.alertTypeId) ? !alertTypeRegistry.get(alert.alertTypeId).requiresAppContext - : false; + : false); const alertActions = alert.actions; const uniqueActions = Array.from(new Set(alertActions.map((item: any) => item.actionTypeId))); @@ -124,6 +132,7 @@ export const AlertDetails: React.FunctionComponent = ({ data-test-subj="openEditAlertFlyoutButton" iconType="pencil" onClick={() => setEditFlyoutVisibility(true)} + name="edit" > = ({ { @@ -229,7 +238,7 @@ export const AlertDetails: React.FunctionComponent = ({ { if (isMuted) { @@ -255,7 +264,11 @@ export const AlertDetails: React.FunctionComponent = ({ {alert.enabled ? ( - + ) : ( diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_instances.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_instances.test.tsx index 2531fd2625b4b..dd2ee48b7a620 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_instances.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_instances.test.tsx @@ -52,7 +52,9 @@ describe('alert_instances', () => { ]; expect( - shallow() + shallow( + + ) .find(EuiBasicTable) .prop('items') ).toEqual(instances); @@ -68,6 +70,7 @@ describe('alert_instances', () => { durationEpoch={fake2MinutesAgo.getTime()} {...mockAPIs} alert={alert} + readOnly={false} alertState={alertState} /> ) @@ -95,6 +98,7 @@ describe('alert_instances', () => { { Promise; durationEpoch?: number; } & Pick; export const alertInstancesTableColumns = ( - onMuteAction: (instance: AlertInstanceListItem) => Promise + onMuteAction: (instance: AlertInstanceListItem) => Promise, + readOnly: boolean ) => [ { field: 'instance', @@ -90,6 +92,7 @@ export const alertInstancesTableColumns = ( showLabel={false} compressed={true} checked={alertInstance.isMuted} + disabled={readOnly} data-test-subj={`muteAlertInstanceButton_${alertInstance.instance}`} onChange={() => onMuteAction(alertInstance)} /> @@ -109,6 +112,7 @@ function durationAsString(duration: Duration): string { export function AlertInstances({ alert, + readOnly, alertState: { alertInstances = {} }, muteAlertInstance, unmuteAlertInstance, @@ -162,7 +166,7 @@ export function AlertInstances({ cellProps={() => ({ 'data-test-subj': 'cell', })} - columns={alertInstancesTableColumns(onMuteAction)} + columns={alertInstancesTableColumns(onMuteAction, readOnly)} data-test-subj="alertInstancesList" /> diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_instances_route.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_instances_route.test.tsx index 9bff33e4aa69c..975856beba556 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_instances_route.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_instances_route.test.tsx @@ -22,9 +22,9 @@ describe('alert_state_route', () => { const alert = mockAlert(); expect( - shallow().containsMatchingElement( - - ) + shallow( + + ).containsMatchingElement() ).toBeTruthy(); }); }); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_instances_route.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_instances_route.tsx index a02b44523e26c..d8a7d18eb87a9 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_instances_route.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_instances_route.tsx @@ -18,11 +18,13 @@ import { AlertInstancesWithApi as AlertInstances } from './alert_instances'; type WithAlertStateProps = { alert: Alert; + readOnly: boolean; requestRefresh: () => Promise; } & Pick; export const AlertInstancesRoute: React.FunctionComponent = ({ alert, + readOnly, requestRefresh, loadAlertState, }) => { @@ -36,7 +38,12 @@ export const AlertInstancesRoute: React.FunctionComponent = }, [alert]); return alertState ? ( - + ) : (
({ + loadAlertTypes: jest.fn(), + health: jest.fn((async) => ({ isSufficientlySecure: true, hasPermanentEncryptionKey: true })), +})); + const actionTypeRegistry = actionTypeRegistryMock.create(); const alertTypeRegistry = alertTypeRegistryMock.create(); @@ -42,6 +48,31 @@ describe('alert_add', () => { async function setup() { const mocks = coreMock.createSetup(); + const { loadAlertTypes } = jest.requireMock('../../lib/alert_api'); + const alertTypes = [ + { + id: 'my-alert-type', + name: 'Test', + actionGroups: [ + { + id: 'testActionGroup', + name: 'Test Action Group', + }, + ], + defaultActionGroupId: 'testActionGroup', + producer: ALERTS_FEATURE_ID, + authorizedConsumers: { + [ALERTS_FEATURE_ID]: { read: true, all: true }, + test: { read: true, all: true }, + }, + actionVariables: { + context: [], + state: [], + params: [], + }, + }, + ]; + loadAlertTypes.mockResolvedValue(alertTypes); const [ { application: { capabilities }, @@ -120,7 +151,11 @@ describe('alert_add', () => { }, }} > - {}} /> + {}} + /> ); @@ -135,6 +170,10 @@ describe('alert_add', () => { it('renders alert add flyout', async () => { await setup(); + await new Promise((resolve) => { + setTimeout(resolve, 1000); + }); + expect(wrapper.find('[data-test-subj="addAlertFlyoutTitle"]').exists()).toBeTruthy(); expect(wrapper.find('[data-test-subj="saveAlertButton"]').exists()).toBeTruthy(); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_add.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_add.tsx index 52c281761f2c1..20cbd42e34b67 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_add.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_add.tsx @@ -168,6 +168,9 @@ export const AlertAdd = ({ dispatch={dispatch} errors={errors} canChangeTrigger={canChangeTrigger} + operation={i18n.translate('xpack.triggersActionsUI.sections.alertAdd.operationName', { + defaultMessage: 'create', + })} /> diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_edit.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_edit.tsx index 076f4b69fb496..f991cea9c009c 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_edit.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_edit.tsx @@ -156,6 +156,9 @@ export const AlertEdit = ({ initialAlert, onClose }: AlertEditProps) => { errors={errors} canChangeTrigger={false} setHasActionsDisabled={setHasActionsDisabled} + operation="i18n.translate('xpack.triggersActionsUI.sections.alertEdit.operationName', { + defaultMessage: 'edit', + })" /> diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.test.tsx index c9ce2848c5670..6091519f5851e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.test.tsx @@ -13,6 +13,8 @@ import { ValidationResult, Alert } from '../../../types'; import { AlertForm } from './alert_form'; import { AlertsContextProvider } from '../../context/alerts_context'; import { coreMock } from 'src/core/public/mocks'; +import { ALERTS_FEATURE_ID } from '../../../../../alerts/common'; + const actionTypeRegistry = actionTypeRegistryMock.create(); const alertTypeRegistry = alertTypeRegistryMock.create(); jest.mock('../../lib/alert_api', () => ({ @@ -20,6 +22,10 @@ jest.mock('../../lib/alert_api', () => ({ })); describe('alert_form', () => { + beforeEach(() => { + jest.resetAllMocks(); + }); + let deps: any; const alertType = { id: 'my-alert-type', @@ -63,6 +69,26 @@ describe('alert_form', () => { async function setup() { const mocks = coreMock.createSetup(); + const { loadAlertTypes } = jest.requireMock('../../lib/alert_api'); + const alertTypes = [ + { + id: 'my-alert-type', + name: 'Test', + actionGroups: [ + { + id: 'testActionGroup', + name: 'Test Action Group', + }, + ], + defaultActionGroupId: 'testActionGroup', + producer: ALERTS_FEATURE_ID, + authorizedConsumers: { + [ALERTS_FEATURE_ID]: { read: true, all: true }, + test: { read: true, all: true }, + }, + }, + ]; + loadAlertTypes.mockResolvedValue(alertTypes); const [ { application: { capabilities }, @@ -85,7 +111,7 @@ describe('alert_form', () => { const initialAlert = ({ name: 'test', params: {}, - consumer: 'alerts', + consumer: ALERTS_FEATURE_ID, schedule: { interval: '1m', }, @@ -111,7 +137,12 @@ describe('alert_form', () => { capabilities: deps!.capabilities, }} > - {}} errors={{ name: [], interval: [] }} /> + {}} + errors={{ name: [], interval: [] }} + operation="create" + /> ); @@ -167,7 +198,11 @@ describe('alert_form', () => { }, ], defaultActionGroupId: 'testActionGroup', - producer: 'alerting', + producer: ALERTS_FEATURE_ID, + authorizedConsumers: { + [ALERTS_FEATURE_ID]: { read: true, all: true }, + test: { read: true, all: true }, + }, }, { id: 'same-consumer-producer-alert-type', @@ -180,6 +215,10 @@ describe('alert_form', () => { ], defaultActionGroupId: 'testActionGroup', producer: 'test', + authorizedConsumers: { + [ALERTS_FEATURE_ID]: { read: true, all: true }, + test: { read: true, all: true }, + }, }, ]); const mocks = coreMock.createSetup(); @@ -250,7 +289,12 @@ describe('alert_form', () => { capabilities: deps!.capabilities, }} > - {}} errors={{ name: [], interval: [] }} /> + {}} + errors={{ name: [], interval: [] }} + operation="create" + /> ); @@ -302,7 +346,7 @@ describe('alert_form', () => { name: 'test', alertTypeId: alertType.id, params: {}, - consumer: 'alerts', + consumer: ALERTS_FEATURE_ID, schedule: { interval: '1m', }, @@ -328,7 +372,12 @@ describe('alert_form', () => { capabilities: deps!.capabilities, }} > - {}} errors={{ name: [], interval: [] }} /> + {}} + errors={{ name: [], interval: [] }} + operation="create" + /> ); 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 874091b2bb7a8..c0674e6c4a5f7 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 @@ -24,6 +24,7 @@ import { EuiButtonIcon, EuiHorizontalRule, EuiLoadingSpinner, + EuiEmptyPrompt, } from '@elastic/eui'; import { some, filter, map, fold } from 'fp-ts/lib/Option'; import { pipe } from 'fp-ts/lib/pipeable'; @@ -38,6 +39,8 @@ import { AlertTypeModel, Alert, IErrorObject, AlertAction, AlertTypeIndex } from import { getTimeOptions } from '../../../common/lib/get_time_options'; import { useAlertsContext } from '../../context/alerts_context'; import { ActionForm } from '../action_connector_form'; +import { ALERTS_FEATURE_ID } from '../../../../../alerts/common'; +import { hasAllPrivilege, hasShowActionsCapability } from '../../lib/capabilities'; export function validateBaseProperties(alertObject: Alert) { const validationResult = { errors: {} }; @@ -78,6 +81,7 @@ interface AlertFormProps { errors: IErrorObject; canChangeTrigger?: boolean; // to hide Change trigger button setHasActionsDisabled?: (value: boolean) => void; + operation: string; } export const AlertForm = ({ @@ -86,6 +90,7 @@ export const AlertForm = ({ dispatch, errors, setHasActionsDisabled, + operation, }: AlertFormProps) => { const alertsContext = useAlertsContext(); const { @@ -96,6 +101,7 @@ export const AlertForm = ({ docLinks, capabilities, } = alertsContext; + const canShowActions = hasShowActionsCapability(capabilities); const [alertTypeModel, setAlertTypeModel] = useState( alert.alertTypeId ? alertTypeRegistry.get(alert.alertTypeId) : null @@ -121,12 +127,12 @@ export const AlertForm = ({ (async () => { try { const alertTypes = await loadAlertTypes({ http }); - const index: AlertTypeIndex = {}; + const index: AlertTypeIndex = new Map(); for (const alertTypeItem of alertTypes) { - index[alertTypeItem.id] = alertTypeItem; + index.set(alertTypeItem.id, alertTypeItem); } - if (alert.alertTypeId && index[alert.alertTypeId]) { - setDefaultActionGroupId(index[alert.alertTypeId].defaultActionGroupId); + if (alert.alertTypeId && index.has(alert.alertTypeId)) { + setDefaultActionGroupId(index.get(alert.alertTypeId)!.defaultActionGroupId); } setAlertTypesIndex(index); } catch (e) { @@ -167,21 +173,21 @@ export const AlertForm = ({ ? alertTypeModel.alertParamsExpression : null; - const alertTypeRegistryList = - alert.consumer === 'alerts' - ? alertTypeRegistry - .list() - .filter( - (alertTypeRegistryItem: AlertTypeModel) => !alertTypeRegistryItem.requiresAppContext - ) - : alertTypeRegistry - .list() - .filter( - (alertTypeRegistryItem: AlertTypeModel) => - alertTypesIndex && - alertTypesIndex[alertTypeRegistryItem.id] && - alertTypesIndex[alertTypeRegistryItem.id].producer === alert.consumer - ); + const alertTypeRegistryList = alertTypesIndex + ? alertTypeRegistry + .list() + .filter( + (alertTypeRegistryItem: AlertTypeModel) => + alertTypesIndex.has(alertTypeRegistryItem.id) && + hasAllPrivilege(alert, alertTypesIndex.get(alertTypeRegistryItem.id)) + ) + .filter((alertTypeRegistryItem: AlertTypeModel) => + alert.consumer === ALERTS_FEATURE_ID + ? !alertTypeRegistryItem.requiresAppContext + : alertTypesIndex.get(alertTypeRegistryItem.id)!.producer === alert.consumer + ) + : []; + const alertTypeNodes = alertTypeRegistryList.map(function (item, index) { return ( @@ -238,15 +244,7 @@ export const AlertForm = ({ ) : null} {AlertParamsExpressionComponent ? ( - - - - - - } - > + ) : null} - {defaultActionGroupId ? ( + {canShowActions && defaultActionGroupId ? ( av.name + alertTypesIndex && alertTypesIndex.has(alert.alertTypeId) + ? actionVariablesFromAlertType(alertTypesIndex.get(alert.alertTypeId)!).sort((a, b) => + a.name.toUpperCase().localeCompare(b.name.toUpperCase()) ) : undefined } @@ -487,7 +485,7 @@ export const AlertForm = ({ {alertTypeModel ? ( {alertTypeDetails} - ) : ( + ) : alertTypeNodes.length ? ( @@ -503,7 +501,47 @@ export const AlertForm = ({ {alertTypeNodes} + ) : alertTypesIndex ? ( + + ) : ( + )} ); }; + +const CenterJustifiedSpinner = () => ( + + + + + +); + +const NoAuthorizedAlertTypes = ({ operation }: { operation: string }) => ( + + + + } + body={ +
+

+ +

+
+ } + /> +); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.test.tsx index 69b0856297bb5..ada881cb93d1e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.test.tsx @@ -17,6 +17,7 @@ import { AppContextProvider } from '../../../app_context'; import { chartPluginMock } from '../../../../../../../../src/plugins/charts/public/mocks'; import { dataPluginMock } from '../../../../../../../../src/plugins/data/public/mocks'; import { alertingPluginMock } from '../../../../../../alerts/public/mocks'; +import { ALERTS_FEATURE_ID } from '../../../../../../alerts/common'; jest.mock('../../../lib/action_connector_api', () => ({ loadActionTypes: jest.fn(), @@ -47,6 +48,17 @@ const alertType = { alertParamsExpression: () => null, requiresAppContext: false, }; +const alertTypeFromApi = { + id: 'test_alert_type', + name: 'some alert type', + actionGroups: [{ id: 'default', name: 'Default' }], + actionVariables: { context: [], state: [] }, + defaultActionGroupId: 'default', + producer: ALERTS_FEATURE_ID, + authorizedConsumers: { + [ALERTS_FEATURE_ID]: { read: true, all: true }, + }, +}; alertTypeRegistry.list.mockReturnValue([alertType]); actionTypeRegistry.list.mockReturnValue([]); @@ -73,7 +85,7 @@ describe('alerts_list component empty', () => { name: 'Test2', }, ]); - loadAlertTypes.mockResolvedValue([{ id: 'test_alert_type', name: 'some alert type' }]); + loadAlertTypes.mockResolvedValue([alertTypeFromApi]); loadAllActions.mockResolvedValue([]); const mockes = coreMock.createSetup(); @@ -94,14 +106,7 @@ describe('alerts_list component empty', () => { http: mockes.http, uiSettings: mockes.uiSettings, navigateToApp, - capabilities: { - ...capabilities, - securitySolution: { - 'alerting:show': true, - 'alerting:save': true, - 'alerting:delete': true, - }, - }, + capabilities, history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: actionTypeRegistry as any, @@ -193,7 +198,7 @@ describe('alerts_list component with items', () => { name: 'Test2', }, ]); - loadAlertTypes.mockResolvedValue([{ id: 'test_alert_type', name: 'some alert type' }]); + loadAlertTypes.mockResolvedValue([alertTypeFromApi]); loadAllActions.mockResolvedValue([]); const mockes = coreMock.createSetup(); const [ @@ -213,14 +218,7 @@ describe('alerts_list component with items', () => { http: mockes.http, uiSettings: mockes.uiSettings, navigateToApp, - capabilities: { - ...capabilities, - securitySolution: { - 'alerting:show': true, - 'alerting:save': true, - 'alerting:delete': true, - }, - }, + capabilities, history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: actionTypeRegistry as any, @@ -295,14 +293,7 @@ describe('alerts_list component empty with show only capability', () => { http: mockes.http, uiSettings: mockes.uiSettings, navigateToApp, - capabilities: { - ...capabilities, - securitySolution: { - 'alerting:show': true, - 'alerting:save': false, - 'alerting:delete': false, - }, - }, + capabilities, history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: { @@ -390,7 +381,8 @@ describe('alerts_list with show only capability', () => { name: 'Test2', }, ]); - loadAlertTypes.mockResolvedValue([{ id: 'test_alert_type', name: 'some alert type' }]); + + loadAlertTypes.mockResolvedValue([alertTypeFromApi]); loadAllActions.mockResolvedValue([]); const mockes = coreMock.createSetup(); const [ @@ -410,14 +402,7 @@ describe('alerts_list with show only capability', () => { http: mockes.http, uiSettings: mockes.uiSettings, navigateToApp, - capabilities: { - ...capabilities, - securitySolution: { - 'alerting:show': true, - 'alerting:save': false, - 'alerting:delete': false, - }, - }, + capabilities, history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: actionTypeRegistry as any, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.tsx index 2929ce6defeaf..2b2897a2181b1 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.tsx @@ -18,6 +18,7 @@ import { EuiSpacer, EuiLink, EuiLoadingSpinner, + EuiEmptyPrompt, } from '@elastic/eui'; import { useHistory } from 'react-router-dom'; @@ -33,10 +34,12 @@ import { TypeFilter } from './type_filter'; import { ActionTypeFilter } from './action_type_filter'; import { loadAlerts, loadAlertTypes, deleteAlerts } from '../../../lib/alert_api'; import { loadActionTypes } from '../../../lib/action_connector_api'; -import { hasDeleteAlertsCapability, hasSaveAlertsCapability } from '../../../lib/capabilities'; +import { hasExecuteActionsCapability } from '../../../lib/capabilities'; import { routeToAlertDetails, DEFAULT_SEARCH_PAGE_SIZE } from '../../../constants'; import { DeleteModalConfirmation } from '../../../components/delete_modal_confirmation'; import { EmptyPrompt } from '../../../components/prompts/empty_prompt'; +import { ALERTS_FEATURE_ID } from '../../../../../../alerts/common'; +import { hasAllPrivilege } from '../../../lib/capabilities'; const ENTER_KEY = 13; @@ -64,8 +67,7 @@ export const AlertsList: React.FunctionComponent = () => { charts, dataPlugin, } = useAppDependencies(); - const canDelete = hasDeleteAlertsCapability(capabilities); - const canSave = hasSaveAlertsCapability(capabilities); + const canExecuteActions = hasExecuteActionsCapability(capabilities); const [actionTypes, setActionTypes] = useState([]); const [selectedIds, setSelectedIds] = useState([]); @@ -79,7 +81,7 @@ export const AlertsList: React.FunctionComponent = () => { const [alertTypesState, setAlertTypesState] = useState({ isLoading: false, isInitialized: false, - data: {}, + data: new Map(), }); const [alertsState, setAlertsState] = useState({ isLoading: false, @@ -91,16 +93,16 @@ export const AlertsList: React.FunctionComponent = () => { useEffect(() => { loadAlertsData(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [page, searchText, typesFilter, actionTypesFilter]); + }, [alertTypesState, page, searchText, typesFilter, actionTypesFilter]); useEffect(() => { (async () => { try { setAlertTypesState({ ...alertTypesState, isLoading: true }); const alertTypes = await loadAlertTypes({ http }); - const index: AlertTypeIndex = {}; + const index: AlertTypeIndex = new Map(); for (const alertType of alertTypes) { - index[alertType.id] = alertType; + index.set(alertType.id, alertType); } setAlertTypesState({ isLoading: false, data: index, isInitialized: true }); } catch (e) { @@ -134,30 +136,33 @@ export const AlertsList: React.FunctionComponent = () => { }, []); async function loadAlertsData() { - setAlertsState({ ...alertsState, isLoading: true }); - try { - const alertsResponse = await loadAlerts({ - http, - page, - searchText, - typesFilter, - actionTypesFilter, - }); - setAlertsState({ - isLoading: false, - data: alertsResponse.data, - totalItemCount: alertsResponse.total, - }); - } catch (e) { - toastNotifications.addDanger({ - title: i18n.translate( - 'xpack.triggersActionsUI.sections.alertsList.unableToLoadAlertsMessage', - { - defaultMessage: 'Unable to load alerts', - } - ), - }); - setAlertsState({ ...alertsState, isLoading: false }); + const hasAnyAuthorizedAlertType = alertTypesState.data.size > 0; + if (hasAnyAuthorizedAlertType) { + setAlertsState({ ...alertsState, isLoading: true }); + try { + const alertsResponse = await loadAlerts({ + http, + page, + searchText, + typesFilter, + actionTypesFilter, + }); + setAlertsState({ + isLoading: false, + data: alertsResponse.data, + totalItemCount: alertsResponse.total, + }); + } catch (e) { + toastNotifications.addDanger({ + title: i18n.translate( + 'xpack.triggersActionsUI.sections.alertsList.unableToLoadAlertsMessage', + { + defaultMessage: 'Unable to load alerts', + } + ), + }); + setAlertsState({ ...alertsState, isLoading: false }); + } } } @@ -245,11 +250,16 @@ export const AlertsList: React.FunctionComponent = () => { }, ]; + const authorizedAlertTypes = [...alertTypesState.data.values()]; + const authorizedToCreateAnyAlerts = authorizedAlertTypes.some( + (alertType) => alertType.authorizedConsumers[ALERTS_FEATURE_ID]?.all + ); + const toolsRight = [ setTypesFilter(types)} - options={Object.values(alertTypesState.data) + options={authorizedAlertTypes .map((alertType) => ({ value: alertType.id, name: alertType.name, @@ -263,7 +273,7 @@ export const AlertsList: React.FunctionComponent = () => { />, ]; - if (canSave) { + if (authorizedToCreateAnyAlerts) { toolsRight.push( { ); } + const authorizedToModifySelectedAlerts = selectedIds.length + ? filterAlertsById(alertsState.data, selectedIds).every((selectedAlert) => + hasAllPrivilege(selectedAlert, alertTypesState.data.get(selectedAlert.alertTypeId)) + ) + : false; + const table = ( - {selectedIds.length > 0 && canDelete && ( + {selectedIds.length > 0 && authorizedToModifySelectedAlerts && ( setIsPerformingAction(true)} onActionPerformed={() => { @@ -337,7 +354,7 @@ export const AlertsList: React.FunctionComponent = () => { items={ alertTypesState.isInitialized === false ? [] - : convertAlertsToTableItems(alertsState.data, alertTypesState.data) + : convertAlertsToTableItems(alertsState.data, alertTypesState.data, canExecuteActions) } itemId="id" columns={alertsTableColumns} @@ -354,15 +371,12 @@ export const AlertsList: React.FunctionComponent = () => { /* Don't display alert count until we have the alert types initialized */ totalItemCount: alertTypesState.isInitialized === false ? 0 : alertsState.totalItemCount, }} - selection={ - canDelete - ? { - onSelectionChange(updatedSelectedItemsList: AlertTableItem[]) { - setSelectedIds(updatedSelectedItemsList.map((item) => item.id)); - }, - } - : undefined - } + selection={{ + selectable: (alert: AlertTableItem) => alert.isEditable, + onSelectionChange(updatedSelectedItemsList: AlertTableItem[]) { + setSelectedIds(updatedSelectedItemsList.map((item) => item.id)); + }, + }} onChange={({ page: changedPage }: { page: Pagination }) => { setPage(changedPage); }} @@ -370,7 +384,11 @@ export const AlertsList: React.FunctionComponent = () => { ); - const loadedItems = convertAlertsToTableItems(alertsState.data, alertTypesState.data); + const loadedItems = convertAlertsToTableItems( + alertsState.data, + alertTypesState.data, + canExecuteActions + ); const isFilterApplied = !( isEmpty(searchText) && @@ -421,8 +439,10 @@ export const AlertsList: React.FunctionComponent = () => { - ) : ( + ) : authorizedToCreateAnyAlerts ? ( setAlertFlyoutVisibility(true)} /> + ) : ( + noPermissionPrompt )} { }} > @@ -448,15 +468,44 @@ export const AlertsList: React.FunctionComponent = () => { ); }; +const noPermissionPrompt = ( + + + + } + body={ +

+ +

+ } + /> +); + function filterAlertsById(alerts: Alert[], ids: string[]): Alert[] { return alerts.filter((alert) => ids.includes(alert.id)); } -function convertAlertsToTableItems(alerts: Alert[], alertTypesIndex: AlertTypeIndex) { +function convertAlertsToTableItems( + alerts: Alert[], + alertTypesIndex: AlertTypeIndex, + canExecuteActions: boolean +) { return alerts.map((alert) => ({ ...alert, actionsText: alert.actions.length, tagsText: alert.tags.join(', '), - alertType: alertTypesIndex[alert.alertTypeId]?.name ?? alert.alertTypeId, + alertType: alertTypesIndex.get(alert.alertTypeId)?.name ?? alert.alertTypeId, + isEditable: + hasAllPrivilege(alert, alertTypesIndex.get(alert.alertTypeId)) && + (canExecuteActions || (!canExecuteActions && !alert.actions.length)), })); } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/collapsed_item_actions.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/collapsed_item_actions.tsx index 2b746e5dea457..9279f8a1745fc 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/collapsed_item_actions.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/collapsed_item_actions.tsx @@ -20,8 +20,6 @@ import { } from '@elastic/eui'; import { AlertTableItem } from '../../../../types'; -import { useAppDependencies } from '../../../app_context'; -import { hasDeleteAlertsCapability, hasSaveAlertsCapability } from '../../../lib/capabilities'; import { ComponentOpts as BulkOperationsComponentOpts, withBulkAlertOperations, @@ -43,16 +41,11 @@ export const CollapsedItemActions: React.FunctionComponent = ({ muteAlert, setAlertsToDelete, }: ComponentOpts) => { - const { capabilities } = useAppDependencies(); - - const canDelete = hasDeleteAlertsCapability(capabilities); - const canSave = hasSaveAlertsCapability(capabilities); - const [isPopoverOpen, setIsPopoverOpen] = useState(false); const button = ( setIsPopoverOpen(!isPopoverOpen)} aria-label={i18n.translate( @@ -75,7 +68,7 @@ export const CollapsedItemActions: React.FunctionComponent = ({
= ({ { @@ -134,7 +127,7 @@ export const CollapsedItemActions: React.FunctionComponent = ({
setAlertsToDelete([item.id])} > diff --git a/x-pack/plugins/triggers_actions_ui/public/index.ts b/x-pack/plugins/triggers_actions_ui/public/index.ts index 55653f49001b9..7808e2a7f608d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/index.ts @@ -19,6 +19,8 @@ export { ActionType, ActionTypeRegistryContract, AlertTypeParamsExpressionProps, + ValidationResult, + ActionVariable, } from './types'; export { ConnectorAddFlyout, diff --git a/x-pack/plugins/triggers_actions_ui/public/plugin.ts b/x-pack/plugins/triggers_actions_ui/public/plugin.ts index af4d2784cfa67..25a917c7a1a15 100644 --- a/x-pack/plugins/triggers_actions_ui/public/plugin.ts +++ b/x-pack/plugins/triggers_actions_ui/public/plugin.ts @@ -14,13 +14,11 @@ import { import { i18n } from '@kbn/i18n'; import { registerBuiltInActionTypes } from './application/components/builtin_action_types'; import { registerBuiltInAlertTypes } from './application/components/builtin_alert_types'; -import { hasShowActionsCapability, hasShowAlertsCapability } from './application/lib/capabilities'; import { ActionTypeModel, AlertTypeModel } from './types'; import { TypeRegistry } from './application/type_registry'; import { ManagementSetup, ManagementAppMountParams, - ManagementApp, } from '../../../../src/plugins/management/public'; import { boot } from './application/boot'; import { ChartsPluginStart } from '../../../../src/plugins/charts/public'; @@ -50,10 +48,14 @@ interface PluginsStart { export class Plugin implements - CorePlugin { + CorePlugin< + TriggersAndActionsUIPublicPluginSetup, + TriggersAndActionsUIPublicPluginStart, + PluginsSetup, + PluginsStart + > { private actionTypeRegistry: TypeRegistry; private alertTypeRegistry: TypeRegistry; - private managementApp?: ManagementApp; constructor(initializerContext: PluginInitializerContext) { const actionTypeRegistry = new TypeRegistry(); @@ -67,7 +69,7 @@ export class Plugin const actionTypeRegistry = this.actionTypeRegistry; const alertTypeRegistry = this.alertTypeRegistry; - this.managementApp = plugins.management.sections.section.insightsAndAlerting.registerApp({ + plugins.management.sections.section.insightsAndAlerting.registerApp({ id: 'triggersActions', title: i18n.translate('xpack.triggersActionsUI.managementSection.displayName', { defaultMessage: 'Alerts and Actions', @@ -116,19 +118,7 @@ export class Plugin }; } - public start(core: CoreStart): TriggersAndActionsUIPublicPluginStart { - const { capabilities } = core.application; - - const canShowActions = hasShowActionsCapability(capabilities); - const canShowAlerts = hasShowAlertsCapability(capabilities); - const managementApp = this.managementApp as ManagementApp; - - // Don't register routes when user doesn't have access to the application - if (canShowActions || canShowAlerts) { - managementApp.enable(); - } else { - managementApp.disable(); - } + public start(): TriggersAndActionsUIPublicPluginStart { return { actionTypeRegistry: this.actionTypeRegistry, alertTypeRegistry: this.alertTypeRegistry, diff --git a/x-pack/plugins/triggers_actions_ui/public/types.ts b/x-pack/plugins/triggers_actions_ui/public/types.ts index fe3bf98b03230..a42a9f56a751f 100644 --- a/x-pack/plugins/triggers_actions_ui/public/types.ts +++ b/x-pack/plugins/triggers_actions_ui/public/types.ts @@ -19,7 +19,7 @@ export { Alert, AlertAction, AlertTaskState, RawAlertInstance, AlertingFramework export { ActionType }; export type ActionTypeIndex = Record; -export type AlertTypeIndex = Record; +export type AlertTypeIndex = Map; export type ActionTypeRegistryContract = PublicMethodsOf< TypeRegistry> >; @@ -32,6 +32,7 @@ export interface ActionConnectorFieldsProps { errors: IErrorObject; docLinks: DocLinksStart; http?: HttpSetup; + readOnly: boolean; consumer?: string; } @@ -40,7 +41,7 @@ export interface ActionParamsProps { index: number; editAction: (property: string, value: any, index: number) => void; errors: IErrorObject; - messageVariables?: string[]; + messageVariables?: ActionVariable[]; defaultMessage?: string; docLinks: DocLinksStart; } @@ -93,6 +94,7 @@ export interface ActionVariable { export interface ActionVariables { context: ActionVariable[]; state: ActionVariable[]; + params: ActionVariable[]; } export interface AlertType { @@ -101,6 +103,7 @@ export interface AlertType { actionGroups: ActionGroup[]; actionVariables: ActionVariables; defaultActionGroupId: ActionGroup['id']; + authorizedConsumers: Record; producer: string; } @@ -111,6 +114,7 @@ export type AlertWithoutId = Omit; export interface AlertTableItem extends Alert { alertType: AlertType['name']; tagsText: string; + isEditable: boolean; } export interface AlertTypeParamsExpressionProps< diff --git a/x-pack/plugins/ui_actions_enhanced/public/drilldowns/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx b/x-pack/plugins/ui_actions_enhanced/public/drilldowns/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx index 20d15b4f4d2bd..283464b137ff9 100644 --- a/x-pack/plugins/ui_actions_enhanced/public/drilldowns/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx +++ b/x-pack/plugins/ui_actions_enhanced/public/drilldowns/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx @@ -11,9 +11,8 @@ import { DrilldownWizardConfig, FlyoutDrilldownWizard } from '../flyout_drilldow import { FlyoutListManageDrilldowns } from '../flyout_list_manage_drilldowns'; import { IStorageWrapper } from '../../../../../../../src/plugins/kibana_utils/public'; import { - VALUE_CLICK_TRIGGER, - SELECT_RANGE_TRIGGER, TriggerContextMapping, + APPLY_FILTER_TRIGGER, } from '../../../../../../../src/plugins/ui_actions/public'; import { useContainerState } from '../../../../../../../src/plugins/kibana_utils/public'; import { DrilldownListItem } from '../list_manage_drilldowns'; @@ -67,8 +66,9 @@ export function createFlyoutManageDrilldowns({ return (props: ConnectedFlyoutManageDrilldownsProps) => { const isCreateOnly = props.viewMode === 'create'; + // TODO: https://github.com/elastic/kibana/issues/59569 const selectedTriggers: Array = React.useMemo( - () => [VALUE_CLICK_TRIGGER, SELECT_RANGE_TRIGGER], + () => [APPLY_FILTER_TRIGGER], [] ); diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_actions.test.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_actions.test.ts index 713d0cb85e2e8..525c3781be749 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_actions.test.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_actions.test.ts @@ -3,8 +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 Boom from 'boom'; +import { SavedObjectsErrorHelpers } from '../../../../../../src/core/server'; import moment from 'moment'; import { @@ -27,7 +26,7 @@ describe('ReindexActions', () => { beforeEach(() => { client = { - errors: null, + errors: SavedObjectsErrorHelpers, create: jest.fn(unimplemented('create')), bulkCreate: jest.fn(unimplemented('bulkCreate')), delete: jest.fn(unimplemented('delete')), @@ -306,7 +305,7 @@ describe('ReindexActions', () => { describe(`IndexConsumerType.${typeKey}`, () => { it('creates the lock doc if it does not exist and executes callback', async () => { expect.assertions(3); - client.get.mockRejectedValueOnce(Boom.notFound()); // mock no ML doc exists yet + client.get.mockRejectedValueOnce(SavedObjectsErrorHelpers.createGenericNotFoundError()); // mock no ML doc exists yet client.create.mockImplementationOnce((type: any, attributes: any, { id }: any) => Promise.resolve({ type, diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_actions.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_actions.ts index 54f9fe9d298f2..6d8afee1ff950 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_actions.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_actions.ts @@ -253,7 +253,7 @@ export const reindexActionsFactory = ( // The IndexGroup enum value (a string) serves as the ID of the lock doc return await client.get(REINDEX_OP_TYPE, indexGroup); } catch (e) { - if (e.isBoom && e.output.statusCode === 404) { + if (client.errors.isNotFoundError(e)) { return await client.create( REINDEX_OP_TYPE, { diff --git a/x-pack/plugins/uptime/common/constants/index.ts b/x-pack/plugins/uptime/common/constants/index.ts index 0ddb995301266..29ae9e47dfb8a 100644 --- a/x-pack/plugins/uptime/common/constants/index.ts +++ b/x-pack/plugins/uptime/common/constants/index.ts @@ -4,13 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -export * from './alerts'; export { CHART_FORMAT_LIMITS } from './chart_format_limits'; export { CLIENT_DEFAULTS } from './client_defaults'; export { CONTEXT_DEFAULTS } from './context_defaults'; export * from './capabilities'; export * from './settings_defaults'; -export { PLUGIN } from './plugin'; export { QUERY } from './query'; export * from './ui'; export * from './rest_api'; diff --git a/x-pack/plugins/uptime/public/apps/plugin.ts b/x-pack/plugins/uptime/public/apps/plugin.ts index 9af4dea9dbb44..cf750434ab324 100644 --- a/x-pack/plugins/uptime/public/apps/plugin.ts +++ b/x-pack/plugins/uptime/public/apps/plugin.ts @@ -12,10 +12,11 @@ import { AppMountParameters, } from 'kibana/public'; import { DEFAULT_APP_CATEGORIES } from '../../../../../src/core/public'; -import { UMFrontendLibs } from '../lib/lib'; -import { PLUGIN } from '../../common/constants'; -import { FeatureCatalogueCategory } from '../../../../../src/plugins/home/public'; -import { HomePublicPluginSetup } from '../../../../../src/plugins/home/public'; + +import { + FeatureCatalogueCategory, + HomePublicPluginSetup, +} from '../../../../../src/plugins/home/public'; import { EmbeddableStart } from '../../../../../src/plugins/embeddable/public'; import { TriggersAndActionsUIPublicPluginSetup, @@ -26,10 +27,8 @@ import { DataPublicPluginStart, } from '../../../../../src/plugins/data/public'; import { alertTypeInitializers } from '../lib/alert_types'; -import { kibanaService } from '../state/kibana_service'; -import { fetchIndexStatus } from '../state/api'; -import { ObservabilityPluginSetup } from '../../../observability/public'; -import { fetchUptimeOverviewData } from './uptime_overview_fetcher'; +import { FetchDataParams, ObservabilityPluginSetup } from '../../../observability/public'; +import { PLUGIN } from '../../common/constants/plugin'; export interface ClientPluginsSetup { data: DataPublicPluginSetup; @@ -66,14 +65,23 @@ export class UptimePlugin category: FeatureCatalogueCategory.DATA, }); } + const getUptimeDataHelper = async () => { + const [coreStart] = await core.getStartServices(); + const { UptimeDataHelper } = await import('./uptime_overview_fetcher'); + return UptimeDataHelper(coreStart); + }; plugins.observability.dashboard.register({ appName: 'uptime', hasData: async () => { - const status = await fetchIndexStatus(); + const dataHelper = await getUptimeDataHelper(); + const status = await dataHelper.indexStatus(); return status.docCount > 0; }, - fetchData: fetchUptimeOverviewData, + fetchData: async (params: FetchDataParams) => { + const dataHelper = await getUptimeDataHelper(); + return await dataHelper.overviewData(params); + }, }); core.application.register({ @@ -85,22 +93,15 @@ export class UptimePlugin category: DEFAULT_APP_CATEGORIES.observability, mount: async (params: AppMountParameters) => { const [coreStart, corePlugins] = await core.getStartServices(); - const { getKibanaFrameworkAdapter } = await import( - '../lib/adapters/framework/new_platform_adapter' - ); - const { element } = params; + const { renderApp } = await import('./render_app'); - const libs: UMFrontendLibs = { - framework: getKibanaFrameworkAdapter(coreStart, plugins, corePlugins), - }; - return libs.framework.render(element); + return renderApp(coreStart, plugins, corePlugins, params); }, }); } public start(start: CoreStart, plugins: ClientPluginsStart): void { - kibanaService.core = start; alertTypeInitializers.forEach((init) => { const alertInitializer = init({ core: start, diff --git a/x-pack/plugins/uptime/public/lib/adapters/framework/new_platform_adapter.tsx b/x-pack/plugins/uptime/public/apps/render_app.tsx similarity index 72% rename from x-pack/plugins/uptime/public/lib/adapters/framework/new_platform_adapter.tsx rename to x-pack/plugins/uptime/public/apps/render_app.tsx index d6185f2c2589a..f834f8b5cdd3c 100644 --- a/x-pack/plugins/uptime/public/lib/adapters/framework/new_platform_adapter.tsx +++ b/x-pack/plugins/uptime/public/apps/render_app.tsx @@ -4,26 +4,26 @@ * you may not use this file except in compliance with the Elastic License. */ -import { CoreStart } from 'src/core/public'; import React from 'react'; import ReactDOM from 'react-dom'; import { i18n as i18nFormatter } from '@kbn/i18n'; -import { UptimeApp, UptimeAppProps } from '../../../uptime_app'; -import { getIntegratedAppAvailability } from './capabilities_adapter'; +import { AppMountParameters, CoreStart } from 'kibana/public'; +import { getIntegratedAppAvailability } from '../lib/adapters/framework/capabilities_adapter'; import { - INTEGRATED_SOLUTIONS, - PLUGIN, DEFAULT_DARK_MODE, DEFAULT_TIMEPICKER_QUICK_RANGES, -} from '../../../../common/constants'; -import { UMFrameworkAdapter } from '../../lib'; -import { ClientPluginsStart, ClientPluginsSetup } from '../../../apps/plugin'; + INTEGRATED_SOLUTIONS, +} from '../../common/constants'; +import { UptimeApp, UptimeAppProps } from './uptime_app'; +import { ClientPluginsSetup, ClientPluginsStart } from './plugin'; +import { PLUGIN } from '../../common/constants/plugin'; -export const getKibanaFrameworkAdapter = ( +export function renderApp( core: CoreStart, plugins: ClientPluginsSetup, - startPlugins: ClientPluginsStart -): UMFrameworkAdapter => { + startPlugins: ClientPluginsStart, + { element }: AppMountParameters +) { const { application: { capabilities }, chrome: { setBadge, setHelpExtension }, @@ -40,17 +40,17 @@ export const getKibanaFrameworkAdapter = ( const canSave = (capabilities.uptime.save ?? false) as boolean; const props: UptimeAppProps = { - basePath: basePath.get(), + plugins, canSave, core, + i18n, + startPlugins, + basePath: basePath.get(), darkMode: core.uiSettings.get(DEFAULT_DARK_MODE), commonlyUsedRanges: core.uiSettings.get(DEFAULT_TIMEPICKER_QUICK_RANGES), - i18n, isApmAvailable: apm, isInfraAvailable: infrastructure, isLogsAvailable: logs, - plugins, - startPlugins, renderGlobalHelpControls: () => setHelpExtension({ appName: i18nFormatter.translate('xpack.uptime.header.appName', { @@ -72,15 +72,9 @@ export const getKibanaFrameworkAdapter = ( setBreadcrumbs: core.chrome.setBreadcrumbs, }; - return { - render: async (element: any) => { - if (element) { - ReactDOM.render(, element); - } + ReactDOM.render(, element); - return () => { - ReactDOM.unmountComponentAtNode(element); - }; - }, + return () => { + ReactDOM.unmountComponentAtNode(element); }; -}; +} diff --git a/x-pack/plugins/uptime/public/apps/template.html b/x-pack/plugins/uptime/public/apps/template.html deleted file mode 100644 index a6fb47048a9b1..0000000000000 --- a/x-pack/plugins/uptime/public/apps/template.html +++ /dev/null @@ -1 +0,0 @@ -
\ No newline at end of file diff --git a/x-pack/plugins/uptime/public/uptime_app.tsx b/x-pack/plugins/uptime/public/apps/uptime_app.tsx similarity index 84% rename from x-pack/plugins/uptime/public/uptime_app.tsx rename to x-pack/plugins/uptime/public/apps/uptime_app.tsx index 4208d79e761ed..41370f9fff492 100644 --- a/x-pack/plugins/uptime/public/uptime_app.tsx +++ b/x-pack/plugins/uptime/public/apps/uptime_app.tsx @@ -9,24 +9,25 @@ import { i18n } from '@kbn/i18n'; import React, { useEffect } from 'react'; import { Provider as ReduxProvider } from 'react-redux'; import { BrowserRouter as Router } from 'react-router-dom'; -import { I18nStart, ChromeBreadcrumb, CoreStart } from 'src/core/public'; -import { KibanaContextProvider } from '../../../../src/plugins/kibana_react/public'; -import { ClientPluginsSetup, ClientPluginsStart } from './apps/plugin'; -import { UMUpdateBadge } from './lib/lib'; +import { I18nStart, ChromeBreadcrumb, CoreStart } from 'kibana/public'; +import { KibanaContextProvider } from '../../../../../src/plugins/kibana_react/public'; +import { ClientPluginsSetup, ClientPluginsStart } from './plugin'; +import { UMUpdateBadge } from '../lib/lib'; import { UptimeRefreshContextProvider, UptimeSettingsContextProvider, UptimeThemeContextProvider, UptimeStartupPluginsContextProvider, -} from './contexts'; -import { CommonlyUsedRange } from './components/common/uptime_date_picker'; -import { setBasePath } from './state/actions'; -import { PageRouter } from './routes'; +} from '../contexts'; +import { CommonlyUsedRange } from '../components/common/uptime_date_picker'; +import { setBasePath } from '../state/actions'; +import { PageRouter } from '../routes'; import { UptimeAlertsContextProvider, UptimeAlertsFlyoutWrapper, -} from './components/overview/alerts'; -import { store } from './state'; +} from '../components/overview/alerts'; +import { store } from '../state'; +import { kibanaService } from '../state/kibana_service'; export interface UptimeAppColors { danger: string; @@ -86,6 +87,8 @@ const Application = (props: UptimeAppProps) => { ); }, [canSave, renderGlobalHelpControls, setBadge]); + kibanaService.core = core; + store.dispatch(setBasePath(basePath)); return ( diff --git a/x-pack/plugins/uptime/public/apps/uptime_overview_fetcher.ts b/x-pack/plugins/uptime/public/apps/uptime_overview_fetcher.ts index d1e394dd4da6b..7e5c18f13b29e 100644 --- a/x-pack/plugins/uptime/public/apps/uptime_overview_fetcher.ts +++ b/x-pack/plugins/uptime/public/apps/uptime_overview_fetcher.ts @@ -4,10 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -import { fetchPingHistogram, fetchSnapshotCount } from '../state/api'; +import { CoreStart } from 'kibana/public'; import { UptimeFetchDataResponse, FetchDataParams } from '../../../observability/public'; +import { fetchIndexStatus, fetchPingHistogram, fetchSnapshotCount } from '../state/api'; +import { kibanaService } from '../state/kibana_service'; -export async function fetchUptimeOverviewData({ +async function fetchUptimeOverviewData({ absoluteTime, relativeTime, bucketSize, @@ -52,3 +54,12 @@ export async function fetchUptimeOverviewData({ }; return response; } + +export function UptimeDataHelper(coreStart: CoreStart | null) { + kibanaService.core = coreStart!; + + return { + indexStatus: fetchIndexStatus, + overviewData: fetchUptimeOverviewData, + }; +} diff --git a/x-pack/plugins/uptime/public/components/common/charts/__tests__/__snapshots__/ping_histogram.test.tsx.snap b/x-pack/plugins/uptime/public/components/common/charts/__tests__/__snapshots__/ping_histogram.test.tsx.snap index fe20071ced4cb..7fdb2e4ede75b 100644 --- a/x-pack/plugins/uptime/public/components/common/charts/__tests__/__snapshots__/ping_histogram.test.tsx.snap +++ b/x-pack/plugins/uptime/public/components/common/charts/__tests__/__snapshots__/ping_histogram.test.tsx.snap @@ -2,11 +2,14 @@ exports[`PingHistogram component renders the component without errors 1`] = ` Array [ -

Pings over time -

, + , +
,
{ + beforeAll(() => { + moment.prototype.fromNow = jest.fn(() => 'a year ago'); + }); + const props: PingHistogramComponentProps = { absoluteStartDate: 1548697920000, absoluteEndDate: 1548700920000, diff --git a/x-pack/plugins/uptime/public/components/common/charts/duration_chart.tsx b/x-pack/plugins/uptime/public/components/common/charts/duration_chart.tsx index a1e23ab8b38a7..35335f9868978 100644 --- a/x-pack/plugins/uptime/public/components/common/charts/duration_chart.tsx +++ b/x-pack/plugins/uptime/public/components/common/charts/duration_chart.tsx @@ -93,7 +93,7 @@ export const DurationChartComponent = ({ xDomain={{ min, max }} showLegend showLegendExtra - legendPosition={Position.Bottom} + legendPosition={Position.Right} onBrushEnd={onBrushEnd} onLegendItemClick={legendToggleVisibility} {...chartTheme} @@ -103,9 +103,6 @@ export const DurationChartComponent = ({ position={Position.Bottom} showOverlappingTicks={true} tickFormat={timeFormatter(getChartDateLabel(min, max))} - title={i18n.translate('xpack.uptime.monitorCharts.durationChart.bottomAxis.title', { - defaultMessage: 'Timestamp', - })} /> getTickFormat(d)} title={i18n.translate('xpack.uptime.monitorCharts.durationChart.leftAxis.title', { - defaultMessage: 'Duration ms', + defaultMessage: 'Duration in ms', })} /> diff --git a/x-pack/plugins/uptime/public/components/common/charts/ping_histogram.tsx b/x-pack/plugins/uptime/public/components/common/charts/ping_histogram.tsx index d5f3b1b164ad9..39b8a38f60982 100644 --- a/x-pack/plugins/uptime/public/components/common/charts/ping_histogram.tsx +++ b/x-pack/plugins/uptime/public/components/common/charts/ping_histogram.tsx @@ -13,7 +13,7 @@ import { timeFormatter, BrushEndListener, } from '@elastic/charts'; -import { EuiTitle } from '@elastic/eui'; +import { EuiTitle, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { useContext } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -173,14 +173,15 @@ export const PingHistogramComponent: React.FC = ({ return ( <> - -

+ +

-

+

+ {content} ); diff --git a/x-pack/plugins/uptime/public/components/monitor/ml/__tests__/__snapshots__/ml_integerations.test.tsx.snap b/x-pack/plugins/uptime/public/components/monitor/ml/__tests__/__snapshots__/ml_integerations.test.tsx.snap index 24c4e818a0592..15f5c03512bf1 100644 --- a/x-pack/plugins/uptime/public/components/monitor/ml/__tests__/__snapshots__/ml_integerations.test.tsx.snap +++ b/x-pack/plugins/uptime/public/components/monitor/ml/__tests__/__snapshots__/ml_integerations.test.tsx.snap @@ -8,18 +8,18 @@ exports[`ML Integrations renders without errors 1`] = ` class="euiPopover__anchor" >
,
-

- Down in 2 Locations -

-
+ Down in 2 locations + `; exports[`StatusByLocation component renders properly against props 1`] = ` - +

-
+ `; exports[`StatusByLocation component renders when down in some locations 1`] = ` -
-

- Down in 1/2 Locations -

-
+ Down in 1/2 locations + `; exports[`StatusByLocation component renders when only one location and it is down 1`] = ` -
-

- Down in 1 Location -

-
+ Down in 1 location + `; exports[`StatusByLocation component renders when only one location and it is up 1`] = ` -
-

- Up in 1 Location -

-
+ Up in 1 location + `; exports[`StatusByLocation component renders when up in all locations 1`] = ` -
-

- Up in 2 Locations -

-
+ Up in 2 locations + `; diff --git a/x-pack/plugins/uptime/public/components/monitor/status_details/location_map/embeddables/__tests__/map_config.test.ts b/x-pack/plugins/uptime/public/components/monitor/status_details/location_map/embeddables/__tests__/map_config.test.ts index 09a41bd9eb4b9..18b43434da24b 100644 --- a/x-pack/plugins/uptime/public/components/monitor/status_details/location_map/embeddables/__tests__/map_config.test.ts +++ b/x-pack/plugins/uptime/public/components/monitor/status_details/location_map/embeddables/__tests__/map_config.test.ts @@ -7,7 +7,7 @@ import { getLayerList } from '../map_config'; import { mockLayerList } from './__mocks__/mock'; import { LocationPoint } from '../embedded_map'; -import { UptimeAppColors } from '../../../../../../uptime_app'; +import { UptimeAppColors } from '../../../../../../apps/uptime_app'; jest.mock('uuid', () => { return { diff --git a/x-pack/plugins/uptime/public/components/monitor/status_details/location_map/embeddables/map_config.ts b/x-pack/plugins/uptime/public/components/monitor/status_details/location_map/embeddables/map_config.ts index e766641102a24..6f9b7e4d39c16 100644 --- a/x-pack/plugins/uptime/public/components/monitor/status_details/location_map/embeddables/map_config.ts +++ b/x-pack/plugins/uptime/public/components/monitor/status_details/location_map/embeddables/map_config.ts @@ -6,7 +6,7 @@ import lowPolyLayerFeatures from './low_poly_layer.json'; import { LocationPoint } from './embedded_map'; -import { UptimeAppColors } from '../../../../../uptime_app'; +import { UptimeAppColors } from '../../../../../apps/uptime_app'; /** * Returns `Source/Destination Point-to-point` Map LayerList configuration, with a source, diff --git a/x-pack/plugins/uptime/public/components/monitor/status_details/status_bar/status_by_location.tsx b/x-pack/plugins/uptime/public/components/monitor/status_details/status_bar/status_by_location.tsx index 461ffc10124fd..fb2a55bb4059b 100644 --- a/x-pack/plugins/uptime/public/components/monitor/status_details/status_bar/status_by_location.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/status_details/status_bar/status_by_location.tsx @@ -5,7 +5,7 @@ */ import React from 'react'; -import { EuiText } from '@elastic/eui'; +import { EuiTitle } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { MonitorLocation } from '../../../../../common/runtime_types'; @@ -43,7 +43,7 @@ export const StatusByLocations = ({ locations }: StatusByLocationsProps) => { } return ( - +

{locations.length <= 1 ? ( { status, loc: statusMessage, }} - defaultMessage="{status} in {loc} Location" + defaultMessage="{status} in {loc} location" /> ) : ( { status, loc: statusMessage, }} - defaultMessage="{status} in {loc} Locations" + defaultMessage="{status} in {loc} locations" /> )}

-
+ ); }; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/__tests__/alert_monitor_status.test.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/__tests__/alert_monitor_status.test.tsx index f3f3d583fd938..f26da59238b20 100644 --- a/x-pack/plugins/uptime/public/components/overview/alerts/__tests__/alert_monitor_status.test.tsx +++ b/x-pack/plugins/uptime/public/components/overview/alerts/__tests__/alert_monitor_status.test.tsx @@ -17,10 +17,6 @@ describe('alert monitor status component', () => { timerangeUnit: 'h', timerangeCount: 21, }, - autocomplete: { - addQuerySuggestionProvider: jest.fn(), - getQuerySuggestions: jest.fn(), - }, enabled: true, hasFilters: false, isOldAlert: true, @@ -45,12 +41,6 @@ describe('alert monitor status component', () => { /> = (p setAlertParams('search', value)} diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/alerts_containers/alert_monitor_status.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/alerts_containers/alert_monitor_status.tsx index 4ac0355f5edc8..50b6fe2aa0ef1 100644 --- a/x-pack/plugins/uptime/public/components/overview/alerts/alerts_containers/alert_monitor_status.tsx +++ b/x-pack/plugins/uptime/public/components/overview/alerts/alerts_containers/alert_monitor_status.tsx @@ -7,7 +7,6 @@ import React, { useMemo, useEffect } from 'react'; import { useLocation } from 'react-router-dom'; import { useSelector, useDispatch } from 'react-redux'; -import { DataPublicPluginSetup } from 'src/plugins/data/public'; import { isRight } from 'fp-ts/lib/Either'; import { selectMonitorStatusAlert, @@ -32,7 +31,6 @@ import { useUpdateKueryString } from '../../../../hooks'; interface Props { alertParams: { [key: string]: any }; - autocomplete: DataPublicPluginSetup['autocomplete']; enabled: boolean; numTimes: number; setAlertParams: (key: string, value: any) => void; @@ -43,7 +41,6 @@ interface Props { } export const AlertMonitorStatus: React.FC = ({ - autocomplete, enabled, numTimes, setAlertParams, @@ -122,7 +119,6 @@ export const AlertMonitorStatus: React.FC = ({ return ( = () => { /> ); }; - -// eslint-disable-next-line import/no-default-export -export { AlertTls as default }; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/anomaly_alert.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/anomaly_alert.tsx index 4b84012575ae9..1428a7f526fc2 100644 --- a/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/anomaly_alert.tsx +++ b/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/anomaly_alert.tsx @@ -25,8 +25,7 @@ interface Props { setAlertParams: (key: string, value: any) => void; } -// eslint-disable-next-line import/no-default-export -export default function AnomalyAlertComponent({ setAlertParams, alertParams }: Props) { +export function AnomalyAlertComponent({ setAlertParams, alertParams }: Props) { const [severity, setSeverity] = useState(DEFAULT_SEVERITY); const monitorIdStore = useSelector(monitorIdSelector); diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/toggle_alert_flyout_button.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/toggle_alert_flyout_button.tsx index 18514bd92d7a0..067972a452f27 100644 --- a/x-pack/plugins/uptime/public/components/overview/alerts/toggle_alert_flyout_button.tsx +++ b/x-pack/plugins/uptime/public/components/overview/alerts/toggle_alert_flyout_button.tsx @@ -15,7 +15,7 @@ import { import React, { useState } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; import { useKibana } from '../../../../../../../src/plugins/kibana_react/public'; -import { CLIENT_ALERT_TYPES } from '../../../../common/constants'; +import { CLIENT_ALERT_TYPES } from '../../../../common/constants/alerts'; import { ToggleFlyoutTranslations } from './translations'; import { ToggleAlertFlyoutButtonProps } from './alerts_containers'; diff --git a/x-pack/plugins/uptime/public/components/overview/kuery_bar/kuery_bar.tsx b/x-pack/plugins/uptime/public/components/overview/kuery_bar/kuery_bar.tsx index 208269b3b00f5..9e373949aea12 100644 --- a/x-pack/plugins/uptime/public/components/overview/kuery_bar/kuery_bar.tsx +++ b/x-pack/plugins/uptime/public/components/overview/kuery_bar/kuery_bar.tsx @@ -5,22 +5,22 @@ */ import React, { useState, useEffect } from 'react'; -import { uniqueId, startsWith } from 'lodash'; -import { EuiCallOut } from '@elastic/eui'; +import { EuiCallOut, htmlIdGenerator } from '@elastic/eui'; import styled from 'styled-components'; import { FormattedMessage } from '@kbn/i18n/react'; import { Typeahead } from './typeahead'; +import { useKibana } from '../../../../../../../src/plugins/kibana_react/public'; import { useSearchText, useUrlParams } from '../../../hooks'; import { esKuery, IIndexPattern, QuerySuggestion, - DataPublicPluginSetup, } from '../../../../../../../src/plugins/data/public'; import { useIndexPattern } from './use_index_pattern'; const Container = styled.div` margin-bottom: 4px; + position: relative; `; interface State { @@ -35,7 +35,6 @@ function convertKueryToEsQuery(kuery: string, indexPattern: IIndexPattern) { interface Props { 'aria-label': string; - autocomplete: DataPublicPluginSetup['autocomplete']; defaultKuery?: string; 'data-test-subj': string; shouldUpdateUrl?: boolean; @@ -44,7 +43,6 @@ interface Props { export function KueryBar({ 'aria-label': ariaLabel, - autocomplete: autocompleteService, defaultKuery, 'data-test-subj': dataTestSubj, shouldUpdateUrl, @@ -53,6 +51,12 @@ export function KueryBar({ const { loading, index_pattern: indexPattern } = useIndexPattern(); const { updateSearchText } = useSearchText(); + const { + services: { + data: { autocomplete }, + }, + } = useKibana(); + const [state, setState] = useState({ suggestions: [], isLoadingIndexPattern: true, @@ -80,7 +84,7 @@ export function KueryBar({ const indexPatternMissing = loading && !indexPattern; - async function onChange(inputValue: string, selectionStart: number) { + async function onChange(inputValue: string, selectionStart: number | null) { if (!indexPattern) { return; } @@ -89,12 +93,12 @@ export function KueryBar({ setState({ ...state, suggestions: [] }); setSuggestionLimit(15); - const currentRequest = uniqueId(); + const currentRequest = htmlIdGenerator()(); currentRequestCheck = currentRequest; try { const suggestions = ( - (await autocompleteService.getQuerySuggestions({ + (await autocomplete.getQuerySuggestions({ language: 'kuery', indexPatterns: [indexPattern], query: inputValue, @@ -111,8 +115,7 @@ export function KueryBar({ }, ], })) || [] - ).filter((suggestion) => !startsWith(suggestion.text, 'span.')); - + ).filter((suggestion: QuerySuggestion) => !suggestion.text.startsWith('span.')); if (currentRequest !== currentRequestCheck) { return; } @@ -155,8 +158,8 @@ export function KueryBar({ return ( { - this.nodeRef = node; - }; - - onClick = (event) => { - if (this.nodeRef && !this.nodeRef.contains(event.target)) { - this.props.onClickOutside(); - } - }; - - render() { - return ( -
- {this.props.children} -
- ); - } -} - -ClickOutside.propTypes = { - onClickOutside: PropTypes.func.isRequired, -}; diff --git a/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/index.d.ts b/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/index.d.ts deleted file mode 100644 index 751170f3b1cf7..0000000000000 --- a/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/index.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; - -interface TypeaheadProps { - onChange: (inputValue: string, selectionStart: number) => void; - onSubmit: (inputValue: string) => void; - loadMore: () => void; - suggestions: unknown[]; - queryExample: string; - initialValue?: string; - isLoading?: boolean; - disabled?: boolean; -} - -export class Typeahead extends React.Component { - incrementIndex(currentIndex: any): void; - - decrementIndex(currentIndex: any): void; - - onKeyUp(event: any): void; - - onKeyDown(event: any): void; - - selectSuggestion(suggestion: any): void; - - onClickOutside(): void; - - onChangeInputValue(event: any): void; - - onClickInput(event: any): void; - - onClickSuggestion(suggestion: any): void; - - onMouseEnterSuggestion(index: any): void; - - onSubmit(): void; - - render(): any; - - loadMore(): void; -} diff --git a/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/index.js b/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/index.js deleted file mode 100644 index 17141235d8bf2..0000000000000 --- a/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/index.js +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { Component } from 'react'; -import PropTypes from 'prop-types'; -import Suggestions from './suggestions'; -import ClickOutside from './click_outside'; -import { EuiFieldSearch, EuiProgress } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; - -const KEY_CODES = { - LEFT: 37, - UP: 38, - RIGHT: 39, - DOWN: 40, - ENTER: 13, - ESC: 27, - TAB: 9, -}; - -export class Typeahead extends Component { - state = { - isSuggestionsVisible: false, - index: null, - value: '', - inputIsPristine: true, - lastSubmitted: '', - selected: null, - }; - - static getDerivedStateFromProps(props, state) { - if (state.inputIsPristine && props.initialValue) { - return { - value: props.initialValue, - }; - } - - return null; - } - - incrementIndex = (currentIndex) => { - let nextIndex = currentIndex + 1; - if (currentIndex === null || nextIndex >= this.props.suggestions.length) { - nextIndex = 0; - } - this.setState({ index: nextIndex }); - }; - - decrementIndex = (currentIndex) => { - let previousIndex = currentIndex - 1; - if (previousIndex < 0) { - previousIndex = null; - } - this.setState({ index: previousIndex }); - }; - - onKeyUp = (event) => { - const { selectionStart } = event.target; - const { value } = this.state; - switch (event.keyCode) { - case KEY_CODES.LEFT: - this.setState({ isSuggestionsVisible: true }); - this.props.onChange(value, selectionStart); - break; - case KEY_CODES.RIGHT: - this.setState({ isSuggestionsVisible: true }); - this.props.onChange(value, selectionStart); - break; - } - }; - - onKeyDown = (event) => { - const { isSuggestionsVisible, index, value } = this.state; - switch (event.keyCode) { - case KEY_CODES.DOWN: - event.preventDefault(); - if (isSuggestionsVisible) { - this.incrementIndex(index); - } else { - this.setState({ isSuggestionsVisible: true, index: 0 }); - } - break; - case KEY_CODES.UP: - event.preventDefault(); - if (isSuggestionsVisible) { - this.decrementIndex(index); - } - break; - case KEY_CODES.ENTER: - event.preventDefault(); - if (isSuggestionsVisible && this.props.suggestions[index]) { - this.selectSuggestion(this.props.suggestions[index]); - } else { - this.setState({ isSuggestionsVisible: false }); - this.props.onSubmit(value); - } - break; - case KEY_CODES.ESC: - event.preventDefault(); - this.setState({ isSuggestionsVisible: false }); - break; - case KEY_CODES.TAB: - this.setState({ isSuggestionsVisible: false }); - break; - } - }; - - selectSuggestion = (suggestion) => { - const nextInputValue = - this.state.value.substr(0, suggestion.start) + - suggestion.text + - this.state.value.substr(suggestion.end); - - this.setState({ value: nextInputValue, index: null, selected: suggestion }); - this.props.onChange(nextInputValue, nextInputValue.length); - }; - - onClickOutside = () => { - if (this.state.isSuggestionsVisible) { - this.setState({ isSuggestionsVisible: false }); - this.onSubmit(); - } - }; - - onChangeInputValue = (event) => { - const { value, selectionStart } = event.target; - const hasValue = Boolean(value.trim()); - this.setState({ - value, - inputIsPristine: false, - isSuggestionsVisible: hasValue, - index: null, - }); - - if (!hasValue) { - this.props.onSubmit(value); - } - this.props.onChange(value, selectionStart); - }; - - onClickInput = (event) => { - const { selectionStart } = event.target; - this.props.onChange(this.state.value, selectionStart); - }; - - onClickSuggestion = (suggestion) => { - this.selectSuggestion(suggestion); - this.inputRef.focus(); - }; - - onMouseEnterSuggestion = (index) => { - this.setState({ index }); - }; - - onSubmit = () => { - const { value, lastSubmitted, selected } = this.state; - - if ( - lastSubmitted !== value && - selected && - (selected.type === 'value' || selected.text.trim() === ': *') - ) { - this.props.onSubmit(value); - this.setState({ lastSubmitted: value, selected: null }); - } - }; - - onFocus = () => { - this.setState({ isSuggestionsVisible: true }); - }; - - render() { - return ( - -
- { - if (node) { - this.inputRef = node; - } - }} - disabled={this.props.disabled} - value={this.state.value} - onKeyDown={this.onKeyDown} - onKeyUp={this.onKeyUp} - onFocus={this.onFocus} - onChange={this.onChangeInputValue} - onClick={this.onClickInput} - autoComplete="off" - spellCheck={false} - /> - - {this.props.isLoading && ( - - )} -
- - -
- ); - } -} - -Typeahead.propTypes = { - initialValue: PropTypes.string, - isLoading: PropTypes.bool, - disabled: PropTypes.bool, - onChange: PropTypes.func.isRequired, - onSubmit: PropTypes.func.isRequired, - loadMore: PropTypes.func.isRequired, - suggestions: PropTypes.array.isRequired, - queryExample: PropTypes.string.isRequired, -}; - -Typeahead.defaultProps = { - isLoading: false, - disabled: false, - suggestions: [], -}; diff --git a/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/index.ts b/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/index.ts new file mode 100644 index 0000000000000..6bf1226131e29 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/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 { Typeahead } from './typehead'; diff --git a/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/suggestion.js b/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/suggestion.js deleted file mode 100644 index 615a444d23e73..0000000000000 --- a/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/suggestion.js +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import PropTypes from 'prop-types'; -import styled from 'styled-components'; -import { EuiIcon } from '@elastic/eui'; -import { - fontFamilyCode, - px, - units, - fontSizes, - unit, - // eslint-disable-next-line @kbn/eslint/no-restricted-paths -} from '../../../../../../apm/public/style/variables'; -import { tint } from 'polished'; -import theme from '@elastic/eui/dist/eui_theme_light.json'; - -function getIconColor(type) { - switch (type) { - case 'field': - return theme.euiColorVis7; - case 'value': - return theme.euiColorVis0; - case 'operator': - return theme.euiColorVis1; - case 'conjunction': - return theme.euiColorVis3; - case 'recentSearch': - return theme.euiColorMediumShade; - } -} - -const Description = styled.div` - color: ${theme.euiColorDarkShade}; - - p { - display: inline; - - span { - font-family: ${fontFamilyCode}; - color: ${theme.euiColorFullShade}; - padding: 0 ${px(units.quarter)}; - display: inline-block; - } - } -`; - -const ListItem = styled.button` - width: inherit; - font-size: ${fontSizes.small}; - height: ${px(units.double)}; - align-items: center; - display: flex; - background: ${(props) => (props.selected ? theme.euiColorLightestShade : 'initial')}; - cursor: pointer; - border-radius: ${px(units.quarter)}; - - ${Description} { - p span { - background: ${(props) => - props.selected ? theme.euiColorEmptyShade : theme.euiColorLightestShade}; - } - @media only screen and (max-width: ${theme.euiBreakpoints.s}) { - margin-left: auto; - text-align: end; - } - } -`; - -const Icon = styled.div` - flex: 0 0 ${px(units.double)}; - background: ${(props) => tint(0.1, getIconColor(props.type))}; - color: ${(props) => getIconColor(props.type)}; - width: 100%; - height: 100%; - text-align: center; - line-height: ${px(units.double)}; -`; - -const TextValue = styled.div` - text-align: left; - flex: 0 0 ${px(unit * 12)}; - color: ${theme.euiColorDarkestShade}; - padding: 0 ${px(units.half)}; - - @media only screen and (max-width: ${theme.euiBreakpoints.s}) { - flex: 0 0 ${px(unit * 8)}; - } - @media only screen and (min-width: 1300px) { - flex: 0 0 ${px(unit * 16)}; - } -`; - -function getEuiIconType(type) { - switch (type) { - case 'field': - return 'kqlField'; - case 'value': - return 'kqlValue'; - case 'recentSearch': - return 'search'; - case 'conjunction': - return 'kqlSelector'; - case 'operator': - return 'kqlOperand'; - default: - throw new Error('Unknown type', type); - } -} - -function Suggestion(props) { - return ( - props.onClick(props.suggestion)} - onMouseEnter={props.onMouseEnter} - > - - - - {props.suggestion.text} - {props.suggestion.description} - - ); -} - -Suggestion.propTypes = { - onClick: PropTypes.func.isRequired, - onMouseEnter: PropTypes.func.isRequired, - selected: PropTypes.bool, - suggestion: PropTypes.object.isRequired, - innerRef: PropTypes.func.isRequired, -}; - -export default Suggestion; diff --git a/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/suggestion.tsx b/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/suggestion.tsx new file mode 100644 index 0000000000000..1dc89d2795309 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/suggestion.tsx @@ -0,0 +1,89 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useRef, useEffect, RefObject } from 'react'; +import styled from 'styled-components'; +import { EuiSuggestItem } from '@elastic/eui'; +import theme from '@elastic/eui/dist/eui_theme_light.json'; + +import { QuerySuggestion } from '../../../../../../../../src/plugins/data/public'; + +const SuggestionItem = styled.div<{ selected: boolean }>` + background: ${(props) => (props.selected ? theme.euiColorLightestShade : 'initial')}; +`; + +function getIconColor(type: string) { + switch (type) { + case 'field': + return 'tint5'; + case 'value': + return 'tint0'; + case 'operator': + return 'tint1'; + case 'conjunction': + return 'tint3'; + case 'recentSearch': + return 'tint10'; + default: + return 'tint5'; + } +} + +function getEuiIconType(type: string) { + switch (type) { + case 'field': + return 'kqlField'; + case 'value': + return 'kqlValue'; + case 'recentSearch': + return 'search'; + case 'conjunction': + return 'kqlSelector'; + case 'operator': + return 'kqlOperand'; + default: + throw new Error(`Unknown type ${type}`); + } +} + +interface SuggestionProps { + onClick: (sug: QuerySuggestion) => void; + onMouseEnter: () => void; + selected: boolean; + suggestion: QuerySuggestion; + innerRef: (node: any) => void; +} + +export const Suggestion: React.FC = ({ + innerRef, + selected, + suggestion, + onClick, + onMouseEnter, +}) => { + const childNode: RefObject = useRef(null); + + useEffect(() => { + if (childNode.current) { + innerRef(childNode.current); + } + + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [childNode]); + + return ( + + onClick(suggestion)} + onMouseEnter={onMouseEnter} + // @ts-ignore + description={suggestion.description} + /> + + ); +}; diff --git a/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/suggestions.js b/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/suggestions.js deleted file mode 100644 index 8d614d7ea1aec..0000000000000 --- a/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/suggestions.js +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { Component } from 'react'; -import PropTypes from 'prop-types'; -import styled from 'styled-components'; -import { isEmpty } from 'lodash'; -import Suggestion from './suggestion'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { units, px, unit } from '../../../../../../apm/public/style/variables'; -import { tint } from 'polished'; -import theme from '@elastic/eui/dist/eui_theme_light.json'; - -const List = styled.ul` - width: 100%; - border: 1px solid ${theme.euiColorLightShade}; - border-radius: ${px(units.quarter)}; - box-shadow: 0px ${px(units.quarter)} ${px(units.double)} ${tint(0.1, theme.euiColorFullShade)}; - position: absolute; - background: #fff; - z-index: 10; - left: 0; - max-height: ${px(unit * 20)}; - overflow: scroll; -`; - -class Suggestions extends Component { - childNodes = []; - - scrollIntoView = () => { - const parent = this.parentNode; - const child = this.childNodes[this.props.index]; - - if (this.props.index == null || !parent || !child) { - return; - } - - const scrollTop = Math.max( - Math.min(parent.scrollTop, child.offsetTop), - child.offsetTop + child.offsetHeight - parent.offsetHeight - ); - - parent.scrollTop = scrollTop; - }; - - handleScroll = () => { - const parent = this.parentNode; - - if (!this.props.loadMore || !parent) { - return; - } - - const position = parent.scrollTop + parent.offsetHeight; - const height = parent.scrollHeight; - const remaining = height - position; - const margin = 50; - - if (!height || !position) { - return; - } - if (remaining <= margin) { - this.props.loadMore(); - } - }; - - componentDidUpdate(prevProps) { - if (prevProps.index !== this.props.index) { - this.scrollIntoView(); - } - } - - render() { - if (!this.props.show || isEmpty(this.props.suggestions)) { - return null; - } - - const suggestions = this.props.suggestions.map((suggestion, index) => { - const key = suggestion + '_' + index; - return ( - (this.childNodes[index] = node)} - selected={index === this.props.index} - suggestion={suggestion} - onClick={this.props.onClick} - onMouseEnter={() => this.props.onMouseEnter(index)} - key={key} - /> - ); - }); - - return ( - (this.parentNode = node)} onScroll={this.handleScroll}> - {suggestions} - - ); - } -} - -Suggestions.propTypes = { - index: PropTypes.number, - onClick: PropTypes.func.isRequired, - onMouseEnter: PropTypes.func.isRequired, - show: PropTypes.bool, - suggestions: PropTypes.array.isRequired, - loadMore: PropTypes.func.isRequired, -}; - -export default Suggestions; diff --git a/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/suggestions.tsx b/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/suggestions.tsx new file mode 100644 index 0000000000000..dcd8df1ba18ef --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/suggestions.tsx @@ -0,0 +1,116 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useRef, useState, useEffect } from 'react'; +import styled from 'styled-components'; +import { isEmpty } from 'lodash'; +import { tint } from 'polished'; +import theme from '@elastic/eui/dist/eui_theme_light.json'; +import { Suggestion } from './suggestion'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { units, px, unit } from '../../../../../../apm/public/style/variables'; +import { QuerySuggestion } from '../../../../../../../../src/plugins/data/public'; + +const List = styled.ul` + width: 100%; + border: 1px solid ${theme.euiColorLightShade}; + border-radius: ${px(units.quarter)}; + box-shadow: 0px ${px(units.quarter)} ${px(units.double)} ${tint(0.1, theme.euiColorFullShade)}; + background: #fff; + z-index: 10; + max-height: ${px(unit * 20)}; + overflow: scroll; + position: absolute; +`; + +interface SuggestionsProps { + index: number; + onClick: (sug: QuerySuggestion) => void; + onMouseEnter: (index: number) => void; + show?: boolean; + suggestions: QuerySuggestion[]; + loadMore: () => void; +} + +export const Suggestions: React.FC = ({ + show, + index, + onClick, + suggestions, + onMouseEnter, + loadMore, +}) => { + const [childNodes, setChildNodes] = useState([]); + + const parentNode = useRef(null); + + useEffect(() => { + const scrollIntoView = () => { + const parent = parentNode.current; + const child = childNodes[index]; + + if (index == null || !parent || !child) { + return; + } + + const scrollTop = Math.max( + Math.min(parent.scrollTop, child.offsetTop), + child.offsetTop + child.offsetHeight - parent.offsetHeight + ); + + parent.scrollTop = scrollTop; + }; + scrollIntoView(); + }, [index, childNodes]); + + if (!show || isEmpty(suggestions)) { + return null; + } + + const handleScroll = () => { + const parent = parentNode.current; + + if (!loadMore || !parent) { + return; + } + + const position = parent.scrollTop + parent.offsetHeight; + const height = parent.scrollHeight; + const remaining = height - position; + const margin = 50; + + if (!height || !position) { + return; + } + if (remaining <= margin) { + loadMore(); + } + }; + + const suggestionsNodes = suggestions.map((suggestion, currIndex) => { + const key = suggestion + '_' + currIndex; + return ( + { + const nodes = childNodes; + nodes[currIndex] = node; + setChildNodes([...nodes]); + }} + selected={currIndex === index} + suggestion={suggestion} + onClick={onClick} + onMouseEnter={() => onMouseEnter(currIndex)} + key={key} + /> + ); + }); + + return ( + + {suggestionsNodes} + + ); +}; diff --git a/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/typehead.tsx b/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/typehead.tsx new file mode 100644 index 0000000000000..5582818b6f09b --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/kuery_bar/typeahead/typehead.tsx @@ -0,0 +1,318 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under 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, { KeyboardEvent, ChangeEvent, MouseEvent, useState, useRef, useEffect } from 'react'; +import { i18n } from '@kbn/i18n'; +import { EuiFieldSearch, EuiProgress, EuiOutsideClickDetector } from '@elastic/eui'; +import { Suggestions } from './suggestions'; +import { QuerySuggestion } from '../../../../../../../../src/plugins/data/public'; + +const KEY_CODES = { + LEFT: 37, + UP: 38, + RIGHT: 39, + DOWN: 40, + ENTER: 13, + ESC: 27, + TAB: 9, +}; + +interface TypeaheadState { + isSuggestionsVisible: boolean; + index: number | null; + value: string; + inputIsPristine: boolean; + lastSubmitted: string; + selected: QuerySuggestion | null; +} + +interface TypeaheadProps { + onChange: (inputValue: string, selectionStart: number | null) => void; + onSubmit: (inputValue: string) => void; + suggestions: QuerySuggestion[]; + queryExample: string; + initialValue?: string; + isLoading?: boolean; + disabled?: boolean; + dataTestSubj: string; + ariaLabel: string; + loadMore: () => void; +} + +export const Typeahead: React.FC = ({ + initialValue, + suggestions, + onChange, + onSubmit, + dataTestSubj, + ariaLabel, + disabled, + isLoading, + loadMore, +}) => { + const [state, setState] = useState({ + isSuggestionsVisible: false, + index: null, + value: '', + inputIsPristine: true, + lastSubmitted: '', + selected: null, + }); + + const inputRef = useRef(); + + useEffect(() => { + if (state.inputIsPristine && initialValue) { + setState((prevState) => ({ + ...prevState, + value: initialValue, + })); + } + + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [initialValue]); + + const incrementIndex = (currentIndex: number) => { + let nextIndex = currentIndex + 1; + if (currentIndex === null || nextIndex >= suggestions.length) { + nextIndex = 0; + } + + setState((prevState) => ({ + ...prevState, + index: nextIndex, + })); + }; + + const decrementIndex = (currentIndex: number) => { + let previousIndex: number | null = currentIndex - 1; + if (previousIndex < 0) { + previousIndex = null; + } + + setState((prevState) => ({ + ...prevState, + index: previousIndex, + })); + }; + + const onKeyUp = (event: KeyboardEvent & ChangeEvent) => { + const { selectionStart } = event.target; + const { value } = state; + switch (event.keyCode) { + case KEY_CODES.LEFT: + setState((prevState) => ({ + ...prevState, + isSuggestionsVisible: true, + })); + onChange(value, selectionStart); + break; + case KEY_CODES.RIGHT: + setState((prevState) => ({ + ...prevState, + isSuggestionsVisible: true, + })); + onChange(value, selectionStart); + break; + } + }; + + const onKeyDown = (event: KeyboardEvent) => { + const { isSuggestionsVisible, index, value } = state; + switch (event.keyCode) { + case KEY_CODES.DOWN: + event.preventDefault(); + if (isSuggestionsVisible) { + incrementIndex(index!); + } else { + setState((prevState) => ({ + ...prevState, + isSuggestionsVisible: true, + index: 0, + })); + } + break; + case KEY_CODES.UP: + event.preventDefault(); + if (isSuggestionsVisible) { + decrementIndex(index!); + } + break; + case KEY_CODES.ENTER: + event.preventDefault(); + if (isSuggestionsVisible && suggestions[index!]) { + selectSuggestion(suggestions[index!]); + } else { + setState((prevState) => ({ + ...prevState, + isSuggestionsVisible: false, + })); + + onSubmit(value); + } + break; + case KEY_CODES.ESC: + event.preventDefault(); + + setState((prevState) => ({ + ...prevState, + isSuggestionsVisible: false, + })); + + break; + case KEY_CODES.TAB: + setState((prevState) => ({ + ...prevState, + isSuggestionsVisible: false, + })); + break; + } + }; + + const selectSuggestion = (suggestion: QuerySuggestion) => { + const nextInputValue = + state.value.substr(0, suggestion.start) + + suggestion.text + + state.value.substr(suggestion.end); + + setState((prevState) => ({ + ...prevState, + value: nextInputValue, + index: null, + selected: suggestion, + })); + + onChange(nextInputValue, nextInputValue.length); + }; + + const onClickOutside = () => { + if (state.isSuggestionsVisible) { + setState((prevState) => ({ + ...prevState, + isSuggestionsVisible: false, + })); + + onSuggestionSubmit(); + } + }; + + const onChangeInputValue = (event: ChangeEvent) => { + const { value, selectionStart } = event.target; + const hasValue = Boolean(value.trim()); + + setState((prevState) => ({ + ...prevState, + value, + inputIsPristine: false, + isSuggestionsVisible: hasValue, + index: null, + })); + + if (!hasValue) { + onSubmit(value); + } + onChange(value, selectionStart!); + }; + + const onClickInput = (event: MouseEvent & ChangeEvent) => { + event.stopPropagation(); + const { selectionStart } = event.target; + onChange(state.value, selectionStart!); + }; + + const onFocus = () => { + setState((prevState) => ({ + ...prevState, + isSuggestionsVisible: true, + })); + }; + + const onClickSuggestion = (suggestion: QuerySuggestion) => { + selectSuggestion(suggestion); + if (inputRef.current) inputRef.current.focus(); + }; + + const onMouseEnterSuggestion = (index: number) => { + setState({ ...state, index }); + + setState((prevState) => ({ + ...prevState, + index, + })); + }; + + const onSuggestionSubmit = () => { + const { value, lastSubmitted, selected } = state; + + if ( + lastSubmitted !== value && + selected && + (selected.type === 'value' || selected.text.trim() === ': *') + ) { + onSubmit(value); + + setState((prevState) => ({ + ...prevState, + lastSubmitted: value, + selected: null, + })); + } + }; + + return ( + + +
+ { + if (node) { + inputRef.current = node; + } + }} + disabled={disabled} + value={state.value} + onKeyDown={onKeyDown} + onKeyUp={onKeyUp} + onFocus={onFocus} + onChange={onChangeInputValue} + onClick={onClickInput} + autoComplete="off" + spellCheck={false} + /> + + {isLoading && ( + + )} +
+ + +
+
+ ); +}; 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 b6ce1eceb62a7..42ac821c10c7a 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 @@ -813,7 +813,13 @@ exports[`MonitorList component renders the monitor list 1`] = ` } .c1 { - margin-left: auto; + position: absolute; + right: 16px; + top: 16px; +} + +.c0 { + position: relative; } .c4 { @@ -828,26 +834,6 @@ exports[`MonitorList component renders the monitor list 1`] = ` } } -@media only screen and (max-width:768px) { - .c0.c0 > :first-child { - -webkit-flex-basis: 40% !important; - -ms-flex-preferred-size: 40% !important; - flex-basis: 40% !important; - } - - .c0.c0 > :nth-child(2) { - -webkit-order: 3; - -ms-flex-order: 3; - order: 3; - } - - .c0.c0 > :nth-child(3) { - -webkit-flex-basis: 60% !important; - -ms-flex-preferred-size: 60% !important; - flex-basis: 60% !important; - } -} -
@@ -936,20 +922,13 @@ exports[`MonitorList component renders the monitor list 1`] = `
- + Certificates status +
{ const popoverId = `${summary.monitor_id}_popover`; - const monitorUrl: string | undefined = get(summary, 'state.url.full', undefined); + const monitorUrl: string | undefined = summary?.state?.url?.full; + const isPopoverOpen: boolean = !!popoverState && popoverState.open && popoverState.id === popoverId; return ( diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_drawer/actions_popover/integration_group.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_drawer/actions_popover/integration_group.tsx index 38aa9287b0c47..ff3b5d67375fe 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_drawer/actions_popover/integration_group.tsx +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_drawer/actions_popover/integration_group.tsx @@ -27,9 +27,12 @@ interface IntegrationGroupProps { export const extractSummaryValues = (summary: Pick) => { const domain = summary.state.url?.domain ?? ''; - const podUid = summary.state.summaryPings?.[0]?.kubernetes?.pod?.uid ?? undefined; - const containerId = summary.state.summaryPings?.[0]?.container?.id ?? undefined; - const ip = summary.state.summaryPings?.[0]?.monitor.ip ?? undefined; + + const firstCheck = summary.state.summaryPings?.[0]; + + const podUid = firstCheck?.kubernetes?.pod?.uid ?? undefined; + const containerId = firstCheck?.container?.id ?? undefined; + const ip = firstCheck?.monitor.ip ?? undefined; return { domain, diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_drawer/monitor_status_list.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_drawer/monitor_status_list.tsx index 334de6e376074..96536a357a450 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_drawer/monitor_status_list.tsx +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_drawer/monitor_status_list.tsx @@ -5,7 +5,6 @@ */ import React from 'react'; -import { upperFirst } from 'lodash'; import { EuiCallOut, EuiSpacer } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { LocationLink } from '../../../common/location_link'; @@ -29,9 +28,9 @@ export const MonitorStatusList = ({ summaryPings }: MonitorStatusListProps) => { const location = ping.observer?.geo?.name ?? UNNAMED_LOCATION; if (ping.monitor.status === STATUS.UP) { - upChecks.add(upperFirst(location)); + upChecks.add(location); } else if (ping.monitor.status === STATUS.DOWN) { - downChecks.add(upperFirst(location)); + downChecks.add(location); } }); diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_header.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_header.tsx index c37cf6a158e46..5f760030f37a3 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_header.tsx +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_header.tsx @@ -12,24 +12,14 @@ import styled from 'styled-components'; import { StatusFilter } from './status_filter'; import { CERTIFICATES_ROUTE } from '../../../../common/constants'; -const TitleStyle = styled(EuiTitle)` - margin-left: auto; +const LinkStyle = styled(Link)` + position: absolute; + right: 16px; + top: 16px; `; const FlexGroupContainer = styled(EuiFlexGroup)` - && { - @media only screen and (max-width: 768px) { - > :first-child { - flex-basis: 40% !important; - } - > :nth-child(2) { - order: 3; - } - > :nth-child(3) { - flex-basis: 60% !important; - } - } - } + position: relative; `; export const MonitorListHeader: React.FC = () => { @@ -48,18 +38,12 @@ export const MonitorListHeader: React.FC = () => { - - -
- - - -
-
-
+ + + ); }; diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_status_column.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_status_column.tsx index 68ddf512e4d3c..7140211d18807 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_status_column.tsx +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_status_column.tsx @@ -7,7 +7,6 @@ import React from 'react'; import moment from 'moment'; import { i18n } from '@kbn/i18n'; -import { upperFirst } from 'lodash'; import styled from 'styled-components'; import { EuiHealth, EuiFlexGroup, EuiFlexItem, EuiText, EuiToolTip } from '@elastic/eui'; import { parseTimestamp } from './parse_timestamp'; @@ -83,9 +82,9 @@ export const getLocationStatus = (summaryPings: Ping[], status: string) => { const location = summaryPing?.observer?.geo?.name ?? UNNAMED_LOCATION; if (summaryPing.monitor.status === STATUS.UP) { - upPings.add(upperFirst(location)); + upPings.add(location); } else if (summaryPing.monitor.status === STATUS.DOWN) { - downPings.add(upperFirst(location)); + downPings.add(location); } }); diff --git a/x-pack/plugins/uptime/public/contexts/uptime_settings_context.tsx b/x-pack/plugins/uptime/public/contexts/uptime_settings_context.tsx index 142c6e17c5fd9..4c08e76a11aae 100644 --- a/x-pack/plugins/uptime/public/contexts/uptime_settings_context.tsx +++ b/x-pack/plugins/uptime/public/contexts/uptime_settings_context.tsx @@ -5,7 +5,7 @@ */ import React, { createContext, useMemo } from 'react'; -import { UptimeAppProps } from '../uptime_app'; +import { UptimeAppProps } from '../apps/uptime_app'; import { CLIENT_DEFAULTS, CONTEXT_DEFAULTS } from '../../common/constants'; import { CommonlyUsedRange } from '../components/common/uptime_date_picker'; import { useGetUrlParams } from '../hooks'; diff --git a/x-pack/plugins/uptime/public/contexts/uptime_theme_context.tsx b/x-pack/plugins/uptime/public/contexts/uptime_theme_context.tsx index ca2fb50cdbc67..51e8bcaed986f 100644 --- a/x-pack/plugins/uptime/public/contexts/uptime_theme_context.tsx +++ b/x-pack/plugins/uptime/public/contexts/uptime_theme_context.tsx @@ -9,7 +9,7 @@ import React, { createContext, useMemo } from 'react'; import euiDarkVars from '@elastic/eui/dist/eui_theme_dark.json'; import { EUI_CHARTS_THEME_DARK, EUI_CHARTS_THEME_LIGHT } from '@elastic/eui/dist/eui_charts_theme'; import { DARK_THEME, LIGHT_THEME, PartialTheme, Theme } from '@elastic/charts'; -import { UptimeAppColors } from '../uptime_app'; +import { UptimeAppColors } from '../apps/uptime_app'; export interface UptimeThemeContextValues { colors: UptimeAppColors; diff --git a/x-pack/plugins/uptime/public/index.ts b/x-pack/plugins/uptime/public/index.ts index 48cf2c90ad07b..cd6efa9016830 100644 --- a/x-pack/plugins/uptime/public/index.ts +++ b/x-pack/plugins/uptime/public/index.ts @@ -5,7 +5,7 @@ */ import { PluginInitializerContext } from 'kibana/public'; -import { UptimePlugin } from './apps'; +import { UptimePlugin } from './apps/plugin'; export const plugin = (initializerContext: PluginInitializerContext) => new UptimePlugin(initializerContext); diff --git a/x-pack/plugins/uptime/public/lib/alert_types/__tests__/monitor_status.test.ts b/x-pack/plugins/uptime/public/lib/alert_types/__tests__/monitor_status.test.ts index cfcb414f4815d..e999768d4e55d 100644 --- a/x-pack/plugins/uptime/public/lib/alert_types/__tests__/monitor_status.test.ts +++ b/x-pack/plugins/uptime/public/lib/alert_types/__tests__/monitor_status.test.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { validate, initMonitorStatusAlertType } from '../monitor_status'; +import { initMonitorStatusAlertType } from '../monitor_status'; +import { validateMonitorStatusParams as validate } from '../lazy_wrapper/validate_monitor_status'; describe('monitor status alert type', () => { describe('validate', () => { @@ -206,19 +207,11 @@ describe('monitor status alert type', () => { ", "iconClass": "uptimeApp", "id": "xpack.uptime.alerts.monitorStatus", - "name": - - , + "name": , "requiresAppContext": false, "validate": [Function], } diff --git a/x-pack/plugins/uptime/public/lib/alert_types/duration_anomaly.tsx b/x-pack/plugins/uptime/public/lib/alert_types/duration_anomaly.tsx index f0eb305461582..c1f802c2d0c91 100644 --- a/x-pack/plugins/uptime/public/lib/alert_types/duration_anomaly.tsx +++ b/x-pack/plugins/uptime/public/lib/alert_types/duration_anomaly.tsx @@ -5,30 +5,22 @@ */ import React from 'react'; -import { Provider as ReduxProvider } from 'react-redux'; import { AlertTypeModel } from '../../../../triggers_actions_ui/public'; -import { CLIENT_ALERT_TYPES } from '../../../common/constants'; +import { CLIENT_ALERT_TYPES } from '../../../common/constants/alerts'; import { DurationAnomalyTranslations } from './translations'; import { AlertTypeInitializer } from '.'; -import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public'; -import { store } from '../../state'; const { name, defaultActionMessage } = DurationAnomalyTranslations; -const AnomalyAlertExpression = React.lazy(() => - import('../../components/overview/alerts/anomaly_alert/anomaly_alert') -); +const DurationAnomalyAlert = React.lazy(() => import('./lazy_wrapper/duration_anomaly')); + export const initDurationAnomalyAlertType: AlertTypeInitializer = ({ core, plugins, }): AlertTypeModel => ({ id: CLIENT_ALERT_TYPES.DURATION_ANOMALY, iconClass: 'uptimeApp', - alertParamsExpression: (params: any) => ( - - - - - + alertParamsExpression: (params: unknown) => ( + ), name, validate: () => ({ errors: {} }), diff --git a/x-pack/plugins/uptime/public/lib/alert_types/lazy_wrapper/duration_anomaly.tsx b/x-pack/plugins/uptime/public/lib/alert_types/lazy_wrapper/duration_anomaly.tsx new file mode 100644 index 0000000000000..60f2d2e803b7b --- /dev/null +++ b/x-pack/plugins/uptime/public/lib/alert_types/lazy_wrapper/duration_anomaly.tsx @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { Provider as ReduxProvider } from 'react-redux'; +import { CoreStart } from 'kibana/public'; +import { store } from '../../../state'; +import { AnomalyAlertComponent } from '../../../components/overview/alerts/anomaly_alert/anomaly_alert'; +import { KibanaContextProvider } from '../../../../../../../src/plugins/kibana_react/public'; +import { ClientPluginsStart } from '../../../apps/plugin'; +import { kibanaService } from '../../../state/kibana_service'; + +interface Props { + core: CoreStart; + plugins: ClientPluginsStart; + params: any; +} + +// eslint-disable-next-line import/no-default-export +export default function DurationAnomalyAlert({ core, plugins, params }: Props) { + kibanaService.core = core; + return ( + + + + + + ); +} diff --git a/x-pack/plugins/uptime/public/lib/alert_types/lazy_wrapper/monitor_status.tsx b/x-pack/plugins/uptime/public/lib/alert_types/lazy_wrapper/monitor_status.tsx new file mode 100644 index 0000000000000..f6b10d0fbf968 --- /dev/null +++ b/x-pack/plugins/uptime/public/lib/alert_types/lazy_wrapper/monitor_status.tsx @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { Provider as ReduxProvider } from 'react-redux'; +import { CoreStart } from 'kibana/public'; +import { store } from '../../../state'; +import { KibanaContextProvider } from '../../../../../../../src/plugins/kibana_react/public'; +import { ClientPluginsStart } from '../../../apps/plugin'; +import { AlertMonitorStatus } from '../../../components/overview/alerts/alerts_containers'; +import { kibanaService } from '../../../state/kibana_service'; + +interface Props { + core: CoreStart; + plugins: ClientPluginsStart; + params: any; +} + +// eslint-disable-next-line import/no-default-export +export default function MonitorStatusAlert({ core, plugins, params }: Props) { + kibanaService.core = core; + return ( + + + + + + ); +} diff --git a/x-pack/plugins/uptime/public/lib/alert_types/lazy_wrapper/tls_alert.tsx b/x-pack/plugins/uptime/public/lib/alert_types/lazy_wrapper/tls_alert.tsx new file mode 100644 index 0000000000000..413734b63ced5 --- /dev/null +++ b/x-pack/plugins/uptime/public/lib/alert_types/lazy_wrapper/tls_alert.tsx @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { Provider as ReduxProvider } from 'react-redux'; +import { CoreStart } from 'kibana/public'; +import { store } from '../../../state'; +import { KibanaContextProvider } from '../../../../../../../src/plugins/kibana_react/public'; +import { ClientPluginsStart } from '../../../apps/plugin'; +import { AlertTls } from '../../../components/overview/alerts/alerts_containers/alert_tls'; +import { kibanaService } from '../../../state/kibana_service'; + +interface Props { + core: CoreStart; + plugins: ClientPluginsStart; + params: any; +} + +// eslint-disable-next-line import/no-default-export +export default function TLSAlert({ core, plugins, params: _params }: Props) { + kibanaService.core = core; + return ( + + + + + + ); +} diff --git a/x-pack/plugins/uptime/public/lib/alert_types/lazy_wrapper/validate_monitor_status.ts b/x-pack/plugins/uptime/public/lib/alert_types/lazy_wrapper/validate_monitor_status.ts new file mode 100644 index 0000000000000..709669c24ed0a --- /dev/null +++ b/x-pack/plugins/uptime/public/lib/alert_types/lazy_wrapper/validate_monitor_status.ts @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { PathReporter } from 'io-ts/lib/PathReporter'; +import { isRight } from 'fp-ts/lib/Either'; +import { + AtomicStatusCheckParamsType, + MonitorAvailabilityType, + StatusCheckParamsType, +} from '../../../../common/runtime_types/alerts'; +import { ValidationResult } from '../../../../../triggers_actions_ui/public'; + +export function validateMonitorStatusParams(alertParams: any): ValidationResult { + const errors: Record = {}; + const decoded = AtomicStatusCheckParamsType.decode(alertParams); + const oldDecoded = StatusCheckParamsType.decode(alertParams); + const availabilityDecoded = MonitorAvailabilityType.decode(alertParams); + + if (!isRight(decoded) && !isRight(oldDecoded) && !isRight(availabilityDecoded)) { + return { + errors: { + typeCheckFailure: 'Provided parameters do not conform to the expected type.', + typeCheckParsingMessage: PathReporter.report(decoded), + }, + }; + } + + if ( + !(alertParams.shouldCheckAvailability ?? false) && + !(alertParams.shouldCheckStatus ?? false) + ) { + return { + errors: { + noAlertSelected: 'Alert must check for monitor status or monitor availability.', + }, + }; + } + + if (isRight(decoded) && decoded.right.shouldCheckStatus) { + const { numTimes, timerangeCount } = decoded.right; + if (numTimes < 1) { + errors.invalidNumTimes = 'Number of alert check down times must be an integer greater than 0'; + } + if (isNaN(timerangeCount)) { + errors.timeRangeStartValueNaN = 'Specified time range value must be a number'; + } + if (timerangeCount <= 0) { + errors.invalidTimeRangeValue = 'Time range value must be greater than 0'; + } + } + + return { errors }; +} diff --git a/x-pack/plugins/uptime/public/lib/alert_types/monitor_status.tsx b/x-pack/plugins/uptime/public/lib/alert_types/monitor_status.tsx index cb24df2357d01..e4da3eb9ef7ae 100644 --- a/x-pack/plugins/uptime/public/lib/alert_types/monitor_status.tsx +++ b/x-pack/plugins/uptime/public/lib/alert_types/monitor_status.tsx @@ -4,70 +4,19 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Provider as ReduxProvider } from 'react-redux'; import React from 'react'; -import { isRight } from 'fp-ts/lib/Either'; -import { PathReporter } from 'io-ts/lib/PathReporter'; -import { AlertTypeModel } from '../../../../triggers_actions_ui/public'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { AlertTypeModel, ValidationResult } from '../../../../triggers_actions_ui/public'; import { AlertTypeInitializer } from '.'; -import { - AtomicStatusCheckParamsType, - StatusCheckParamsType, - MonitorAvailabilityType, -} from '../../../common/runtime_types'; -import { MonitorStatusTitle } from './monitor_status_title'; -import { CLIENT_ALERT_TYPES } from '../../../common/constants'; -import { MonitorStatusTranslations } from './translations'; -import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public'; -import { store } from '../../state'; - -export const validate = (alertParams: any) => { - const errors: Record = {}; - const decoded = AtomicStatusCheckParamsType.decode(alertParams); - const oldDecoded = StatusCheckParamsType.decode(alertParams); - const availabilityDecoded = MonitorAvailabilityType.decode(alertParams); - - if (!isRight(decoded) && !isRight(oldDecoded) && !isRight(availabilityDecoded)) { - return { - errors: { - typeCheckFailure: 'Provided parameters do not conform to the expected type.', - typeCheckParsingMessage: PathReporter.report(decoded), - }, - }; - } - - if ( - !(alertParams.shouldCheckAvailability ?? false) && - !(alertParams.shouldCheckStatus ?? false) - ) { - return { - errors: { - noAlertSelected: 'Alert must check for monitor status or monitor availability.', - }, - }; - } - - if (isRight(decoded) && decoded.right.shouldCheckStatus) { - const { numTimes, timerangeCount } = decoded.right; - if (numTimes < 1) { - errors.invalidNumTimes = 'Number of alert check down times must be an integer greater than 0'; - } - if (isNaN(timerangeCount)) { - errors.timeRangeStartValueNaN = 'Specified time range value must be a number'; - } - if (timerangeCount <= 0) { - errors.invalidTimeRangeValue = 'Time range value must be greater than 0'; - } - } - return { errors }; -}; +import { CLIENT_ALERT_TYPES } from '../../../common/constants/alerts'; +import { MonitorStatusTranslations } from './translations'; const { defaultActionMessage } = MonitorStatusTranslations; -const AlertMonitorStatus = React.lazy(() => - import('../../components/overview/alerts/alerts_containers/alert_monitor_status') -); +const MonitorStatusAlert = React.lazy(() => import('./lazy_wrapper/monitor_status')); + +let validateFunc: (alertParams: any) => ValidationResult; export const initMonitorStatusAlertType: AlertTypeInitializer = ({ core, @@ -75,21 +24,26 @@ export const initMonitorStatusAlertType: AlertTypeInitializer = ({ }): AlertTypeModel => ({ id: CLIENT_ALERT_TYPES.MONITOR_STATUS, name: ( - - - + ), iconClass: 'uptimeApp', - alertParamsExpression: (params: any) => { - return ( - - - - - - ); + alertParamsExpression: (params: any) => ( + + ), + validate: (alertParams: any) => { + if (!validateFunc) { + (async function loadValidate() { + const { validateMonitorStatusParams } = await import( + './lazy_wrapper/validate_monitor_status' + ); + validateFunc = validateMonitorStatusParams; + })(); + } + return validateFunc && validateFunc(alertParams); }, - validate, defaultActionMessage, requiresAppContext: false, }); diff --git a/x-pack/plugins/uptime/public/lib/alert_types/monitor_status_title.tsx b/x-pack/plugins/uptime/public/lib/alert_types/monitor_status_title.tsx deleted file mode 100644 index 1e2751a4ac388..0000000000000 --- a/x-pack/plugins/uptime/public/lib/alert_types/monitor_status_title.tsx +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { FormattedMessage } from '@kbn/i18n/react'; - -export const MonitorStatusTitle = () => { - return ( - - ); -}; diff --git a/x-pack/plugins/uptime/public/lib/alert_types/tls.tsx b/x-pack/plugins/uptime/public/lib/alert_types/tls.tsx index c541ea4ae1331..9019fc216192c 100644 --- a/x-pack/plugins/uptime/public/lib/alert_types/tls.tsx +++ b/x-pack/plugins/uptime/public/lib/alert_types/tls.tsx @@ -5,27 +5,18 @@ */ import React from 'react'; -import { Provider as ReduxProvider } from 'react-redux'; import { AlertTypeModel } from '../../../../triggers_actions_ui/public'; -import { CLIENT_ALERT_TYPES } from '../../../common/constants'; +import { CLIENT_ALERT_TYPES } from '../../../common/constants/alerts'; import { TlsTranslations } from './translations'; import { AlertTypeInitializer } from '.'; -import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public'; -import { store } from '../../state'; const { name, defaultActionMessage } = TlsTranslations; -const TlsAlertExpression = React.lazy(() => - import('../../components/overview/alerts/alerts_containers/alert_tls') -); +const TLSAlert = React.lazy(() => import('./lazy_wrapper/tls_alert')); export const initTlsAlertType: AlertTypeInitializer = ({ core, plugins }): AlertTypeModel => ({ id: CLIENT_ALERT_TYPES.TLS, iconClass: 'uptimeApp', - alertParamsExpression: (_params: any) => ( - - - - - + alertParamsExpression: (params: any) => ( + ), name, validate: () => ({ errors: {} }), diff --git a/x-pack/plugins/uptime/public/lib/helper/observability_integration/build_href.ts b/x-pack/plugins/uptime/public/lib/helper/observability_integration/build_href.ts index 94383262b0acd..8c96a469da492 100644 --- a/x-pack/plugins/uptime/public/lib/helper/observability_integration/build_href.ts +++ b/x-pack/plugins/uptime/public/lib/helper/observability_integration/build_href.ts @@ -4,24 +4,23 @@ * you may not use this file except in compliance with the Elastic License. */ -import { get } from 'lodash'; import { Ping } from '../../../../common/runtime_types'; /** * Builds URLs to the designated features by extracting values from the provided * monitor object on a given path. Then returns the result of a provided function * to place the value in its rightful place on the URI string. - * @param checks array of summary checks containing the data to extract - * @param path the location on the object of the desired data + * @param summaryPings array of summary checks containing the data to extract + * @param getData the location on the object of the desired data * @param getHref a function that returns the full URL */ export const buildHref = ( summaryPings: Ping[], - path: string, + getData: (ping: Ping) => string | undefined, getHref: (value: string | string[] | undefined) => string | undefined ): string | undefined => { const queryValue = summaryPings - .map((ping) => get(ping, path, undefined)) + .map((ping) => getData(ping)) .filter((value: string | undefined) => value !== undefined); if (queryValue.length === 0) { return getHref(undefined); diff --git a/x-pack/plugins/uptime/public/lib/helper/observability_integration/get_apm_href.ts b/x-pack/plugins/uptime/public/lib/helper/observability_integration/get_apm_href.ts index 0ff5a8acb3367..a1d69950cb61a 100644 --- a/x-pack/plugins/uptime/public/lib/helper/observability_integration/get_apm_href.ts +++ b/x-pack/plugins/uptime/public/lib/helper/observability_integration/get_apm_href.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { get } from 'lodash'; import { addBasePath } from './add_base_path'; import { MonitorSummary } from '../../../../common/runtime_types'; @@ -17,6 +16,6 @@ export const getApmHref = ( addBasePath( basePath, `/app/apm#/services?kuery=${encodeURI( - `url.domain: "${get(summary, 'state.url.domain')}"` + `url.domain: "${summary?.state?.url?.domain}"` )}&rangeFrom=${dateRangeStart}&rangeTo=${dateRangeEnd}` ); diff --git a/x-pack/plugins/uptime/public/lib/helper/observability_integration/get_infra_href.ts b/x-pack/plugins/uptime/public/lib/helper/observability_integration/get_infra_href.ts index 33d24a0f081b4..c225382350eac 100644 --- a/x-pack/plugins/uptime/public/lib/helper/observability_integration/get_infra_href.ts +++ b/x-pack/plugins/uptime/public/lib/helper/observability_integration/get_infra_href.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { MonitorSummary } from '../../../../common/runtime_types'; +import { MonitorSummary, Ping } from '../../../../common/runtime_types'; import { addBasePath } from './add_base_path'; import { buildHref } from './build_href'; @@ -22,7 +22,7 @@ export const getInfraContainerHref = ( `/app/metrics/link-to/container-detail/${encodeURIComponent(ret)}` ); }; - return buildHref(summary.state.summaryPings || [], 'container.id', getHref); + return buildHref(summary.state.summaryPings || [], (ping: Ping) => ping?.container?.id, getHref); }; export const getInfraKubernetesHref = ( @@ -37,7 +37,11 @@ export const getInfraKubernetesHref = ( return addBasePath(basePath, `/app/metrics/link-to/pod-detail/${encodeURIComponent(ret)}`); }; - return buildHref(summary.state.summaryPings || [], 'kubernetes.pod.uid', getHref); + return buildHref( + summary.state.summaryPings || [], + (ping: Ping) => ping?.kubernetes?.pod?.uid, + getHref + ); }; export const getInfraIpHref = (summary: MonitorSummary, basePath: string) => { @@ -63,5 +67,5 @@ export const getInfraIpHref = (summary: MonitorSummary, basePath: string) => { `/app/metrics/inventory?waffleFilter=(expression:'${encodeURIComponent(ips)}',kind:kuery)` ); }; - return buildHref(summary.state.summaryPings || [], 'monitor.ip', getHref); + return buildHref(summary.state.summaryPings || [], (ping: Ping) => ping?.monitor?.ip, getHref); }; diff --git a/x-pack/plugins/uptime/public/lib/helper/observability_integration/get_logging_href.ts b/x-pack/plugins/uptime/public/lib/helper/observability_integration/get_logging_href.ts index c4fee330e9763..32709882d1d21 100644 --- a/x-pack/plugins/uptime/public/lib/helper/observability_integration/get_logging_href.ts +++ b/x-pack/plugins/uptime/public/lib/helper/observability_integration/get_logging_href.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { MonitorSummary } from '../../../../common/runtime_types'; +import { MonitorSummary, Ping } from '../../../../common/runtime_types'; import { addBasePath } from './add_base_path'; import { buildHref } from './build_href'; @@ -22,7 +22,7 @@ export const getLoggingContainerHref = ( `/app/logs?logFilter=${encodeURI(`(expression:'container.id : ${ret}',kind:kuery)`)}` ); }; - return buildHref(summary.state.summaryPings || [], 'container.id', getHref); + return buildHref(summary.state.summaryPings || [], (ping: Ping) => ping?.container?.id, getHref); }; export const getLoggingKubernetesHref = (summary: MonitorSummary, basePath: string) => { @@ -36,7 +36,11 @@ export const getLoggingKubernetesHref = (summary: MonitorSummary, basePath: stri `/app/logs?logFilter=${encodeURI(`(expression:'pod.uid : ${ret}',kind:kuery)`)}` ); }; - return buildHref(summary.state.summaryPings || [], 'kubernetes.pod.uid', getHref); + return buildHref( + summary.state.summaryPings || [], + (ping: Ping) => ping?.kubernetes?.pod?.uid, + getHref + ); }; export const getLoggingIpHref = (summary: MonitorSummary, basePath: string) => { @@ -50,5 +54,5 @@ export const getLoggingIpHref = (summary: MonitorSummary, basePath: string) => { `/app/logs?logFilter=(expression:'${encodeURIComponent(`host.ip : ${ret}`)}',kind:kuery)` ); }; - return buildHref(summary.state.summaryPings || [], 'monitor.ip', getHref); + return buildHref(summary.state.summaryPings || [], (ping: Ping) => ping?.monitor?.ip, getHref); }; diff --git a/x-pack/plugins/uptime/public/lib/lib.ts b/x-pack/plugins/uptime/public/lib/lib.ts index 187dcee7adb1a..ac95f018a80a2 100644 --- a/x-pack/plugins/uptime/public/lib/lib.ts +++ b/x-pack/plugins/uptime/public/lib/lib.ts @@ -4,19 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ReactElement } from 'react'; -import { AppUnmount } from 'kibana/public'; import { UMBadge } from '../badge'; -import { UptimeAppProps } from '../uptime_app'; - -export interface UMFrontendLibs { - framework: UMFrameworkAdapter; -} export type UMUpdateBadge = (badge: UMBadge) => void; - -export type BootstrapUptimeApp = (props: UptimeAppProps) => ReactElement; - -export interface UMFrameworkAdapter { - render(element: any): Promise; -} diff --git a/x-pack/plugins/uptime/public/pages/__tests__/__snapshots__/page_header.test.tsx.snap b/x-pack/plugins/uptime/public/pages/__tests__/__snapshots__/page_header.test.tsx.snap index fcf68ad97c8ce..1b5856bf1f9e2 100644 --- a/x-pack/plugins/uptime/public/pages/__tests__/__snapshots__/page_header.test.tsx.snap +++ b/x-pack/plugins/uptime/public/pages/__tests__/__snapshots__/page_header.test.tsx.snap @@ -80,28 +80,25 @@ Array [ class="euiFlexItem euiFlexItem--flexGrowZero" > - +
{ }, [dispatch, page, search, sort.direction, sort.field, lastRefresh]); const { data: certificates } = useSelector(certificatesSelector); + const history = useHistory(); return ( <> - - - {labels.RETURN_TO_OVERVIEW} - - + + {labels.RETURN_TO_OVERVIEW} + - - - {labels.SETTINGS_ON_CERT} - - + + {labels.SETTINGS_ON_CERT} + diff --git a/x-pack/plugins/uptime/public/pages/not_found.tsx b/x-pack/plugins/uptime/public/pages/not_found.tsx index 0576a79999a50..264a2b6b682c8 100644 --- a/x-pack/plugins/uptime/public/pages/not_found.tsx +++ b/x-pack/plugins/uptime/public/pages/not_found.tsx @@ -13,38 +13,39 @@ import { EuiButton, } from '@elastic/eui'; import React from 'react'; -import { Link } from 'react-router-dom'; +import { useHistory } from 'react-router-dom'; import { FormattedMessage } from '@kbn/i18n/react'; -export const NotFoundPage = () => ( - - - - -

- -

- - } - body={ - - +export const NotFoundPage = () => { + const history = useHistory(); + return ( + + + + +

+ +

+ + } + body={ + - - } - /> -
-
-
-); + } + /> +
+
+
+ ); +}; diff --git a/x-pack/plugins/uptime/public/pages/overview.tsx b/x-pack/plugins/uptime/public/pages/overview.tsx index 32c86435913f7..3b58ea1e5cf84 100644 --- a/x-pack/plugins/uptime/public/pages/overview.tsx +++ b/x-pack/plugins/uptime/public/pages/overview.tsx @@ -18,7 +18,6 @@ import { useTrackPageview } from '../../../observability/public'; import { MonitorList } from '../components/overview/monitor_list/monitor_list_container'; import { EmptyState, FilterGroup, KueryBar, ParsingErrorCallout } from '../components/overview'; import { StatusPanel } from '../components/overview/status_panel'; -import { useKibana } from '../../../../../src/plugins/kibana_react/public'; interface Props { loading: boolean; @@ -43,12 +42,6 @@ export const OverviewPageComponent = React.memo( const { absoluteDateRangeStart, absoluteDateRangeEnd, ...params } = useGetUrlParams(); const { search, filters: urlFilters } = params; - const { - services: { - data: { autocomplete }, - }, - } = useKibana(); - useTrackPageview({ app: 'uptime', path: 'overview' }); useTrackPageview({ app: 'uptime', path: 'overview', delay: 15000 }); @@ -77,7 +70,6 @@ export const OverviewPageComponent = React.memo( aria-label={i18n.translate('xpack.uptime.filterBar.ariaLabel', { defaultMessage: 'Input filter criteria for the overview page', })} - autocomplete={autocomplete} data-test-subj="xpack.uptime.filterBar" />
diff --git a/x-pack/plugins/uptime/public/pages/page_header.tsx b/x-pack/plugins/uptime/public/pages/page_header.tsx index 421e0e3a4ebde..16279a63b5f40 100644 --- a/x-pack/plugins/uptime/public/pages/page_header.tsx +++ b/x-pack/plugins/uptime/public/pages/page_header.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { EuiFlexGroup, EuiFlexItem, EuiTitle, EuiSpacer, EuiButtonEmpty } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { Link } from 'react-router-dom'; +import { useHistory } from 'react-router-dom'; import styled from 'styled-components'; import { UptimeDatePicker } from '../components/common/uptime_date_picker'; import { SETTINGS_ROUTE } from '../../common/constants'; @@ -58,6 +58,7 @@ export const PageHeader = React.memo( ) : null; const kibana = useKibana(); + const history = useHistory(); const extraLinkComponents = !extraLinks ? null : ( @@ -65,11 +66,13 @@ export const PageHeader = React.memo( - - - {SETTINGS_LINK_TEXT} - - + + {SETTINGS_LINK_TEXT} + { + return ( + settings?.certAgeThreshold !== formFields?.certAgeThreshold || + settings?.certExpirationThreshold !== formFields?.certExpirationThreshold || + settings?.heartbeatIndices !== formFields?.heartbeatIndices + ); +}; + export const SettingsPage: React.FC = () => { const dss = useSelector(selectDynamicSettings); @@ -121,7 +128,8 @@ export const SettingsPage: React.FC = () => { const resetForm = () => setFormFields(dss.settings ? { ...dss.settings } : null); - const isFormDirty = !isEqual(dss.settings, formFields); + const isFormDirty = isDirtyForm(formFields, dss.settings); + const canEdit: boolean = !!useKibana().services?.application?.capabilities.uptime.configureSettings || false; const isFormDisabled = dss.loading || !canEdit; @@ -135,13 +143,19 @@ export const SettingsPage: React.FC = () => { ); + const history = useHistory(); + return ( <> - - - {Translations.settings.returnToOverviewLinkLabel} - - + + {Translations.settings.returnToOverviewLinkLabel} + diff --git a/x-pack/plugins/uptime/public/state/actions/__tests__/__snapshots__/overview_filters.test.ts.snap b/x-pack/plugins/uptime/public/state/actions/__tests__/__snapshots__/overview_filters.test.ts.snap index 6fe2c8eaa362d..1e7ea536bae79 100644 --- a/x-pack/plugins/uptime/public/state/actions/__tests__/__snapshots__/overview_filters.test.ts.snap +++ b/x-pack/plugins/uptime/public/state/actions/__tests__/__snapshots__/overview_filters.test.ts.snap @@ -2,6 +2,7 @@ exports[`overview filters action creators creates a fail action 1`] = ` Object { + "error": true, "payload": [Error: There was an error retrieving the overview filters], "type": "FETCH_OVERVIEW_FILTERS_FAIL", } diff --git a/x-pack/plugins/uptime/public/state/actions/overview_filters.ts b/x-pack/plugins/uptime/public/state/actions/overview_filters.ts index 8eefa701a240a..1dcf49414c413 100644 --- a/x-pack/plugins/uptime/public/state/actions/overview_filters.ts +++ b/x-pack/plugins/uptime/public/state/actions/overview_filters.ts @@ -4,13 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ +import { createAction } from 'redux-actions'; import { OverviewFilters } from '../../../common/runtime_types'; -export const FETCH_OVERVIEW_FILTERS = 'FETCH_OVERVIEW_FILTERS'; -export const FETCH_OVERVIEW_FILTERS_FAIL = 'FETCH_OVERVIEW_FILTERS_FAIL'; -export const FETCH_OVERVIEW_FILTERS_SUCCESS = 'FETCH_OVERVIEW_FILTERS_SUCCESS'; -export const SET_OVERVIEW_FILTERS = 'SET_OVERVIEW_FILTERS'; - export interface GetOverviewFiltersPayload { dateRangeStart: string; dateRangeEnd: string; @@ -22,52 +18,16 @@ export interface GetOverviewFiltersPayload { tags: string[]; } -interface GetOverviewFiltersFetchAction { - type: typeof FETCH_OVERVIEW_FILTERS; - payload: GetOverviewFiltersPayload; -} - -interface GetOverviewFiltersSuccessAction { - type: typeof FETCH_OVERVIEW_FILTERS_SUCCESS; - payload: OverviewFilters; -} - -interface GetOverviewFiltersFailAction { - type: typeof FETCH_OVERVIEW_FILTERS_FAIL; - payload: Error; -} - -interface SetOverviewFiltersAction { - type: typeof SET_OVERVIEW_FILTERS; - payload: OverviewFilters; -} - -export type OverviewFiltersAction = - | GetOverviewFiltersFetchAction - | GetOverviewFiltersSuccessAction - | GetOverviewFiltersFailAction - | SetOverviewFiltersAction; +export type OverviewFiltersPayload = GetOverviewFiltersPayload & Error & OverviewFilters; -export const fetchOverviewFilters = ( - payload: GetOverviewFiltersPayload -): GetOverviewFiltersFetchAction => ({ - type: FETCH_OVERVIEW_FILTERS, - payload, -}); +export const fetchOverviewFilters = createAction( + 'FETCH_OVERVIEW_FILTERS' +); -export const fetchOverviewFiltersFail = (error: Error): GetOverviewFiltersFailAction => ({ - type: FETCH_OVERVIEW_FILTERS_FAIL, - payload: error, -}); +export const fetchOverviewFiltersFail = createAction('FETCH_OVERVIEW_FILTERS_FAIL'); -export const fetchOverviewFiltersSuccess = ( - filters: OverviewFilters -): GetOverviewFiltersSuccessAction => ({ - type: FETCH_OVERVIEW_FILTERS_SUCCESS, - payload: filters, -}); +export const fetchOverviewFiltersSuccess = createAction( + 'FETCH_OVERVIEW_FILTERS_SUCCESS' +); -export const setOverviewFilters = (filters: OverviewFilters): SetOverviewFiltersAction => ({ - type: SET_OVERVIEW_FILTERS, - payload: filters, -}); +export const setOverviewFilters = createAction('SET_OVERVIEW_FILTERS'); diff --git a/x-pack/plugins/uptime/public/state/api/utils.ts b/x-pack/plugins/uptime/public/state/api/utils.ts index 4f3765275c49a..e0cec56dd52cd 100644 --- a/x-pack/plugins/uptime/public/state/api/utils.ts +++ b/x-pack/plugins/uptime/public/state/api/utils.ts @@ -8,7 +8,11 @@ import { PathReporter } from 'io-ts/lib/PathReporter'; import { isRight } from 'fp-ts/lib/Either'; import { HttpFetchQuery, HttpSetup } from 'src/core/public'; import * as t from 'io-ts'; -import { isObject } from 'lodash'; + +function isObject(value: unknown) { + const type = typeof value; + return value != null && (type === 'object' || type === 'function'); +} // TODO: Copied from https://github.com/elastic/kibana/blob/master/x-pack/plugins/security_solution/common/format_errors.ts // We should figure out a better way to share this diff --git a/x-pack/plugins/uptime/public/state/effects/index_status.ts b/x-pack/plugins/uptime/public/state/effects/index_status.ts index a4b85312849a2..3917159381eb5 100644 --- a/x-pack/plugins/uptime/public/state/effects/index_status.ts +++ b/x-pack/plugins/uptime/public/state/effects/index_status.ts @@ -6,8 +6,8 @@ import { takeLeading } from 'redux-saga/effects'; import { indexStatusAction } from '../actions'; -import { fetchIndexStatus } from '../api'; import { fetchEffectFactory } from './fetch_effect'; +import { fetchIndexStatus } from '../api/index_status'; export function* fetchIndexStatusEffect() { yield takeLeading( diff --git a/x-pack/plugins/uptime/public/state/effects/overview_filters.ts b/x-pack/plugins/uptime/public/state/effects/overview_filters.ts index 92b578bafed2d..9149f20f233c6 100644 --- a/x-pack/plugins/uptime/public/state/effects/overview_filters.ts +++ b/x-pack/plugins/uptime/public/state/effects/overview_filters.ts @@ -6,7 +6,7 @@ import { takeLatest } from 'redux-saga/effects'; import { - FETCH_OVERVIEW_FILTERS, + fetchOverviewFilters as fetchAction, fetchOverviewFiltersFail, fetchOverviewFiltersSuccess, } from '../actions'; @@ -15,7 +15,7 @@ import { fetchEffectFactory } from './fetch_effect'; export function* fetchOverviewFiltersEffect() { yield takeLatest( - FETCH_OVERVIEW_FILTERS, + String(fetchAction), fetchEffectFactory(fetchOverviewFilters, fetchOverviewFiltersSuccess, fetchOverviewFiltersFail) ); } diff --git a/x-pack/plugins/uptime/public/state/reducers/overview_filters.ts b/x-pack/plugins/uptime/public/state/reducers/overview_filters.ts index 4548627d9dcb8..702518b69cba5 100644 --- a/x-pack/plugins/uptime/public/state/reducers/overview_filters.ts +++ b/x-pack/plugins/uptime/public/state/reducers/overview_filters.ts @@ -4,13 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ +import { handleActions, Action } from 'redux-actions'; import { OverviewFilters } from '../../../common/runtime_types'; import { - FETCH_OVERVIEW_FILTERS, - FETCH_OVERVIEW_FILTERS_FAIL, - FETCH_OVERVIEW_FILTERS_SUCCESS, - OverviewFiltersAction, - SET_OVERVIEW_FILTERS, + fetchOverviewFilters, + fetchOverviewFiltersFail, + fetchOverviewFiltersSuccess, + setOverviewFilters, + GetOverviewFiltersPayload, + OverviewFiltersPayload, } from '../actions'; export interface OverviewFiltersState { @@ -30,34 +32,29 @@ const initialState: OverviewFiltersState = { loading: false, }; -export function overviewFiltersReducer( - state = initialState, - action: OverviewFiltersAction -): OverviewFiltersState { - switch (action.type) { - case FETCH_OVERVIEW_FILTERS: - return { - ...state, - loading: true, - }; - case FETCH_OVERVIEW_FILTERS_SUCCESS: - return { - ...state, - filters: action.payload, - loading: false, - }; - case FETCH_OVERVIEW_FILTERS_FAIL: - return { - ...state, - errors: [...state.errors, action.payload], - loading: false, - }; - case SET_OVERVIEW_FILTERS: - return { - ...state, - filters: action.payload, - }; - default: - return state; - } -} +export const overviewFiltersReducer = handleActions( + { + [String(fetchOverviewFilters)]: (state, _action: Action) => ({ + ...state, + loading: true, + }), + + [String(fetchOverviewFiltersSuccess)]: (state, action: Action) => ({ + ...state, + filters: action.payload, + loading: false, + }), + + [String(fetchOverviewFiltersFail)]: (state, action: Action) => ({ + ...state, + errors: [...state.errors, action.payload], + loading: false, + }), + + [String(setOverviewFilters)]: (state, action: Action) => ({ + ...state, + filters: action.payload, + }), + }, + initialState +); diff --git a/x-pack/plugins/uptime/server/kibana.index.ts b/x-pack/plugins/uptime/server/kibana.index.ts index d68bbabe82b86..ab8d7a068b19d 100644 --- a/x-pack/plugins/uptime/server/kibana.index.ts +++ b/x-pack/plugins/uptime/server/kibana.index.ts @@ -5,7 +5,7 @@ */ import { Request, Server } from 'hapi'; -import { PLUGIN } from '../common/constants'; +import { PLUGIN } from '../common/constants/plugin'; import { compose } from './lib/compose/kibana'; import { initUptimeServer } from './uptime_server'; import { UptimeCorePlugins, UptimeCoreSetup } from './lib/adapters/framework'; @@ -35,51 +35,42 @@ export const initServerWithKibana = (server: UptimeCoreSetup, plugins: UptimeCor icon: 'uptimeApp', app: ['uptime', 'kibana'], catalogue: ['uptime'], + management: { + insightsAndAlerting: ['triggersActions'], + }, + alerting: ['xpack.uptime.alerts.tls', 'xpack.uptime.alerts.monitorStatus'], privileges: { all: { app: ['uptime', 'kibana'], catalogue: ['uptime'], - api: [ - 'uptime-read', - 'uptime-write', - 'actions-read', - 'actions-all', - 'alerting-read', - 'alerting-all', - ], + api: ['uptime-read', 'uptime-write'], savedObject: { - all: [umDynamicSettings.name, 'alert', 'action', 'action_task_params'], + all: [umDynamicSettings.name, 'alert'], read: [], }, - ui: [ - 'save', - 'configureSettings', - 'show', - 'alerting:show', - 'actions:show', - 'alerting:save', - 'actions:save', - 'alerting:delete', - 'actions:delete', - ], + alerting: { + all: ['xpack.uptime.alerts.tls', 'xpack.uptime.alerts.monitorStatus'], + }, + management: { + insightsAndAlerting: ['triggersActions'], + }, + ui: ['save', 'configureSettings', 'show'], }, read: { app: ['uptime', 'kibana'], catalogue: ['uptime'], - api: ['uptime-read', 'actions-read', 'actions-all', 'alerting-read', 'alerting-all'], + api: ['uptime-read'], savedObject: { - all: ['alert', 'action', 'action_task_params'], + all: ['alert'], read: [umDynamicSettings.name], }, - ui: [ - 'show', - 'alerting:show', - 'actions:show', - 'alerting:save', - 'actions:save', - 'alerting:delete', - 'actions:delete', - ], + alerting: { + all: ['xpack.uptime.alerts.tls', 'xpack.uptime.alerts.monitorStatus'], + }, + management: { + insightsAndAlerting: ['triggersActions'], + }, + ui: ['show'], }, }, }); diff --git a/x-pack/plugins/uptime/server/lib/alerts/duration_anomaly.ts b/x-pack/plugins/uptime/server/lib/alerts/duration_anomaly.ts index 7dd357e99b83d..a71913d0eea9a 100644 --- a/x-pack/plugins/uptime/server/lib/alerts/duration_anomaly.ts +++ b/x-pack/plugins/uptime/server/lib/alerts/duration_anomaly.ts @@ -8,7 +8,7 @@ import moment from 'moment'; import { schema } from '@kbn/config-schema'; import { ILegacyScopedClusterClient } from 'kibana/server'; import { updateState } from './common'; -import { ACTION_GROUP_DEFINITIONS } from '../../../common/constants'; +import { ACTION_GROUP_DEFINITIONS } from '../../../common/constants/alerts'; import { commonStateTranslations, durationAnomalyTranslations } from './translations'; import { AnomaliesTableRecord } from '../../../../ml/common/types/anomalies'; import { getSeverityType } from '../../../../ml/common/util/anomaly_utils'; diff --git a/x-pack/plugins/uptime/server/lib/alerts/status_check.ts b/x-pack/plugins/uptime/server/lib/alerts/status_check.ts index 2117ac4b7ed4e..a34d7eb292eef 100644 --- a/x-pack/plugins/uptime/server/lib/alerts/status_check.ts +++ b/x-pack/plugins/uptime/server/lib/alerts/status_check.ts @@ -21,7 +21,7 @@ import { MonitorAvailabilityType, DynamicSettings, } from '../../../common/runtime_types'; -import { ACTION_GROUP_DEFINITIONS } from '../../../common/constants'; +import { ACTION_GROUP_DEFINITIONS } from '../../../common/constants/alerts'; import { savedObjectsAdapter } from '../saved_objects'; import { updateState } from './common'; import { commonStateTranslations } from './translations'; diff --git a/x-pack/plugins/uptime/server/lib/alerts/tls.ts b/x-pack/plugins/uptime/server/lib/alerts/tls.ts index 61e738b088d50..d4853ad7a9cb0 100644 --- a/x-pack/plugins/uptime/server/lib/alerts/tls.ts +++ b/x-pack/plugins/uptime/server/lib/alerts/tls.ts @@ -9,7 +9,8 @@ import { schema } from '@kbn/config-schema'; import { UptimeAlertTypeFactory } from './types'; import { savedObjectsAdapter } from '../saved_objects'; import { updateState } from './common'; -import { ACTION_GROUP_DEFINITIONS, DYNAMIC_SETTINGS_DEFAULTS } from '../../../common/constants'; +import { ACTION_GROUP_DEFINITIONS } from '../../../common/constants/alerts'; +import { DYNAMIC_SETTINGS_DEFAULTS } from '../../../common/constants'; import { Cert, CertResult } from '../../../common/runtime_types'; import { commonStateTranslations, tlsTranslations } from './translations'; import { DEFAULT_FROM, DEFAULT_TO } from '../../rest_api/certs/certs'; diff --git a/x-pack/plugins/uptime/server/lib/requests/get_ping_histogram.ts b/x-pack/plugins/uptime/server/lib/requests/get_ping_histogram.ts index a74b55c24e227..970d9ad166982 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_ping_histogram.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_ping_histogram.ts @@ -8,6 +8,7 @@ import { UMElasticsearchQueryFn } from '../adapters'; import { getFilterClause } from '../helper'; import { HistogramResult, HistogramQueryResult } from '../../../common/runtime_types'; import { QUERY } from '../../../common/constants'; +import { getHistogramInterval } from '../helper/get_histogram_interval'; export interface GetPingHistogramParams { /** @member dateRangeStart timestamp bounds */ @@ -36,22 +37,6 @@ export const getPingHistogram: UMElasticsearchQueryFn< } const filter = getFilterClause(from, to, additionalFilters); - const seriesHistogram: any = {}; - - if (bucketSize) { - seriesHistogram.date_histogram = { - field: '@timestamp', - fixed_interval: bucketSize, - missing: 0, - }; - } else { - seriesHistogram.auto_date_histogram = { - field: '@timestamp', - buckets: QUERY.DEFAULT_BUCKET_COUNT, - missing: 0, - }; - } - const params = { index: dynamicSettings.heartbeatIndices, body: { @@ -63,7 +48,12 @@ export const getPingHistogram: UMElasticsearchQueryFn< size: 0, aggs: { timeseries: { - ...seriesHistogram, + date_histogram: { + field: '@timestamp', + fixed_interval: + bucketSize || getHistogramInterval(from, to, QUERY.DEFAULT_BUCKET_COUNT) + 'ms', + missing: 0, + }, aggs: { down: { filter: { diff --git a/x-pack/plugins/uptime/server/lib/saved_objects.ts b/x-pack/plugins/uptime/server/lib/saved_objects.ts index 5a61eb859c28b..8024aba198058 100644 --- a/x-pack/plugins/uptime/server/lib/saved_objects.ts +++ b/x-pack/plugins/uptime/server/lib/saved_objects.ts @@ -22,7 +22,11 @@ export const umDynamicSettings: SavedObjectsType = { hidden: false, namespaceType: 'single', mappings: { + dynamic: false, properties: { + /* Leaving these commented to make it clear that these fields exist, even though we don't want them indexed. + When adding new fields please add them here. If they need to be searchable put them in the uncommented + part of properties. heartbeatIndices: { type: 'keyword', }, @@ -32,6 +36,7 @@ export const umDynamicSettings: SavedObjectsType = { certExpirationThreshold: { type: 'long', }, + */ }, }, }; diff --git a/x-pack/scripts/functional_tests.js b/x-pack/scripts/functional_tests.js index ee8af9e040401..eeff81d492d26 100644 --- a/x-pack/scripts/functional_tests.js +++ b/x-pack/scripts/functional_tests.js @@ -10,6 +10,8 @@ const alwaysImportedTests = [ require.resolve('../test/functional_with_es_ssl/config.ts'), require.resolve('../test/functional/config_security_basic.ts'), require.resolve('../test/functional/config_security_trial.ts'), + require.resolve('../test/functional_embedded/config.ts'), + require.resolve('../test/functional_enterprise_search/without_host_configured.config.ts'), ]; const onlyNotInCoverageTests = [ require.resolve('../test/api_integration/config_security_basic.ts'), @@ -51,9 +53,8 @@ const onlyNotInCoverageTests = [ require.resolve('../test/licensing_plugin/config.legacy.ts'), require.resolve('../test/endpoint_api_integration_no_ingest/config.ts'), require.resolve('../test/reporting_api_integration/config.js'), - require.resolve('../test/functional_embedded/config.ts'), + require.resolve('../test/security_solution_endpoint_api_int/config.ts'), require.resolve('../test/ingest_manager_api_integration/config.ts'), - require.resolve('../test/functional_enterprise_search/without_host_configured.config.ts'), ]; require('@kbn/plugin-helpers').babelRegister(); diff --git a/x-pack/tasks/test.ts b/x-pack/tasks/test.ts deleted file mode 100644 index 0d990bff9f44e..0000000000000 --- a/x-pack/tasks/test.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import * as pluginHelpers from '@kbn/plugin-helpers'; -import gulp from 'gulp'; - -import { getEnabledPlugins } from './helpers/flags'; - -export const testServerTask = async () => { - throw new Error('server mocha tests are now included in the `node scripts/mocha` script'); -}; - -export const testKarmaTask = async () => { - const plugins = await getEnabledPlugins(); - await pluginHelpers.run('testKarma', { - plugins: plugins.join(','), - }); -}; - -export const testKarmaDebugTask = async () => { - const plugins = await getEnabledPlugins(); - await pluginHelpers.run('testKarma', { - dev: true, - plugins: plugins.join(','), - }); -}; - -export const testTask = gulp.series(testKarmaTask, testServerTask); diff --git a/x-pack/test/alerting_api_integration/common/fixtures/plugins/actions_simulators/server/plugin.ts b/x-pack/test/alerting_api_integration/common/fixtures/plugins/actions_simulators/server/plugin.ts index b8b2cbdc03f39..cb1271494c294 100644 --- a/x-pack/test/alerting_api_integration/common/fixtures/plugins/actions_simulators/server/plugin.ts +++ b/x-pack/test/alerting_api_integration/common/fixtures/plugins/actions_simulators/server/plugin.ts @@ -61,27 +61,27 @@ export class FixturePlugin implements Plugin { public setup(core: CoreSetup, { features, actions, alerts }: FixtureSetupDeps) { features.registerFeature({ - id: 'alerts', + id: 'alertsFixture', name: 'Alerts', app: ['alerts', 'kibana'], + alerting: [ + 'test.always-firing', + 'test.cumulative-firing', + 'test.never-firing', + 'test.failing', + 'test.authorization', + 'test.validation', + 'test.onlyContextVariables', + 'test.onlyStateVariables', + 'test.noop', + 'test.unrestricted-noop', + ], privileges: { all: { app: ['alerts', 'kibana'], @@ -36,8 +48,21 @@ export class FixturePlugin implements Plugin, + { alerts }: Pick +) { + const noopRestrictedAlertType: AlertType = { + id: 'test.restricted-noop', + name: 'Test: Restricted Noop', + actionGroups: [{ id: 'default', name: 'Default' }], + producer: 'alertsRestrictedFixture', + defaultActionGroupId: 'default', + async executor({ services, params, state }: AlertExecutorOptions) {}, + }; + const noopUnrestrictedAlertType: AlertType = { + id: 'test.unrestricted-noop', + name: 'Test: Unrestricted Noop', + actionGroups: [{ id: 'default', name: 'Default' }], + producer: 'alertsRestrictedFixture', + defaultActionGroupId: 'default', + async executor({ services, params, state }: AlertExecutorOptions) {}, + }; + alerts.registerType(noopRestrictedAlertType); + alerts.registerType(noopUnrestrictedAlertType); +} diff --git a/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts_restricted/server/index.ts b/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts_restricted/server/index.ts new file mode 100644 index 0000000000000..54d6de50cff4d --- /dev/null +++ b/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts_restricted/server/index.ts @@ -0,0 +1,9 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FixturePlugin } from './plugin'; + +export const plugin = () => new FixturePlugin(); diff --git a/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts_restricted/server/plugin.ts b/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts_restricted/server/plugin.ts new file mode 100644 index 0000000000000..e297733fb47eb --- /dev/null +++ b/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts_restricted/server/plugin.ts @@ -0,0 +1,62 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Plugin, CoreSetup } from 'kibana/server'; +import { PluginSetupContract as ActionsPluginSetup } from '../../../../../../../plugins/actions/server/plugin'; +import { PluginSetupContract as AlertingPluginSetup } from '../../../../../../../plugins/alerts/server/plugin'; +import { EncryptedSavedObjectsPluginStart } from '../../../../../../../plugins/encrypted_saved_objects/server'; +import { PluginSetupContract as FeaturesPluginSetup } from '../../../../../../../plugins/features/server'; +import { defineAlertTypes } from './alert_types'; + +export interface FixtureSetupDeps { + features: FeaturesPluginSetup; + actions: ActionsPluginSetup; + alerts: AlertingPluginSetup; +} + +export interface FixtureStartDeps { + encryptedSavedObjects: EncryptedSavedObjectsPluginStart; +} + +export class FixturePlugin implements Plugin { + public setup(core: CoreSetup, { features, alerts }: FixtureSetupDeps) { + features.registerFeature({ + id: 'alertsRestrictedFixture', + name: 'AlertRestricted', + app: ['alerts', 'kibana'], + alerting: ['test.restricted-noop', 'test.unrestricted-noop', 'test.noop'], + privileges: { + all: { + app: ['alerts', 'kibana'], + savedObject: { + all: ['alert'], + read: [], + }, + alerting: { + all: ['test.restricted-noop', 'test.unrestricted-noop', 'test.noop'], + }, + ui: [], + }, + read: { + app: ['alerts', 'kibana'], + savedObject: { + all: [], + read: [], + }, + alerting: { + read: ['test.restricted-noop', 'test.unrestricted-noop', 'test.noop'], + }, + ui: [], + }, + }, + }); + + defineAlertTypes(core, { alerts }); + } + + public start() {} + public stop() {} +} diff --git a/x-pack/test/alerting_api_integration/common/lib/alert_utils.ts b/x-pack/test/alerting_api_integration/common/lib/alert_utils.ts index 708e7e1b75b58..a68f8de39d48e 100644 --- a/x-pack/test/alerting_api_integration/common/lib/alert_utils.ts +++ b/x-pack/test/alerting_api_integration/common/lib/alert_utils.ts @@ -252,7 +252,7 @@ export class AlertUtils { throttle: '30s', tags: [], alertTypeId: 'test.failing', - consumer: 'bar', + consumer: 'alertsFixture', params: { index: ES_TEST_INDEX_NAME, reference, @@ -267,6 +267,22 @@ export class AlertUtils { } } +export function getConsumerUnauthorizedErrorMessage( + operation: string, + alertType: string, + consumer: string +) { + return `Unauthorized to ${operation} a "${alertType}" alert for "${consumer}"`; +} + +export function getProducerUnauthorizedErrorMessage( + operation: string, + alertType: string, + producer: string +) { + return `Unauthorized to ${operation} a "${alertType}" alert by "${producer}"`; +} + function getDefaultAlwaysFiringAlertData(reference: string, actionId: string) { const messageTemplate = ` alertId: {{alertId}}, @@ -284,7 +300,7 @@ instanceStateValue: {{state.instanceStateValue}} throttle: '1m', tags: ['tag-A', 'tag-B'], alertTypeId: 'test.always-firing', - consumer: 'bar', + consumer: 'alertsFixture', params: { index: ES_TEST_INDEX_NAME, reference, diff --git a/x-pack/test/alerting_api_integration/common/lib/get_event_log.ts b/x-pack/test/alerting_api_integration/common/lib/get_event_log.ts index 69eeaafbf64fa..99f51ff244546 100644 --- a/x-pack/test/alerting_api_integration/common/lib/get_event_log.ts +++ b/x-pack/test/alerting_api_integration/common/lib/get_event_log.ts @@ -22,6 +22,7 @@ interface GetEventLogParams { export async function getEventLog(params: GetEventLogParams): Promise { const { getService, spaceId, type, id, provider, actions } = params; const supertest = getService('supertest'); + const actionsSet = new Set(actions); const spacePrefix = getUrlPrefix(spaceId); const url = `${spacePrefix}/api/event_log/${type}/${id}/_find`; @@ -31,11 +32,13 @@ export async function getEventLog(params: GetEventLogParams): Promise event?.event?.provider === provider - ); + // filter events to matching provider and requested actions + const events: IValidatedEvent[] = (result.data as IValidatedEvent[]) + .filter((event) => event?.event?.provider === provider) + .filter((event) => event?.event?.action) + .filter((event) => actionsSet.has(event?.event?.action!)); const foundActions = new Set( - events.map((event) => event?.event?.action).filter((event) => !!event) + events.map((event) => event?.event?.action).filter((action) => !!action) ); for (const action of actions) { diff --git a/x-pack/test/alerting_api_integration/common/lib/get_test_alert_data.ts b/x-pack/test/alerting_api_integration/common/lib/get_test_alert_data.ts index 76f78809d5d11..2e7a4e325094c 100644 --- a/x-pack/test/alerting_api_integration/common/lib/get_test_alert_data.ts +++ b/x-pack/test/alerting_api_integration/common/lib/get_test_alert_data.ts @@ -10,7 +10,7 @@ export function getTestAlertData(overwrites = {}) { name: 'abc', tags: ['foo'], alertTypeId: 'test.noop', - consumer: 'bar', + consumer: 'alertsFixture', schedule: { interval: '1m' }, throttle: '1m', actions: [], diff --git a/x-pack/test/alerting_api_integration/common/lib/index.ts b/x-pack/test/alerting_api_integration/common/lib/index.ts index eae679cd38c11..94caf373c98d1 100644 --- a/x-pack/test/alerting_api_integration/common/lib/index.ts +++ b/x-pack/test/alerting_api_integration/common/lib/index.ts @@ -8,7 +8,11 @@ export { ObjectRemover } from './object_remover'; export { getUrlPrefix } from './space_test_utils'; export { ES_TEST_INDEX_NAME, ESTestIndexTool } from './es_test_index_tool'; export { getTestAlertData } from './get_test_alert_data'; -export { AlertUtils } from './alert_utils'; +export { + AlertUtils, + getConsumerUnauthorizedErrorMessage, + getProducerUnauthorizedErrorMessage, +} from './alert_utils'; export { TaskManagerUtils } from './task_manager_utils'; export * from './test_assertions'; export { checkAAD } from './check_aad'; diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/scenarios.ts b/x-pack/test/alerting_api_integration/security_and_spaces/scenarios.ts index c72ee6a192bf2..2f57d05be4227 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/scenarios.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/scenarios.ts @@ -47,8 +47,10 @@ const GlobalRead: User = { kibana: [ { feature: { - alerts: ['read'], actions: ['read'], + alertsFixture: ['read'], + alertsRestrictedFixture: ['read'], + actionsSimulators: ['read'], }, spaces: ['*'], }, @@ -75,8 +77,9 @@ const Space1All: User = { kibana: [ { feature: { - alerts: ['all'], actions: ['all'], + alertsFixture: ['all'], + actionsSimulators: ['all'], }, spaces: ['space1'], }, @@ -94,7 +97,71 @@ const Space1All: User = { }, }; -export const Users: User[] = [NoKibanaPrivileges, Superuser, GlobalRead, Space1All]; +const Space1AllAlertingNoneActions: User = { + username: 'space_1_all_alerts_none_actions', + fullName: 'space_1_all_alerts_none_actions', + password: 'space_1_all_alerts_none_actions-password', + role: { + name: 'space_1_all_alerts_none_actions_role', + kibana: [ + { + feature: { + alertsFixture: ['all'], + actionsSimulators: ['all'], + }, + spaces: ['space1'], + }, + ], + elasticsearch: { + // TODO: Remove once Elasticsearch doesn't require the permission for own keys + cluster: ['manage_api_key'], + indices: [ + { + names: [`${ES_TEST_INDEX_NAME}*`], + privileges: ['all'], + }, + ], + }, + }, +}; + +const Space1AllWithRestrictedFixture: User = { + username: 'space_1_all_with_restricted_fixture', + fullName: 'space_1_all_with_restricted_fixture', + password: 'space_1_all_with_restricted_fixture-password', + role: { + name: 'space_1_all_with_restricted_fixture_role', + kibana: [ + { + feature: { + actions: ['all'], + alertsFixture: ['all'], + alertsRestrictedFixture: ['all'], + }, + spaces: ['space1'], + }, + ], + elasticsearch: { + // TODO: Remove once Elasticsearch doesn't require the permission for own keys + cluster: ['manage_api_key'], + indices: [ + { + names: [`${ES_TEST_INDEX_NAME}*`], + privileges: ['all'], + }, + ], + }, + }, +}; + +export const Users: User[] = [ + NoKibanaPrivileges, + Superuser, + GlobalRead, + Space1All, + Space1AllWithRestrictedFixture, + Space1AllAlertingNoneActions, +]; const Space1: Space = { id: 'space1', @@ -160,6 +227,23 @@ const Space1AllAtSpace1: Space1AllAtSpace1 = { user: Space1All, space: Space1, }; +interface Space1AllWithRestrictedFixtureAtSpace1 extends Scenario { + id: 'space_1_all_with_restricted_fixture at space1'; +} +const Space1AllWithRestrictedFixtureAtSpace1: Space1AllWithRestrictedFixtureAtSpace1 = { + id: 'space_1_all_with_restricted_fixture at space1', + user: Space1AllWithRestrictedFixture, + space: Space1, +}; + +interface Space1AllAlertingNoneActionsAtSpace1 extends Scenario { + id: 'space_1_all_alerts_none_actions at space1'; +} +const Space1AllAlertingNoneActionsAtSpace1: Space1AllAlertingNoneActionsAtSpace1 = { + id: 'space_1_all_alerts_none_actions at space1', + user: Space1AllAlertingNoneActions, + space: Space1, +}; interface Space1AllAtSpace2 extends Scenario { id: 'space_1_all at space2'; @@ -175,11 +259,15 @@ export const UserAtSpaceScenarios: [ SuperuserAtSpace1, GlobalReadAtSpace1, Space1AllAtSpace1, - Space1AllAtSpace2 + Space1AllAtSpace2, + Space1AllWithRestrictedFixtureAtSpace1, + Space1AllAlertingNoneActionsAtSpace1 ] = [ NoKibanaPrivilegesAtSpace1, SuperuserAtSpace1, GlobalReadAtSpace1, Space1AllAtSpace1, Space1AllAtSpace2, + Space1AllWithRestrictedFixtureAtSpace1, + Space1AllAlertingNoneActionsAtSpace1, ]; diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/create.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/create.ts index 69dcb7c813815..75609d58f7792 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/create.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/create.ts @@ -41,16 +41,18 @@ export default function createActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': case 'global_read at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to create a "test.index-record" action', }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); objectRemover.add(space.id, response.body.id, 'action', 'actions'); expect(response.body).to.eql({ @@ -90,16 +92,18 @@ export default function createActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': case 'global_read at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to create a "test.unregistered-action-type" action', }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -122,16 +126,11 @@ export default function createActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': case 'global_read at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -160,16 +159,18 @@ export default function createActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': case 'global_read at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to create a "test.index-record" action', }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -196,16 +197,18 @@ export default function createActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': case 'global_read at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to create a "test.not-enabled" action', }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ statusCode: 403, diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/delete.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/delete.ts index d96ffc5bb3be3..97c933f2ef8c5 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/delete.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/delete.ts @@ -46,18 +46,20 @@ export default function deleteActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to delete actions', }); objectRemover.add(space.id, createdAction.id, 'action', 'actions'); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); break; @@ -88,19 +90,22 @@ export default function deleteActionTests({ getService }: FtrProviderContext) { .auth(user.username, user.password) .set('kbn-xsrf', 'foo'); - expect(response.statusCode).to.eql(404); switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'global_read at space1': case 'space_1_all at space2': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to delete actions', }); break; case 'superuser at space1': + expect(response.statusCode).to.eql(404); expect(response.body).to.eql({ statusCode: 404, error: 'Not Found', @@ -120,17 +125,19 @@ export default function deleteActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to delete actions', }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(404); break; default: @@ -146,17 +153,19 @@ export default function deleteActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to delete actions', }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.body).to.eql({ statusCode: 400, error: 'Bad Request', diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/execute.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/execute.ts index 5d609d001ee5d..a45eee400b445 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/execute.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/execute.ts @@ -77,17 +77,19 @@ export default function ({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to execute actions', }); break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body).to.be.an('object'); const searchResult = await esTestIndexTool.search( @@ -154,19 +156,22 @@ export default function ({ getService }: FtrProviderContext) { }, }); - expect(response.statusCode).to.eql(404); switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to execute actions', }); break; case 'global_read at space1': case 'superuser at space1': + expect(response.statusCode).to.eql(404); expect(response.body).to.eql({ statusCode: 404, error: 'Not Found', @@ -224,17 +229,19 @@ export default function ({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to execute actions', }); break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body).to.be.an('object'); const searchResult = await esTestIndexTool.search( @@ -275,17 +282,19 @@ export default function ({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to execute actions', }); break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(404); expect(response.body).to.eql({ statusCode: 404, @@ -307,17 +316,12 @@ export default function ({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -383,17 +387,19 @@ export default function ({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to execute actions', }); break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); break; default: @@ -431,16 +437,18 @@ export default function ({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to execute actions', }); break; case 'global_read at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); searchResult = await esTestIndexTool.search('action:test.authorization', reference); expect(searchResult.hits.total.value).to.eql(1); diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/get.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/get.ts index c610ac670f690..fc08be3e30a6f 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/get.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/get.ts @@ -45,17 +45,19 @@ export default function getActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to get actions', }); break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body).to.eql({ id: createdAction.id, @@ -93,19 +95,22 @@ export default function getActionTests({ getService }: FtrProviderContext) { .get(`${getUrlPrefix('other')}/api/actions/action/${createdAction.id}`) .auth(user.username, user.password); - expect(response.statusCode).to.eql(404); switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to get actions', }); break; case 'global_read at space1': case 'superuser at space1': + expect(response.statusCode).to.eql(404); expect(response.body).to.eql({ statusCode: 404, error: 'Not Found', @@ -124,17 +129,19 @@ export default function getActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to get actions', }); break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body).to.eql({ id: 'my-slack1', diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/get_all.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/get_all.ts index 45491aa2d28fc..994072d5cb03c 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/get_all.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/get_all.ts @@ -45,17 +45,19 @@ export default function getAllActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to get actions', }); break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body).to.eql([ { @@ -150,17 +152,19 @@ export default function getAllActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to get actions', }); break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body).to.eql([ { @@ -231,13 +235,15 @@ export default function getAllActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': case 'space_1_all at space1': - expect(response.statusCode).to.eql(404); + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to get actions', }); break; case 'global_read at space1': diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/list_action_types.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/list_action_types.ts index 22c89a1a8148f..83b7077cbaadd 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/list_action_types.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/list_action_types.ts @@ -28,19 +28,15 @@ export default function listActionTypesTests({ getService }: FtrProviderContext) }; } + expect(response.statusCode).to.eql(200); switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); // Check for values explicitly in order to avoid this test failing each time plugins register // a new action type diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/update.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/update.ts index cb0e0efda0b1a..82b12e6ce9a22 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/update.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/update.ts @@ -55,17 +55,19 @@ export default function updateActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to update actions', }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body).to.eql({ id: createdAction.id, @@ -120,19 +122,22 @@ export default function updateActionTests({ getService }: FtrProviderContext) { }, }); - expect(response.statusCode).to.eql(404); switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': case 'global_read at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to update actions', }); break; case 'superuser at space1': + expect(response.statusCode).to.eql(404); expect(response.body).to.eql({ statusCode: 404, error: 'Not Found', @@ -156,17 +161,12 @@ export default function updateActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -196,17 +196,19 @@ export default function updateActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to update actions', }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(404); expect(response.body).to.eql({ statusCode: 404, @@ -228,17 +230,12 @@ export default function updateActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -285,17 +282,19 @@ export default function updateActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to update actions', }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -326,17 +325,19 @@ export default function updateActionTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': + case 'space_1_all_alerts_none_actions at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + statusCode: 403, + error: 'Forbidden', + message: 'Unauthorized to update actions', }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.body).to.eql({ statusCode: 400, error: 'Bad Request', diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/alerts.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/alerts.ts index db1e59746162b..8d8bc066a9b1a 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/alerts.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/alerts.ts @@ -14,6 +14,7 @@ import { getTestAlertData, ObjectRemover, AlertUtils, + getConsumerUnauthorizedErrorMessage, TaskManagerUtils, getEventLog, } from '../../../common/lib'; @@ -30,8 +31,7 @@ export default function alertTests({ getService }: FtrProviderContext) { const esTestIndexTool = new ESTestIndexTool(es, retry); const taskManagerUtils = new TaskManagerUtils(es, retry); - // FLAKY: https://github.com/elastic/kibana/issues/72207 - describe.skip('alerts', () => { + describe('alerts', () => { const authorizationIndex = '.kibana-test-authorization'; const objectRemover = new ObjectRemover(supertest); @@ -88,15 +88,28 @@ export default function alertTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.always-firing', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to get actions`, + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); // Wait for the action to index a document before disabling the alert and waiting for tasks to finish @@ -189,15 +202,28 @@ instanceStateValue: true case 'no_kibana_privileges at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.always-firing', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: `Unauthorized to get actions`, + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); // Wait for the action to index a document before disabling the alert and waiting for tasks to finish @@ -376,15 +402,28 @@ instanceStateValue: true case 'no_kibana_privileges at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.always-firing', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to get actions`, + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); objectRemover.add(space.id, response.body.id, 'alert', 'alerts'); @@ -460,14 +499,20 @@ instanceStateValue: true case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.authorization', + 'alertsFixture' + ), + statusCode: 403, }); break; case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); objectRemover.add(space.id, response.body.id, 'alert', 'alerts'); @@ -574,14 +619,19 @@ instanceStateValue: true case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.always-firing', + 'alertsFixture' + ), + statusCode: 403, }); break; case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); objectRemover.add(space.id, response.body.id, 'alert', 'alerts'); @@ -614,6 +664,14 @@ instanceStateValue: true }, }); break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to get actions`, + statusCode: 403, + }); + break; case 'superuser at space1': expect(response.statusCode).to.eql(200); objectRemover.add(space.id, response.body.id, 'alert', 'alerts'); @@ -658,14 +716,27 @@ instanceStateValue: true case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.always-firing', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: `Unauthorized to get actions`, + statusCode: 403, }); break; case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': case 'superuser at space1': expect(response.statusCode).to.eql(200); // Wait until alerts scheduled actions 3 times before disabling the alert and waiting for tasks to finish @@ -724,14 +795,27 @@ instanceStateValue: true case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.always-firing', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to get actions`, + statusCode: 403, }); break; case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': case 'superuser at space1': expect(response.statusCode).to.eql(200); // Wait for actions to execute twice before disabling the alert and waiting for tasks to finish @@ -774,14 +858,27 @@ instanceStateValue: true case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.always-firing', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: `Unauthorized to get actions`, + statusCode: 403, }); break; case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': case 'superuser at space1': expect(response.statusCode).to.eql(200); // Actions should execute twice before widning things down @@ -816,14 +913,27 @@ instanceStateValue: true case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.always-firing', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to get actions`, + statusCode: 403, }); break; case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': case 'superuser at space1': await alertUtils.muteAll(response.body.id); await alertUtils.enable(response.body.id); @@ -861,14 +971,27 @@ instanceStateValue: true case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.always-firing', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: `Unauthorized to get actions`, + statusCode: 403, }); break; case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': case 'superuser at space1': await alertUtils.muteInstance(response.body.id, '1'); await alertUtils.enable(response.body.id); @@ -906,14 +1029,27 @@ instanceStateValue: true case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.always-firing', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: `Unauthorized to get actions`, + statusCode: 403, }); break; case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': case 'superuser at space1': await alertUtils.muteInstance(response.body.id, '1'); await alertUtils.muteAll(response.body.id); diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/create.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/create.ts index 4ca943f3e188a..8d7b9dec58cf1 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/create.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/create.ts @@ -6,7 +6,14 @@ import expect from '@kbn/expect'; import { UserAtSpaceScenarios } from '../../scenarios'; -import { checkAAD, getTestAlertData, getUrlPrefix, ObjectRemover } from '../../../common/lib'; +import { + checkAAD, + getTestAlertData, + getConsumerUnauthorizedErrorMessage, + getUrlPrefix, + ObjectRemover, + getProducerUnauthorizedErrorMessage, +} from '../../../common/lib'; import { FtrProviderContext } from '../../../common/ftr_provider_context'; // eslint-disable-next-line import/no-default-export @@ -62,15 +69,28 @@ export default function createAlertTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to get actions`, + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); objectRemover.add(space.id, response.body.id, 'alert', 'alerts'); expect(response.body).to.eql({ @@ -87,7 +107,7 @@ export default function createAlertTests({ getService }: FtrProviderContext) { ], enabled: true, alertTypeId: 'test.noop', - consumer: 'bar', + consumer: 'alertsFixture', params: {}, createdBy: user.username, schedule: { interval: '1m' }, @@ -124,6 +144,174 @@ export default function createAlertTests({ getService }: FtrProviderContext) { } }); + it('should handle create alert request appropriately when consumer is the same as producer', async () => { + const response = await supertestWithoutAuth + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .send( + getTestAlertData({ + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + }) + ); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'global_read at space1': + case 'space_1_all at space2': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(200); + objectRemover.add(space.id, response.body.id, 'alert', 'alerts'); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle create alert request appropriately when consumer is not the producer', async () => { + const response = await supertestWithoutAuth + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .send( + getTestAlertData({ alertTypeId: 'test.unrestricted-noop', consumer: 'alertsFixture' }) + ); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'global_read at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.unrestricted-noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'create', + 'test.unrestricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(200); + objectRemover.add(space.id, response.body.id, 'alert', 'alerts'); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle create alert request appropriately when consumer is "alerts"', async () => { + const response = await supertestWithoutAuth + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .send( + getTestAlertData({ + alertTypeId: 'test.noop', + consumer: 'alerts', + }) + ); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage('create', 'test.noop', 'alerts'), + statusCode: 403, + }); + break; + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'create', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(200); + objectRemover.add(space.id, response.body.id, 'alert', 'alerts'); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle create alert request appropriately when consumer is unknown', async () => { + const response = await supertestWithoutAuth + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .send( + getTestAlertData({ + alertTypeId: 'test.noop', + consumer: 'some consumer patrick invented', + }) + ); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'global_read at space1': + case 'space_1_all at space2': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': + case 'superuser at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.noop', + 'some consumer patrick invented' + ), + statusCode: 403, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + it('should handle create alert request appropriately when an alert is disabled ', async () => { const response = await supertestWithoutAuth .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) @@ -135,15 +323,21 @@ export default function createAlertTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); objectRemover.add(space.id, response.body.id, 'alert', 'alerts'); expect(response.body.scheduledTaskId).to.eql(undefined); @@ -168,15 +362,10 @@ export default function createAlertTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; - case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': + case 'superuser at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -200,15 +389,10 @@ export default function createAlertTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -236,15 +420,21 @@ export default function createAlertTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.validation', + 'alertsFixture' + ), + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -269,15 +459,10 @@ export default function createAlertTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ error: 'Bad Request', @@ -301,15 +486,10 @@ export default function createAlertTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'global_read at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ error: 'Bad Request', diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/delete.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/delete.ts index 6f8ae010b9cd8..fc453c8da72e7 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/delete.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/delete.ts @@ -6,7 +6,13 @@ import expect from '@kbn/expect'; import { UserAtSpaceScenarios } from '../../scenarios'; -import { getUrlPrefix, getTestAlertData, ObjectRemover } from '../../../common/lib'; +import { + getUrlPrefix, + getTestAlertData, + getConsumerUnauthorizedErrorMessage, + getProducerUnauthorizedErrorMessage, + ObjectRemover, +} from '../../../common/lib'; import { FtrProviderContext } from '../../../common/ftr_provider_context'; // eslint-disable-next-line import/no-default-export @@ -46,11 +52,15 @@ export default function createDeleteTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'delete', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, }); objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); // Ensure task still exists @@ -58,6 +68,185 @@ export default function createDeleteTests({ getService }: FtrProviderContext) { break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + try { + await getScheduledTask(createdAlert.scheduledTaskId); + throw new Error('Should have removed scheduled task'); + } catch (e) { + expect(e.status).to.eql(404); + } + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle delete alert request appropriately when consumer is the same as producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + }) + ) + .expect(200); + + const response = await supertestWithoutAuth + .delete(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'delete', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + // Ensure task still exists + await getScheduledTask(createdAlert.scheduledTaskId); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + try { + await getScheduledTask(createdAlert.scheduledTaskId); + throw new Error('Should have removed scheduled task'); + } catch (e) { + expect(e.status).to.eql(404); + } + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle delete alert request appropriately when consumer is not the producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ alertTypeId: 'test.unrestricted-noop', consumer: 'alertsFixture' }) + ) + .expect(200); + + const response = await supertestWithoutAuth + .delete(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'delete', + 'test.unrestricted-noop', + 'alertsFixture' + ), + statusCode: 403, + }); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + // Ensure task still exists + await getScheduledTask(createdAlert.scheduledTaskId); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'delete', + 'test.unrestricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + // Ensure task still exists + await getScheduledTask(createdAlert.scheduledTaskId); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + try { + await getScheduledTask(createdAlert.scheduledTaskId); + throw new Error('Should have removed scheduled task'); + } catch (e) { + expect(e.status).to.eql(404); + } + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle delete alert request appropriately when consumer is "alerts"', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.noop', + consumer: 'alerts', + }) + ) + .expect(200); + + const response = await supertestWithoutAuth + .delete(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage('delete', 'test.noop', 'alerts'), + statusCode: 403, + }); + break; + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'delete', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + // Ensure task still exists + await getScheduledTask(createdAlert.scheduledTaskId); + break; + case 'superuser at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); try { @@ -91,12 +280,8 @@ export default function createDeleteTests({ getService }: FtrProviderContext) { case 'space_1_all at space2': case 'global_read at space1': case 'space_1_all at space1': - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': case 'superuser at space1': expect(response.body).to.eql({ statusCode: 404, @@ -137,11 +322,15 @@ export default function createDeleteTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'delete', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, }); objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); // Ensure task still exists @@ -149,6 +338,8 @@ export default function createDeleteTests({ getService }: FtrProviderContext) { break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); try { diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/disable.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/disable.ts index 589942a7ac11c..4e4f9053bd24f 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/disable.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/disable.ts @@ -13,6 +13,8 @@ import { getUrlPrefix, getTestAlertData, ObjectRemover, + getConsumerUnauthorizedErrorMessage, + getProducerUnauthorizedErrorMessage, } from '../../../common/lib'; // eslint-disable-next-line import/no-default-export @@ -39,10 +41,32 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte describe(scenario.id, () => { it('should handle disable alert request appropriately', async () => { + const { body: createdAction } = await supertest + .post(`${getUrlPrefix(space.id)}/api/actions/action`) + .set('kbn-xsrf', 'foo') + .send({ + name: 'MY action', + actionTypeId: 'test.noop', + config: {}, + secrets: {}, + }) + .expect(200); + const { body: createdAlert } = await supertest .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) .set('kbn-xsrf', 'foo') - .send(getTestAlertData({ enabled: true })) + .send( + getTestAlertData({ + enabled: true, + actions: [ + { + id: createdAction.id, + group: 'default', + params: {}, + }, + ], + }) + ) .expect(200); objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); @@ -52,17 +76,23 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'disable', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, }); // Ensure task still exists await getScheduledTask(createdAlert.scheduledTaskId); break; + case 'space_1_all_alerts_none_actions at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); try { @@ -84,6 +114,171 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte } }); + it('should handle disable alert request appropriately when consumer is the same as producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + enabled: true, + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getDisableRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'disable', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + try { + await getScheduledTask(createdAlert.scheduledTaskId); + throw new Error('Should have removed scheduled task'); + } catch (e) { + expect(e.status).to.eql(404); + } + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle disable alert request appropriately when consumer is not the producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.unrestricted-noop', + consumer: 'alertsFixture', + enabled: true, + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getDisableRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'disable', + 'test.unrestricted-noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'disable', + 'test.unrestricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + try { + await getScheduledTask(createdAlert.scheduledTaskId); + throw new Error('Should have removed scheduled task'); + } catch (e) { + expect(e.status).to.eql(404); + } + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle disable alert request appropriately when consumer is "alerts"', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.noop', + consumer: 'alerts', + enabled: true, + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getDisableRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage('disable', 'test.noop', 'alerts'), + statusCode: 403, + }); + break; + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'disable', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + try { + await getScheduledTask(createdAlert.scheduledTaskId); + throw new Error('Should have removed scheduled task'); + } catch (e) { + expect(e.status).to.eql(404); + } + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + it('should still be able to disable alert when AAD is broken', async () => { const { body: createdAlert } = await supertest .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) @@ -110,17 +305,23 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'disable', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, }); // Ensure task still exists await getScheduledTask(createdAlert.scheduledTaskId); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); try { @@ -157,14 +358,10 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.body).to.eql({ statusCode: 404, error: 'Not Found', diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/enable.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/enable.ts index 8cb0eeb0092a3..d7f6546bf34a9 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/enable.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/enable.ts @@ -13,6 +13,8 @@ import { getUrlPrefix, getTestAlertData, ObjectRemover, + getConsumerUnauthorizedErrorMessage, + getProducerUnauthorizedErrorMessage, } from '../../../common/lib'; // eslint-disable-next-line import/no-default-export @@ -39,10 +41,32 @@ export default function createEnableAlertTests({ getService }: FtrProviderContex describe(scenario.id, () => { it('should handle enable alert request appropriately', async () => { + const { body: createdAction } = await supertest + .post(`${getUrlPrefix(space.id)}/api/actions/action`) + .set('kbn-xsrf', 'foo') + .send({ + name: 'MY action', + actionTypeId: 'test.noop', + config: {}, + secrets: {}, + }) + .expect(200); + const { body: createdAlert } = await supertest .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) .set('kbn-xsrf', 'foo') - .send(getTestAlertData({ enabled: false })) + .send( + getTestAlertData({ + enabled: false, + actions: [ + { + id: createdAction.id, + group: 'default', + params: {}, + }, + ], + }) + ) .expect(200); objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); @@ -51,16 +75,40 @@ export default function createEnableAlertTests({ getService }: FtrProviderContex switch (scenario.id) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'enable', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'enable', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to execute actions`, + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); const { body: updatedAlert } = await supertestWithoutAuth @@ -89,6 +137,165 @@ export default function createEnableAlertTests({ getService }: FtrProviderContex } }); + it('should handle enable alert request appropriately when consumer is the same as producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + enabled: false, + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getEnableRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'enable', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + try { + await getScheduledTask(createdAlert.scheduledTaskId); + throw new Error('Should have removed scheduled task'); + } catch (e) { + expect(e.status).to.eql(404); + } + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle enable alert request appropriately when consumer is not the producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.unrestricted-noop', + consumer: 'alertsFixture', + enabled: false, + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getEnableRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'enable', + 'test.unrestricted-noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'enable', + 'test.unrestricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle enable alert request appropriately when consumer is "alerts"', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.noop', + consumer: 'alerts', + enabled: false, + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getEnableRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage('enable', 'test.noop', 'alerts'), + statusCode: 403, + }); + break; + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'enable', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + try { + await getScheduledTask(createdAlert.scheduledTaskId); + throw new Error('Should have removed scheduled task'); + } catch (e) { + expect(e.status).to.eql(404); + } + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + it('should still be able to enable alert when AAD is broken', async () => { const { body: createdAlert } = await supertest .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) @@ -115,15 +322,21 @@ export default function createEnableAlertTests({ getService }: FtrProviderContex case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'enable', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); const { body: updatedAlert } = await supertestWithoutAuth @@ -167,14 +380,10 @@ export default function createEnableAlertTests({ getService }: FtrProviderContex case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.body).to.eql({ statusCode: 404, error: 'Not Found', diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/find.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/find.ts index 5fe9edeb91ec9..268212d4294d0 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/find.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/find.ts @@ -5,6 +5,8 @@ */ import expect from '@kbn/expect'; +import { chunk, omit } from 'lodash'; +import uuid from 'uuid'; import { UserAtSpaceScenarios } from '../../scenarios'; import { getUrlPrefix, getTestAlertData, ObjectRemover } from '../../../common/lib'; import { FtrProviderContext } from '../../../common/ftr_provider_context'; @@ -41,16 +43,18 @@ export default function createFindTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: `Unauthorized to find any alert types`, + statusCode: 403, }); break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body.page).to.equal(1); expect(response.body.perPage).to.be.greaterThan(0); @@ -61,7 +65,7 @@ export default function createFindTests({ getService }: FtrProviderContext) { name: 'abc', tags: ['foo'], alertTypeId: 'test.noop', - consumer: 'bar', + consumer: 'alertsFixture', schedule: { interval: '1m' }, enabled: true, actions: [], @@ -84,6 +88,108 @@ export default function createFindTests({ getService }: FtrProviderContext) { } }); + it('should filter out types that the user is not authorized to `get` retaining pagination', async () => { + async function createNoOpAlert(overrides = {}) { + const alert = getTestAlertData(overrides); + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send(alert) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + return { + id: createdAlert.id, + alertTypeId: alert.alertTypeId, + }; + } + function createRestrictedNoOpAlert() { + return createNoOpAlert({ + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + }); + } + function createUnrestrictedNoOpAlert() { + return createNoOpAlert({ + alertTypeId: 'test.unrestricted-noop', + consumer: 'alertsFixture', + }); + } + const allAlerts = []; + allAlerts.push(await createNoOpAlert()); + allAlerts.push(await createNoOpAlert()); + allAlerts.push(await createRestrictedNoOpAlert()); + allAlerts.push(await createUnrestrictedNoOpAlert()); + allAlerts.push(await createUnrestrictedNoOpAlert()); + allAlerts.push(await createRestrictedNoOpAlert()); + allAlerts.push(await createNoOpAlert()); + allAlerts.push(await createNoOpAlert()); + + const perPage = 4; + + const response = await supertestWithoutAuth + .get( + `${getUrlPrefix(space.id)}/api/alerts/_find?per_page=${perPage}&sort_field=createdAt` + ) + .auth(user.username, user.password); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to find any alert types`, + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(200); + expect(response.body.page).to.equal(1); + expect(response.body.perPage).to.be.equal(perPage); + expect(response.body.total).to.be.equal(6); + { + const [firstPage] = chunk( + allAlerts + .filter((alert) => alert.alertTypeId !== 'test.restricted-noop') + .map((alert) => alert.id), + perPage + ); + expect(response.body.data.map((alert: any) => alert.id)).to.eql(firstPage); + } + break; + case 'global_read at space1': + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(200); + expect(response.body.page).to.equal(1); + expect(response.body.perPage).to.be.equal(perPage); + expect(response.body.total).to.be.equal(8); + + { + const [firstPage, secondPage] = chunk( + allAlerts.map((alert) => alert.id), + perPage + ); + expect(response.body.data.map((alert: any) => alert.id)).to.eql(firstPage); + + const secondResponse = await supertestWithoutAuth + .get( + `${getUrlPrefix( + space.id + )}/api/alerts/_find?per_page=${perPage}&sort_field=createdAt&page=2` + ) + .auth(user.username, user.password); + + expect(secondResponse.body.data.map((alert: any) => alert.id)).to.eql(secondPage); + } + + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + it('should handle find alert request with filter appropriately', async () => { const { body: createdAction } = await supertest .post(`${getUrlPrefix(space.id)}/api/actions/action`) @@ -125,16 +231,18 @@ export default function createFindTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: `Unauthorized to find any alert types`, + statusCode: 403, }); break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body.page).to.equal(1); expect(response.body.perPage).to.be.greaterThan(0); @@ -145,7 +253,7 @@ export default function createFindTests({ getService }: FtrProviderContext) { name: 'abc', tags: ['foo'], alertTypeId: 'test.noop', - consumer: 'bar', + consumer: 'alertsFixture', schedule: { interval: '1m' }, enabled: false, actions: [ @@ -174,6 +282,83 @@ export default function createFindTests({ getService }: FtrProviderContext) { } }); + it('should handle find alert request with fields appropriately', async () => { + const myTag = uuid.v4(); + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + tags: [myTag], + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + // create another type with same tag + const { body: createdSecondAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + tags: [myTag], + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdSecondAlert.id, 'alert', 'alerts'); + + const response = await supertestWithoutAuth + .get( + `${getUrlPrefix( + space.id + )}/api/alerts/_find?filter=alert.attributes.alertTypeId:test.restricted-noop&fields=["tags"]&sort_field=createdAt` + ) + .auth(user.username, user.password); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to find any alert types`, + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(200); + expect(response.body.data).to.eql([]); + break; + case 'global_read at space1': + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(200); + expect(response.body.page).to.equal(1); + expect(response.body.perPage).to.be.greaterThan(0); + expect(response.body.total).to.be.greaterThan(0); + const [matchFirst, matchSecond] = response.body.data; + expect(omit(matchFirst, 'updatedAt')).to.eql({ + id: createdAlert.id, + actions: [], + tags: [myTag], + }); + expect(omit(matchSecond, 'updatedAt')).to.eql({ + id: createdSecondAlert.id, + actions: [], + tags: [myTag], + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + it(`shouldn't find alert from another space`, async () => { const { body: createdAlert } = await supertest .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) @@ -192,11 +377,13 @@ export default function createFindTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'space_1_all at space1': - expect(response.statusCode).to.eql(404); + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: `Unauthorized to find any alert types`, + statusCode: 403, }); break; case 'global_read at space1': diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/get.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/get.ts index a203b7d7c151b..1043ece08a2ac 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/get.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/get.ts @@ -6,7 +6,13 @@ import expect from '@kbn/expect'; import { UserAtSpaceScenarios } from '../../scenarios'; -import { getUrlPrefix, getTestAlertData, ObjectRemover } from '../../../common/lib'; +import { + getUrlPrefix, + getTestAlertData, + ObjectRemover, + getConsumerUnauthorizedErrorMessage, + getProducerUnauthorizedErrorMessage, +} from '../../../common/lib'; import { FtrProviderContext } from '../../../common/ftr_provider_context'; // eslint-disable-next-line import/no-default-export @@ -37,23 +43,25 @@ export default function createGetTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage('get', 'test.noop', 'alertsFixture'), + statusCode: 403, }); break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body).to.eql({ id: createdAlert.id, name: 'abc', tags: ['foo'], alertTypeId: 'test.noop', - consumer: 'bar', + consumer: 'alertsFixture', schedule: { interval: '1m' }, enabled: true, actions: [], @@ -76,6 +84,157 @@ export default function createGetTests({ getService }: FtrProviderContext) { } }); + it('should handle get alert request appropriately when consumer is the same as producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .auth(user.username, user.password); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'get', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'global_read at space1': + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(200); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle get alert request appropriately when consumer is not the producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.unrestricted-noop', + consumer: 'alertsFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .auth(user.username, user.password); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'get', + 'test.unrestricted-noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'get', + 'test.unrestricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'global_read at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(200); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle get alert request appropriately when consumer is "alerts"', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.restricted-noop', + consumer: 'alerts', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .auth(user.username, user.password); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'get', + 'test.restricted-noop', + 'alerts' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'get', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'global_read at space1': + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(200); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + it(`shouldn't get alert from another space`, async () => { const { body: createdAlert } = await supertest .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) @@ -93,12 +252,8 @@ export default function createGetTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'space_1_all at space1': - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': case 'global_read at space1': case 'superuser at space1': expect(response.body).to.eql({ @@ -120,16 +275,11 @@ export default function createGetTests({ getService }: FtrProviderContext) { switch (scenario.id) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(404); expect(response.body).to.eql({ statusCode: 404, diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/get_alert_state.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/get_alert_state.ts index fd071bd55b377..2e89aa2961c73 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/get_alert_state.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/get_alert_state.ts @@ -5,7 +5,13 @@ */ import expect from '@kbn/expect'; -import { getUrlPrefix, ObjectRemover, getTestAlertData } from '../../../common/lib'; +import { + getUrlPrefix, + ObjectRemover, + getTestAlertData, + getConsumerUnauthorizedErrorMessage, + getProducerUnauthorizedErrorMessage, +} from '../../../common/lib'; import { FtrProviderContext } from '../../../common/ftr_provider_context'; import { UserAtSpaceScenarios } from '../../scenarios'; @@ -37,16 +43,73 @@ export default function createGetAlertStateTests({ getService }: FtrProviderCont switch (scenario.id) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage('get', 'test.noop', 'alertsFixture'), + statusCode: 403, }); break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(200); + expect(response.body).to.key('alertInstances', 'previousStartedAt'); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle getAlertState alert request appropriately when unauthorized', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.unrestricted-noop', + consumer: 'alertsFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}/state`) + .auth(user.username, user.password); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'get', + 'test.unrestricted-noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'get', + 'test.unrestricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'global_read at space1': + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body).to.key('alertInstances', 'previousStartedAt'); break; @@ -72,12 +135,8 @@ export default function createGetAlertStateTests({ getService }: FtrProviderCont case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'space_1_all at space1': - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': case 'global_read at space1': case 'superuser at space1': expect(response.body).to.eql({ @@ -99,16 +158,11 @@ export default function createGetAlertStateTests({ getService }: FtrProviderCont switch (scenario.id) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'global_read at space1': case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(404); expect(response.body).to.eql({ statusCode: 404, diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/index.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/index.ts index f14f66f66fe2f..4cd5f0805121c 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/index.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/index.ts @@ -9,11 +9,11 @@ import { FtrProviderContext } from '../../../common/ftr_provider_context'; // eslint-disable-next-line import/no-default-export export default function alertingTests({ loadTestFile }: FtrProviderContext) { describe('Alerts', () => { + loadTestFile(require.resolve('./find')); loadTestFile(require.resolve('./create')); loadTestFile(require.resolve('./delete')); loadTestFile(require.resolve('./disable')); loadTestFile(require.resolve('./enable')); - loadTestFile(require.resolve('./find')); loadTestFile(require.resolve('./get')); loadTestFile(require.resolve('./get_alert_state')); loadTestFile(require.resolve('./list_alert_types')); diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/list_alert_types.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/list_alert_types.ts index dd31e2dbbb5b8..ad60ed6941caf 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/list_alert_types.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/list_alert_types.ts @@ -5,6 +5,7 @@ */ import expect from '@kbn/expect'; +import { omit } from 'lodash'; import { UserAtSpaceScenarios } from '../../scenarios'; import { getUrlPrefix } from '../../../common/lib/space_test_utils'; import { FtrProviderContext } from '../../../common/ftr_provider_context'; @@ -13,42 +14,127 @@ import { FtrProviderContext } from '../../../common/ftr_provider_context'; export default function listAlertTypes({ getService }: FtrProviderContext) { const supertestWithoutAuth = getService('supertestWithoutAuth'); + const expectedNoOpType = { + actionGroups: [{ id: 'default', name: 'Default' }], + defaultActionGroupId: 'default', + id: 'test.noop', + name: 'Test: Noop', + actionVariables: { + state: [], + context: [], + params: [], + }, + producer: 'alertsFixture', + }; + + const expectedRestrictedNoOpType = { + actionGroups: [{ id: 'default', name: 'Default' }], + defaultActionGroupId: 'default', + id: 'test.restricted-noop', + name: 'Test: Restricted Noop', + actionVariables: { + state: [], + context: [], + params: [], + }, + producer: 'alertsRestrictedFixture', + }; + describe('list_alert_types', () => { for (const scenario of UserAtSpaceScenarios) { const { user, space } = scenario; describe(scenario.id, () => { - it('should return 200 with list of alert types', async () => { + it('should return 200 with list of globally available alert types', async () => { const response = await supertestWithoutAuth .get(`${getUrlPrefix(space.id)}/api/alerts/list_alert_types`) .auth(user.username, user.password); + expect(response.statusCode).to.eql(200); + const noOpAlertType = response.body.find( + (alertType: any) => alertType.id === 'test.noop' + ); + const restrictedNoOpAlertType = response.body.find( + (alertType: any) => alertType.id === 'test.restricted-noop' + ); switch (scenario.id) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + expect(response.body).to.eql([]); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(omit(noOpAlertType, 'authorizedConsumers')).to.eql(expectedNoOpType); + expect(restrictedNoOpAlertType).to.eql(undefined); + expect(noOpAlertType.authorizedConsumers).to.eql({ + alerts: { read: true, all: true }, + alertsFixture: { read: true, all: true }, }); break; case 'global_read at space1': + expect(omit(noOpAlertType, 'authorizedConsumers')).to.eql(expectedNoOpType); + expect(noOpAlertType.authorizedConsumers.alertsFixture).to.eql({ + read: true, + all: false, + }); + expect(noOpAlertType.authorizedConsumers.alertsRestrictedFixture).to.eql({ + read: true, + all: false, + }); + + expect(omit(restrictedNoOpAlertType, 'authorizedConsumers')).to.eql( + expectedRestrictedNoOpType + ); + expect(Object.keys(restrictedNoOpAlertType.authorizedConsumers)).not.to.contain( + 'alertsFixture' + ); + expect(restrictedNoOpAlertType.authorizedConsumers.alertsRestrictedFixture).to.eql({ + read: true, + all: false, + }); + break; + case 'space_1_all_with_restricted_fixture at space1': + expect(omit(noOpAlertType, 'authorizedConsumers')).to.eql(expectedNoOpType); + expect(noOpAlertType.authorizedConsumers.alertsFixture).to.eql({ + read: true, + all: true, + }); + expect(noOpAlertType.authorizedConsumers.alertsRestrictedFixture).to.eql({ + read: true, + all: true, + }); + + expect(omit(restrictedNoOpAlertType, 'authorizedConsumers')).to.eql( + expectedRestrictedNoOpType + ); + expect(Object.keys(restrictedNoOpAlertType.authorizedConsumers)).not.to.contain( + 'alertsFixture' + ); + expect(restrictedNoOpAlertType.authorizedConsumers.alertsRestrictedFixture).to.eql({ + read: true, + all: true, + }); + break; case 'superuser at space1': - case 'space_1_all at space1': - expect(response.statusCode).to.eql(200); - const fixtureAlertType = response.body.find( - (alertType: any) => alertType.id === 'test.noop' + expect(omit(noOpAlertType, 'authorizedConsumers')).to.eql(expectedNoOpType); + expect(noOpAlertType.authorizedConsumers.alertsFixture).to.eql({ + read: true, + all: true, + }); + expect(noOpAlertType.authorizedConsumers.alertsRestrictedFixture).to.eql({ + read: true, + all: true, + }); + + expect(omit(restrictedNoOpAlertType, 'authorizedConsumers')).to.eql( + expectedRestrictedNoOpType ); - expect(fixtureAlertType).to.eql({ - actionGroups: [{ id: 'default', name: 'Default' }], - defaultActionGroupId: 'default', - id: 'test.noop', - name: 'Test: Noop', - actionVariables: { - state: [], - context: [], - }, - producer: 'alerting', + expect(noOpAlertType.authorizedConsumers.alertsFixture).to.eql({ + read: true, + all: true, + }); + expect(noOpAlertType.authorizedConsumers.alertsRestrictedFixture).to.eql({ + read: true, + all: true, }); break; default: diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/mute_all.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/mute_all.ts index 2416bc2ea1d12..a497affa266e4 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/mute_all.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/mute_all.ts @@ -13,6 +13,8 @@ import { getUrlPrefix, getTestAlertData, ObjectRemover, + getConsumerUnauthorizedErrorMessage, + getProducerUnauthorizedErrorMessage, } from '../../../common/lib'; // eslint-disable-next-line import/no-default-export @@ -31,10 +33,151 @@ export default function createMuteAlertTests({ getService }: FtrProviderContext) describe(scenario.id, () => { it('should handle mute alert request appropriately', async () => { + const { body: createdAction } = await supertest + .post(`${getUrlPrefix(space.id)}/api/actions/action`) + .set('kbn-xsrf', 'foo') + .send({ + name: 'MY action', + actionTypeId: 'test.noop', + config: {}, + secrets: {}, + }) + .expect(200); + + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + actions: [ + { + id: createdAction.id, + group: 'default', + params: {}, + }, + ], + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getMuteAllRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'muteAll', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to execute actions`, + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.muteAll).to.eql(true); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle mute alert request appropriately when consumer is the same as producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getMuteAllRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'muteAll', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.muteAll).to.eql(true); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle mute alert request appropriately when consumer is not the producer', async () => { const { body: createdAlert } = await supertest .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) .set('kbn-xsrf', 'foo') - .send(getTestAlertData({ enabled: false })) + .send( + getTestAlertData({ + enabled: false, + alertTypeId: 'test.unrestricted-noop', + consumer: 'alertsFixture', + }) + ) .expect(200); objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); @@ -44,15 +187,99 @@ export default function createMuteAlertTests({ getService }: FtrProviderContext) case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'muteAll', + 'test.unrestricted-noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'muteAll', + 'test.unrestricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, }); break; case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.muteAll).to.eql(true); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle mute alert request appropriately when consumer is "alerts"', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + alertTypeId: 'test.restricted-noop', + consumer: 'alerts', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getMuteAllRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'muteAll', + 'test.restricted-noop', + 'alerts' + ), + statusCode: 403, + }); + break; + case 'global_read at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'muteAll', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); const { body: updatedAlert } = await supertestWithoutAuth diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/mute_instance.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/mute_instance.ts index c59b9f4503a03..b4277479d8fd9 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/mute_instance.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/mute_instance.ts @@ -13,6 +13,8 @@ import { getUrlPrefix, getTestAlertData, ObjectRemover, + getConsumerUnauthorizedErrorMessage, + getProducerUnauthorizedErrorMessage, } from '../../../common/lib'; // eslint-disable-next-line import/no-default-export @@ -31,10 +33,32 @@ export default function createMuteAlertInstanceTests({ getService }: FtrProvider describe(scenario.id, () => { it('should handle mute alert instance request appropriately', async () => { + const { body: createdAction } = await supertest + .post(`${getUrlPrefix(space.id)}/api/actions/action`) + .set('kbn-xsrf', 'foo') + .send({ + name: 'MY action', + actionTypeId: 'test.noop', + config: {}, + secrets: {}, + }) + .expect(200); + const { body: createdAlert } = await supertest .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) .set('kbn-xsrf', 'foo') - .send(getTestAlertData({ enabled: false })) + .send( + getTestAlertData({ + enabled: false, + actions: [ + { + id: createdAction.id, + group: 'default', + params: {}, + }, + ], + }) + ) .expect(200); objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); @@ -44,15 +68,218 @@ export default function createMuteAlertInstanceTests({ getService }: FtrProvider case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'muteInstance', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to execute actions`, + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.mutedInstanceIds).to.eql(['1']); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle mute alert instance request appropriately when consumer is the same as producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getMuteInstanceRequest(createdAlert.id, '1'); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'muteInstance', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.mutedInstanceIds).to.eql(['1']); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle mute alert instance request appropriately when consumer is not the producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + alertTypeId: 'test.unrestricted-noop', + consumer: 'alertsFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getMuteInstanceRequest(createdAlert.id, '1'); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'muteInstance', + 'test.unrestricted-noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'muteInstance', + 'test.unrestricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.mutedInstanceIds).to.eql(['1']); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle mute alert instance request appropriately when consumer is "alerts"', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + alertTypeId: 'test.restricted-noop', + consumer: 'alerts', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getMuteInstanceRequest(createdAlert.id, '1'); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'muteInstance', + 'test.restricted-noop', + 'alerts' + ), + statusCode: 403, + }); + break; + case 'global_read at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'muteInstance', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); const { body: updatedAlert } = await supertestWithoutAuth @@ -95,15 +322,21 @@ export default function createMuteAlertInstanceTests({ getService }: FtrProvider case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'muteInstance', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); const { body: updatedAlert } = await supertestWithoutAuth diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/unmute_all.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/unmute_all.ts index fd22752ccc11a..46653900cb1c7 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/unmute_all.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/unmute_all.ts @@ -13,6 +13,8 @@ import { getUrlPrefix, getTestAlertData, ObjectRemover, + getConsumerUnauthorizedErrorMessage, + getProducerUnauthorizedErrorMessage, } from '../../../common/lib'; // eslint-disable-next-line import/no-default-export @@ -31,10 +33,32 @@ export default function createUnmuteAlertTests({ getService }: FtrProviderContex describe(scenario.id, () => { it('should handle unmute alert request appropriately', async () => { + const { body: createdAction } = await supertest + .post(`${getUrlPrefix(space.id)}/api/actions/action`) + .set('kbn-xsrf', 'foo') + .send({ + name: 'MY action', + actionTypeId: 'test.noop', + config: {}, + secrets: {}, + }) + .expect(200); + const { body: createdAlert } = await supertest .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) .set('kbn-xsrf', 'foo') - .send(getTestAlertData({ enabled: false })) + .send( + getTestAlertData({ + enabled: false, + actions: [ + { + id: createdAction.id, + group: 'default', + params: {}, + }, + ], + }) + ) .expect(200); objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); @@ -49,15 +73,233 @@ export default function createUnmuteAlertTests({ getService }: FtrProviderContex case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'unmuteAll', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to execute actions`, + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.muteAll).to.eql(false); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle unmute alert request appropriately when consumer is the same as producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}/_mute_all`) + .set('kbn-xsrf', 'foo') + .expect(204, ''); + + const response = await alertUtils.getUnmuteAllRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'unmuteAll', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.muteAll).to.eql(false); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle unmute alert request appropriately when consumer is not the producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + alertTypeId: 'test.unrestricted-noop', + consumer: 'alertsFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}/_mute_all`) + .set('kbn-xsrf', 'foo') + .expect(204, ''); + + const response = await alertUtils.getUnmuteAllRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'unmuteAll', + 'test.unrestricted-noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'unmuteAll', + 'test.unrestricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.muteAll).to.eql(false); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle unmute alert request appropriately when consumer is "alerts"', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + alertTypeId: 'test.restricted-noop', + consumer: 'alerts', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}/_mute_all`) + .set('kbn-xsrf', 'foo') + .expect(204, ''); + + const response = await alertUtils.getUnmuteAllRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'unmuteAll', + 'test.restricted-noop', + 'alerts' + ), + statusCode: 403, + }); + break; + case 'global_read at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'unmuteAll', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); const { body: updatedAlert } = await supertestWithoutAuth diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/unmute_instance.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/unmute_instance.ts index 72b524282354a..2bc501c9a7c72 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/unmute_instance.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/unmute_instance.ts @@ -13,6 +13,8 @@ import { getUrlPrefix, getTestAlertData, ObjectRemover, + getConsumerUnauthorizedErrorMessage, + getProducerUnauthorizedErrorMessage, } from '../../../common/lib'; // eslint-disable-next-line import/no-default-export @@ -31,10 +33,32 @@ export default function createMuteAlertInstanceTests({ getService }: FtrProvider describe(scenario.id, () => { it('should handle unmute alert instance request appropriately', async () => { + const { body: createdAction } = await supertest + .post(`${getUrlPrefix(space.id)}/api/actions/action`) + .set('kbn-xsrf', 'foo') + .send({ + name: 'MY action', + actionTypeId: 'test.noop', + config: {}, + secrets: {}, + }) + .expect(200); + const { body: createdAlert } = await supertest .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) .set('kbn-xsrf', 'foo') - .send(getTestAlertData({ enabled: false })) + .send( + getTestAlertData({ + enabled: false, + actions: [ + { + id: createdAction.id, + group: 'default', + params: {}, + }, + ], + }) + ) .expect(200); objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); @@ -51,15 +75,239 @@ export default function createMuteAlertInstanceTests({ getService }: FtrProvider case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'unmuteInstance', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: `Unauthorized to execute actions`, + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.mutedInstanceIds).to.eql([]); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle unmute alert instance request appropriately when consumer is the same as producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + await supertest + .post( + `${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}/alert_instance/1/_mute` + ) + .set('kbn-xsrf', 'foo') + .expect(204, ''); + + const response = await alertUtils.getUnmuteInstanceRequest(createdAlert.id, '1'); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'unmuteInstance', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.mutedInstanceIds).to.eql([]); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle unmute alert instance request appropriately when consumer is not the producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + alertTypeId: 'test.unrestricted-noop', + consumer: 'alertsFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + await supertest + .post( + `${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}/alert_instance/1/_mute` + ) + .set('kbn-xsrf', 'foo') + .expect(204, ''); + + const response = await alertUtils.getUnmuteInstanceRequest(createdAlert.id, '1'); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'unmuteInstance', + 'test.unrestricted-noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'unmuteInstance', + 'test.unrestricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.mutedInstanceIds).to.eql([]); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle unmute alert instance request appropriately when consumer is "alerts"', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + enabled: false, + alertTypeId: 'test.restricted-noop', + consumer: 'alerts', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + await supertest + .post( + `${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}/alert_instance/1/_mute` + ) + .set('kbn-xsrf', 'foo') + .expect(204, ''); + + const response = await alertUtils.getUnmuteInstanceRequest(createdAlert.id, '1'); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'unmuteInstance', + 'test.restricted-noop', + 'alerts' + ), + statusCode: 403, + }); + break; + case 'global_read at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'unmuteInstance', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); const { body: updatedAlert } = await supertestWithoutAuth diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/update.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/update.ts index 2bcc035beb7a9..cac6355409ac9 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/update.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/update.ts @@ -13,6 +13,8 @@ import { getTestAlertData, ObjectRemover, ensureDatetimeIsWithinRange, + getConsumerUnauthorizedErrorMessage, + getProducerUnauthorizedErrorMessage, } from '../../../common/lib'; import { FtrProviderContext } from '../../../common/ftr_provider_context'; @@ -29,7 +31,8 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { .then((response: SupertestResponse) => response.body); } - describe('update', () => { + // FLAKY: https://github.com/elastic/kibana/issues/72803 + describe.skip('update', () => { const objectRemover = new ObjectRemover(supertest); after(() => objectRemover.removeAll()); @@ -38,6 +41,17 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { const { user, space } = scenario; describe(scenario.id, () => { it('should handle update alert request appropriately', async () => { + const { body: createdAction } = await supertest + .post(`${getUrlPrefix(space.id)}/api/actions/action`) + .set('kbn-xsrf', 'foo') + .send({ + name: 'MY action', + actionTypeId: 'test.noop', + config: {}, + secrets: {}, + }) + .expect(200); + const { body: createdAlert } = await supertest .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) .set('kbn-xsrf', 'foo') @@ -52,7 +66,13 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { foo: true, }, schedule: { interval: '12s' }, - actions: [], + actions: [ + { + id: createdAction.id, + group: 'default', + params: {}, + }, + ], throttle: '1m', }; const response = await supertestWithoutAuth @@ -65,21 +85,310 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'update', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to get actions`, + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body).to.eql({ ...updatedData, id: createdAlert.id, alertTypeId: 'test.noop', - consumer: 'bar', + consumer: 'alertsFixture', + createdBy: 'elastic', + enabled: true, + updatedBy: user.username, + apiKeyOwner: user.username, + muteAll: false, + mutedInstanceIds: [], + actions: [ + { + id: createdAction.id, + actionTypeId: 'test.noop', + group: 'default', + params: {}, + }, + ], + scheduledTaskId: createdAlert.scheduledTaskId, + createdAt: response.body.createdAt, + updatedAt: response.body.updatedAt, + }); + expect(Date.parse(response.body.createdAt)).to.be.greaterThan(0); + expect(Date.parse(response.body.updatedAt)).to.be.greaterThan(0); + expect(Date.parse(response.body.updatedAt)).to.be.greaterThan( + Date.parse(response.body.createdAt) + ); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle update alert request appropriately when consumer is the same as producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const updatedData = { + name: 'bcd', + tags: ['bar'], + params: { + foo: true, + }, + schedule: { interval: '12s' }, + actions: [], + throttle: '1m', + }; + const response = await supertestWithoutAuth + .put(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .send(updatedData); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'update', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(200); + expect(response.body).to.eql({ + ...updatedData, + id: createdAlert.id, + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + createdBy: 'elastic', + enabled: true, + updatedBy: user.username, + apiKeyOwner: user.username, + muteAll: false, + mutedInstanceIds: [], + scheduledTaskId: createdAlert.scheduledTaskId, + createdAt: response.body.createdAt, + updatedAt: response.body.updatedAt, + }); + expect(Date.parse(response.body.createdAt)).to.be.greaterThan(0); + expect(Date.parse(response.body.updatedAt)).to.be.greaterThan(0); + expect(Date.parse(response.body.updatedAt)).to.be.greaterThan( + Date.parse(response.body.createdAt) + ); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle update alert request appropriately when consumer is not the producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.unrestricted-noop', + consumer: 'alertsFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const updatedData = { + name: 'bcd', + tags: ['bar'], + params: { + foo: true, + }, + schedule: { interval: '12s' }, + actions: [], + throttle: '1m', + }; + const response = await supertestWithoutAuth + .put(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .send(updatedData); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'update', + 'test.unrestricted-noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'update', + 'test.unrestricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(200); + expect(response.body).to.eql({ + ...updatedData, + id: createdAlert.id, + alertTypeId: 'test.unrestricted-noop', + consumer: 'alertsFixture', + createdBy: 'elastic', + enabled: true, + updatedBy: user.username, + apiKeyOwner: user.username, + muteAll: false, + mutedInstanceIds: [], + scheduledTaskId: createdAlert.scheduledTaskId, + createdAt: response.body.createdAt, + updatedAt: response.body.updatedAt, + }); + expect(Date.parse(response.body.createdAt)).to.be.greaterThan(0); + expect(Date.parse(response.body.updatedAt)).to.be.greaterThan(0); + expect(Date.parse(response.body.updatedAt)).to.be.greaterThan( + Date.parse(response.body.createdAt) + ); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle update alert request appropriately when consumer is "alerts"', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.restricted-noop', + consumer: 'alerts', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const updatedData = { + name: 'bcd', + tags: ['bar'], + params: { + foo: true, + }, + schedule: { interval: '12s' }, + actions: [], + throttle: '1m', + }; + const response = await supertestWithoutAuth + .put(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .send(updatedData); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'update', + 'test.restricted-noop', + 'alerts' + ), + statusCode: 403, + }); + break; + case 'global_read at space1': + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'update', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(200); + expect(response.body).to.eql({ + ...updatedData, + id: createdAlert.id, + alertTypeId: 'test.restricted-noop', + consumer: 'alerts', createdBy: 'elastic', enabled: true, updatedBy: user.username, @@ -148,21 +457,27 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'update', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); expect(response.body).to.eql({ ...updatedData, id: createdAlert.id, alertTypeId: 'test.noop', - consumer: 'bar', + consumer: 'alertsFixture', createdBy: 'elastic', enabled: true, updatedBy: user.username, @@ -220,12 +535,8 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { case 'space_1_all at space2': case 'global_read at space1': case 'space_1_all at space1': - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': case 'superuser at space1': expect(response.body).to.eql({ statusCode: 404, @@ -266,15 +577,10 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -298,15 +604,10 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -351,15 +652,21 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'update', + 'test.validation', + 'alertsFixture' + ), + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -390,15 +697,10 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(400); expect(response.body).to.eql({ statusCode: 400, @@ -450,15 +752,21 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'update', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(200); await retry.try(async () => { const alertTask = (await getAlertingTaskById(createdAlert.scheduledTaskId)).docs[0]; diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/update_api_key.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/update_api_key.ts index bf72b970dc0f1..7dea591b895ee 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/update_api_key.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/update_api_key.ts @@ -13,6 +13,8 @@ import { getUrlPrefix, getTestAlertData, ObjectRemover, + getConsumerUnauthorizedErrorMessage, + getProducerUnauthorizedErrorMessage, } from '../../../common/lib'; // eslint-disable-next-line import/no-default-export @@ -31,28 +33,245 @@ export default function createUpdateApiKeyTests({ getService }: FtrProviderConte describe(scenario.id, () => { it('should handle update alert api key request appropriately', async () => { + const { body: createdAction } = await supertest + .post(`${getUrlPrefix(space.id)}/api/actions/action`) + .set('kbn-xsrf', 'foo') + .send({ + name: 'MY action', + actionTypeId: 'test.noop', + config: {}, + secrets: {}, + }) + .expect(200); + const { body: createdAlert } = await supertest .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) .set('kbn-xsrf', 'foo') - .send(getTestAlertData()) + .send( + getTestAlertData({ + actions: [ + { + id: createdAction.id, + group: 'default', + params: {}, + }, + ], + }) + ) .expect(200); objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); const response = await alertUtils.getUpdateApiKeyRequest(createdAlert.id); + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'updateApiKey', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: `Unauthorized to execute actions`, + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.apiKeyOwner).to.eql(user.username); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + it('should handle update alert api key request appropriately when consumer is the same as producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.restricted-noop', + consumer: 'alertsRestrictedFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getUpdateApiKeyRequest(createdAlert.id); switch (scenario.id) { case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'updateApiKey', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.apiKeyOwner).to.eql(user.username); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle update alert api key request appropriately when consumer is not the producer', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.unrestricted-noop', + consumer: 'alertsFixture', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getUpdateApiKeyRequest(createdAlert.id); + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'updateApiKey', + 'test.unrestricted-noop', + 'alertsFixture' + ), + statusCode: 403, + }); + break; + case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'updateApiKey', + 'test.unrestricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, }); break; case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alerts/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(updatedAlert.apiKeyOwner).to.eql(user.username); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + + it('should handle update alert api key request appropriately when consumer is "alerts"', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send( + getTestAlertData({ + alertTypeId: 'test.restricted-noop', + consumer: 'alerts', + }) + ) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts'); + + const response = await alertUtils.getUpdateApiKeyRequest(createdAlert.id); + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'updateApiKey', + 'test.restricted-noop', + 'alerts' + ), + statusCode: 403, + }); + break; + case 'global_read at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + expect(response.statusCode).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getProducerUnauthorizedErrorMessage( + 'updateApiKey', + 'test.restricted-noop', + 'alertsRestrictedFixture' + ), + statusCode: 403, + }); + break; + case 'superuser at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); const { body: updatedAlert } = await supertestWithoutAuth @@ -100,15 +319,21 @@ export default function createUpdateApiKeyTests({ getService }: FtrProviderConte case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.statusCode).to.eql(404); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'updateApiKey', + 'test.noop', + 'alertsFixture' + ), + statusCode: 403, }); break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.statusCode).to.eql(204); expect(response.body).to.eql(''); const { body: updatedAlert } = await supertestWithoutAuth @@ -145,14 +370,10 @@ export default function createUpdateApiKeyTests({ getService }: FtrProviderConte case 'no_kibana_privileges at space1': case 'space_1_all at space2': case 'global_read at space1': - expect(response.body).to.eql({ - statusCode: 404, - error: 'Not Found', - message: 'Not Found', - }); - break; case 'superuser at space1': case 'space_1_all at space1': + case 'space_1_all_alerts_none_actions at space1': + case 'space_1_all_with_restricted_fixture at space1': expect(response.body).to.eql({ statusCode: 404, error: 'Not Found', diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/alert.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/alert.ts index 8412c09eefcda..92db0458c0639 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/alert.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/alert.ts @@ -346,7 +346,7 @@ export default function alertTests({ getService }: FtrProviderContext) { .set('kbn-xsrf', 'foo') .send({ name: params.name, - consumer: 'function test', + consumer: 'alerts', enabled: true, alertTypeId: ALERT_TYPE_ID, schedule: { interval: `${ALERT_INTERVAL_SECONDS}s` }, diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/create.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/create.ts index fa256712a012b..86775f77a7671 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/create.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/create.ts @@ -6,7 +6,13 @@ import expect from '@kbn/expect'; import { Spaces } from '../../scenarios'; -import { checkAAD, getUrlPrefix, getTestAlertData, ObjectRemover } from '../../../common/lib'; +import { + checkAAD, + getUrlPrefix, + getTestAlertData, + ObjectRemover, + getConsumerUnauthorizedErrorMessage, +} from '../../../common/lib'; import { FtrProviderContext } from '../../../common/ftr_provider_context'; // eslint-disable-next-line import/no-default-export @@ -69,7 +75,7 @@ export default function createAlertTests({ getService }: FtrProviderContext) { ], enabled: true, alertTypeId: 'test.noop', - consumer: 'bar', + consumer: 'alertsFixture', params: {}, createdBy: null, schedule: { interval: '1m' }, @@ -102,6 +108,24 @@ export default function createAlertTests({ getService }: FtrProviderContext) { }); }); + it('should handle create alert request appropriately when consumer is unknown', async () => { + const response = await supertest + .post(`${getUrlPrefix(Spaces.space1.id)}/api/alerts/alert`) + .set('kbn-xsrf', 'foo') + .send(getTestAlertData({ consumer: 'some consumer patrick invented' })); + + expect(response.status).to.eql(403); + expect(response.body).to.eql({ + error: 'Forbidden', + message: getConsumerUnauthorizedErrorMessage( + 'create', + 'test.noop', + 'some consumer patrick invented' + ), + statusCode: 403, + }); + }); + it('should handle create alert request appropriately when an alert is disabled ', async () => { const response = await supertest .post(`${getUrlPrefix(Spaces.space1.id)}/api/alerts/alert`) diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/find.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/find.ts index 06f27d666c3da..b28ce89b30472 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/find.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/find.ts @@ -42,7 +42,7 @@ export default function createFindTests({ getService }: FtrProviderContext) { name: 'abc', tags: ['foo'], alertTypeId: 'test.noop', - consumer: 'bar', + consumer: 'alertsFixture', schedule: { interval: '1m' }, enabled: true, actions: [], diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/get.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/get.ts index ff671e16654b5..165eaa09126a8 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/get.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/get.ts @@ -36,7 +36,7 @@ export default function createGetTests({ getService }: FtrProviderContext) { name: 'abc', tags: ['foo'], alertTypeId: 'test.noop', - consumer: 'bar', + consumer: 'alertsFixture', schedule: { interval: '1m' }, enabled: true, actions: [], diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/get_alert_state.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/get_alert_state.ts index d3f08d7c509a0..e3f87a9be00ba 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/get_alert_state.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/get_alert_state.ts @@ -44,7 +44,7 @@ export default function createGetAlertStateTests({ getService }: FtrProviderCont name: 'abc', tags: ['foo'], alertTypeId: 'test.cumulative-firing', - consumer: 'bar', + consumer: 'alertsFixture', schedule: { interval: '5s' }, throttle: '5s', actions: [], diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/index.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/index.ts index 0970738b630c4..a23f0fa835313 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/index.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/index.ts @@ -27,8 +27,5 @@ export default function alertingTests({ loadTestFile }: FtrProviderContext) { loadTestFile(require.resolve('./alerts_space1')); loadTestFile(require.resolve('./alerts_default_space')); loadTestFile(require.resolve('./builtin_alert_types')); - - // note that this test will destroy existing spaces - loadTestFile(require.resolve('./migrations')); }); } diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/list_alert_types.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/list_alert_types.ts index aef87eefba2ad..6fb573c7344b3 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/list_alert_types.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/list_alert_types.ts @@ -19,7 +19,9 @@ export default function listAlertTypes({ getService }: FtrProviderContext) { `${getUrlPrefix(Spaces.space1.id)}/api/alerts/list_alert_types` ); expect(response.status).to.eql(200); - const fixtureAlertType = response.body.find((alertType: any) => alertType.id === 'test.noop'); + const { authorizedConsumers, ...fixtureAlertType } = response.body.find( + (alertType: any) => alertType.id === 'test.noop' + ); expect(fixtureAlertType).to.eql({ actionGroups: [{ id: 'default', name: 'Default' }], defaultActionGroupId: 'default', @@ -27,10 +29,12 @@ export default function listAlertTypes({ getService }: FtrProviderContext) { name: 'Test: Noop', actionVariables: { state: [], + params: [], context: [], }, - producer: 'alerting', + producer: 'alertsFixture', }); + expect(Object.keys(authorizedConsumers)).to.contain('alertsFixture'); }); it('should return actionVariables with both context and state', async () => { @@ -45,6 +49,7 @@ export default function listAlertTypes({ getService }: FtrProviderContext) { expect(fixtureAlertType.actionVariables).to.eql({ state: [{ name: 'instanceStateValue', description: 'the instance state value' }], + params: [{ name: 'instanceParamsValue', description: 'the instance params value' }], context: [{ name: 'instanceContextValue', description: 'the instance context value' }], }); }); @@ -61,6 +66,7 @@ export default function listAlertTypes({ getService }: FtrProviderContext) { expect(fixtureAlertType.actionVariables).to.eql({ state: [], + params: [], context: [{ name: 'aContextVariable', description: 'this is a context variable' }], }); }); @@ -78,6 +84,7 @@ export default function listAlertTypes({ getService }: FtrProviderContext) { expect(fixtureAlertType.actionVariables).to.eql({ state: [{ name: 'aStateVariable', description: 'this is a state variable' }], context: [], + params: [], }); }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/migrations.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/migrations.ts deleted file mode 100644 index fc61f59d129d7..0000000000000 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/migrations.ts +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import { getUrlPrefix } from '../../../common/lib'; -import { FtrProviderContext } from '../../../common/ftr_provider_context'; - -// eslint-disable-next-line import/no-default-export -export default function createGetTests({ getService }: FtrProviderContext) { - const supertest = getService('supertest'); - const esArchiver = getService('esArchiver'); - - describe('migrations', () => { - before(async () => { - await esArchiver.load('alerts'); - }); - - after(async () => { - await esArchiver.unload('alerts'); - }); - - it('7.9.0 migrates the `alerting` consumer to be the `alerts`', async () => { - const response = await supertest.get( - `${getUrlPrefix(``)}/api/alerts/alert/74f3e6d7-b7bb-477d-ac28-92ee22728e6e` - ); - - expect(response.status).to.eql(200); - expect(response.body.consumer).to.equal('alerts'); - }); - }); -} diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/update.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/update.ts index b01a1b140f2d6..9c8e6f6b8d94c 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/update.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/update.ts @@ -47,7 +47,7 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { id: createdAlert.id, tags: ['bar'], alertTypeId: 'test.noop', - consumer: 'bar', + consumer: 'alertsFixture', createdBy: null, enabled: true, updatedBy: null, diff --git a/x-pack/test/api_integration/apis/endpoint/index.ts b/x-pack/test/api_integration/apis/endpoint/index.ts deleted file mode 100644 index 5ada2bd094d4b..0000000000000 --- a/x-pack/test/api_integration/apis/endpoint/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { FtrProviderContext } from '../../ftr_provider_context'; - -export default function endpointAPIIntegrationTests({ - loadTestFile, - getService, -}: FtrProviderContext) { - describe('Endpoint plugin', function () { - const ingestManager = getService('ingestManager'); - this.tags(['endpoint']); - before(async () => { - await ingestManager.setup(); - }); - loadTestFile(require.resolve('./resolver')); - loadTestFile(require.resolve('./metadata')); - loadTestFile(require.resolve('./policy')); - }); -} diff --git a/x-pack/test/api_integration/apis/features/features/features.ts b/x-pack/test/api_integration/apis/features/features/features.ts index df6eca795f801..9c44bfeb810fa 100644 --- a/x-pack/test/api_integration/apis/features/features/features.ts +++ b/x-pack/test/api_integration/apis/features/features/features.ts @@ -97,6 +97,7 @@ export default function ({ getService }: FtrProviderContext) { 'visualize', 'dashboard', 'dev_tools', + 'actions', 'enterpriseSearch', 'advancedSettings', 'indexPatterns', @@ -106,6 +107,7 @@ export default function ({ getService }: FtrProviderContext) { 'savedObjectsManagement', 'ml', 'apm', + 'builtInAlerts', 'canvas', 'infrastructure', 'logs', diff --git a/x-pack/test/api_integration/apis/index.js b/x-pack/test/api_integration/apis/index.js index ce0e534d8a750..23532d1311754 100644 --- a/x-pack/test/api_integration/apis/index.js +++ b/x-pack/test/api_integration/apis/index.js @@ -26,11 +26,8 @@ export default function ({ loadTestFile }) { loadTestFile(require.resolve('./security_solution')); loadTestFile(require.resolve('./short_urls')); loadTestFile(require.resolve('./lens')); - loadTestFile(require.resolve('./fleet')); loadTestFile(require.resolve('./ml')); loadTestFile(require.resolve('./transform')); - loadTestFile(require.resolve('./endpoint')); - loadTestFile(require.resolve('./ingest_manager')); loadTestFile(require.resolve('./lists')); loadTestFile(require.resolve('./upgrade_assistant')); }); diff --git a/x-pack/test/api_integration/apis/management/ingest_pipelines/ingest_pipelines.ts b/x-pack/test/api_integration/apis/management/ingest_pipelines/ingest_pipelines.ts index a48460d7a3b23..b3fab42a46114 100644 --- a/x-pack/test/api_integration/apis/management/ingest_pipelines/ingest_pipelines.ts +++ b/x-pack/test/api_integration/apis/management/ingest_pipelines/ingest_pipelines.ts @@ -14,16 +14,26 @@ const API_BASE_PATH = '/api/ingest_pipelines'; export default function ({ getService }: FtrProviderContext) { const supertest = getService('supertest'); - const { createPipeline, deletePipeline } = registerEsHelpers(getService); + const { createPipeline, deletePipeline, cleanupPipelines } = registerEsHelpers(getService); describe('Pipelines', function () { + after(async () => { + await cleanupPipelines(); + }); + describe('Create', () => { const PIPELINE_ID = 'test_create_pipeline'; const REQUIRED_FIELDS_PIPELINE_ID = 'test_create_required_fields_pipeline'; - after(() => { - deletePipeline(PIPELINE_ID); - deletePipeline(REQUIRED_FIELDS_PIPELINE_ID); + after(async () => { + // Clean up any pipelines created in test cases + await Promise.all([PIPELINE_ID, REQUIRED_FIELDS_PIPELINE_ID].map(deletePipeline)).catch( + (err) => { + // eslint-disable-next-line no-console + console.log(`[Cleanup error] Error deleting pipelines: ${err.message}`); + throw err; + } + ); }); it('should create a pipeline', async () => { @@ -127,8 +137,16 @@ export default function ({ getService }: FtrProviderContext) { ], }; - before(() => createPipeline({ body: PIPELINE, id: PIPELINE_ID })); - after(() => deletePipeline(PIPELINE_ID)); + before(async () => { + // Create pipeline that can be used to test PUT request + try { + await createPipeline({ body: PIPELINE, id: PIPELINE_ID }, true); + } catch (err) { + // eslint-disable-next-line no-console + console.log('[Setup error] Error creating ingest node pipeline'); + throw err; + } + }); it('should allow an existing pipeline to be updated', async () => { const uri = `${API_BASE_PATH}/${PIPELINE_ID}`; @@ -185,7 +203,7 @@ export default function ({ getService }: FtrProviderContext) { }); describe('Get', () => { - const PIPELINE_ID = 'test_pipeline'; + const PIPELINE_ID = 'test_get_pipeline'; const PIPELINE = { description: 'test pipeline description', processors: [ @@ -198,8 +216,16 @@ export default function ({ getService }: FtrProviderContext) { version: 1, }; - before(() => createPipeline({ body: PIPELINE, id: PIPELINE_ID })); - after(() => deletePipeline(PIPELINE_ID)); + before(async () => { + // Create pipeline that can be used to test GET request + try { + await createPipeline({ body: PIPELINE, id: PIPELINE_ID }, true); + } catch (err) { + // eslint-disable-next-line no-console + console.log('[Setup error] Error creating ingest node pipeline'); + throw err; + } + }); describe('all pipelines', () => { it('should return an array of pipelines', async () => { @@ -245,29 +271,40 @@ export default function ({ getService }: FtrProviderContext) { version: 1, }; + const pipelineA = { body: PIPELINE, id: 'test_delete_pipeline_a' }; + const pipelineB = { body: PIPELINE, id: 'test_delete_pipeline_b' }; + const pipelineC = { body: PIPELINE, id: 'test_delete_pipeline_c' }; + const pipelineD = { body: PIPELINE, id: 'test_delete_pipeline_d' }; + + before(async () => { + // Create several pipelines that can be used to test deletion + await Promise.all( + [pipelineA, pipelineB, pipelineC, pipelineD].map((pipeline) => createPipeline(pipeline)) + ).catch((err) => { + // eslint-disable-next-line no-console + console.log(`[Setup error] Error creating pipelines: ${err.message}`); + throw err; + }); + }); + it('should delete a pipeline', async () => { - // Create pipeline to be deleted - const PIPELINE_ID = 'test_delete_pipeline'; - createPipeline({ body: PIPELINE, id: PIPELINE_ID }); + const { id } = pipelineA; - const uri = `${API_BASE_PATH}/${PIPELINE_ID}`; + const uri = `${API_BASE_PATH}/${id}`; const { body } = await supertest.delete(uri).set('kbn-xsrf', 'xxx').expect(200); expect(body).to.eql({ - itemsDeleted: [PIPELINE_ID], + itemsDeleted: [id], errors: [], }); }); it('should delete multiple pipelines', async () => { - // Create pipelines to be deleted - const PIPELINE_ONE_ID = 'test_delete_pipeline_1'; - const PIPELINE_TWO_ID = 'test_delete_pipeline_2'; - createPipeline({ body: PIPELINE, id: PIPELINE_ONE_ID }); - createPipeline({ body: PIPELINE, id: PIPELINE_TWO_ID }); + const { id: pipelineBId } = pipelineB; + const { id: pipelineCId } = pipelineC; - const uri = `${API_BASE_PATH}/${PIPELINE_ONE_ID},${PIPELINE_TWO_ID}`; + const uri = `${API_BASE_PATH}/${pipelineBId},${pipelineCId}`; const { body: { itemsDeleted, errors }, @@ -276,24 +313,21 @@ export default function ({ getService }: FtrProviderContext) { expect(errors).to.eql([]); // The itemsDeleted array order isn't guaranteed, so we assert against each pipeline name instead - [PIPELINE_ONE_ID, PIPELINE_TWO_ID].forEach((pipelineName) => { + [pipelineBId, pipelineCId].forEach((pipelineName) => { expect(itemsDeleted.includes(pipelineName)).to.be(true); }); }); it('should return an error for any pipelines not sucessfully deleted', async () => { const PIPELINE_DOES_NOT_EXIST = 'pipeline_does_not_exist'; + const { id: existingPipelineId } = pipelineD; - // Create pipeline to be deleted - const PIPELINE_ONE_ID = 'test_delete_pipeline_1'; - createPipeline({ body: PIPELINE, id: PIPELINE_ONE_ID }); - - const uri = `${API_BASE_PATH}/${PIPELINE_ONE_ID},${PIPELINE_DOES_NOT_EXIST}`; + const uri = `${API_BASE_PATH}/${existingPipelineId},${PIPELINE_DOES_NOT_EXIST}`; const { body } = await supertest.delete(uri).set('kbn-xsrf', 'xxx').expect(200); expect(body).to.eql({ - itemsDeleted: [PIPELINE_ONE_ID], + itemsDeleted: [existingPipelineId], errors: [ { name: PIPELINE_DOES_NOT_EXIST, diff --git a/x-pack/test/api_integration/apis/management/ingest_pipelines/lib/elasticsearch.ts b/x-pack/test/api_integration/apis/management/ingest_pipelines/lib/elasticsearch.ts index 2f42596a66b54..6de91e1154a85 100644 --- a/x-pack/test/api_integration/apis/management/ingest_pipelines/lib/elasticsearch.ts +++ b/x-pack/test/api_integration/apis/management/ingest_pipelines/lib/elasticsearch.ts @@ -26,14 +26,33 @@ interface Pipeline { * @param {ElasticsearchClient} es The Elasticsearch client instance */ export const registerEsHelpers = (getService: FtrProviderContext['getService']) => { + let pipelinesCreated: string[] = []; + const es = getService('legacyEs'); - const createPipeline = (pipeline: Pipeline) => es.ingest.putPipeline(pipeline); + const createPipeline = (pipeline: Pipeline, cachePipeline?: boolean) => { + if (cachePipeline) { + pipelinesCreated.push(pipeline.id); + } + + return es.ingest.putPipeline(pipeline); + }; const deletePipeline = (pipelineId: string) => es.ingest.deletePipeline({ id: pipelineId }); + const cleanupPipelines = () => + Promise.all(pipelinesCreated.map(deletePipeline)) + .then(() => { + pipelinesCreated = []; + }) + .catch((err) => { + // eslint-disable-next-line no-console + console.log(`[Cleanup error] Error deleting ES resources: ${err.message}`); + }); + return { createPipeline, deletePipeline, + cleanupPipelines, }; }; diff --git a/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts new file mode 100644 index 0000000000000..f163df0109ffd --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts @@ -0,0 +1,84 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; + +import { FtrProviderContext } from '../../../ftr_provider_context'; +import { USER } from '../../../../functional/services/ml/security_common'; +import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common'; + +// eslint-disable-next-line import/no-default-export +export default ({ getService }: FtrProviderContext) => { + const supertest = getService('supertestWithoutAuth'); + const ml = getService('ml'); + + describe('create_calendars', function () { + const calendarId = `test_create_calendar`; + + const requestBody = { + calendarId, + job_ids: ['test_job_1', 'test_job_2'], + description: 'Test calendar', + events: [ + { description: 'event 1', start_time: 1513641600000, end_time: 1513728000000 }, + { description: 'event 2', start_time: 1513814400000, end_time: 1513900800000 }, + { description: 'event 3', start_time: 1514160000000, end_time: 1514246400000 }, + ], + }; + + before(async () => { + await ml.testResources.setKibanaTimeZoneToUTC(); + }); + + afterEach(async () => { + await ml.api.deleteCalendar(calendarId); + }); + + it('should successfully create calendar by id', async () => { + await supertest + .put(`/api/ml/calendars`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(200); + + const results = await ml.api.getCalendar(requestBody.calendarId); + const createdCalendar = results.body.calendars[0]; + + expect(createdCalendar.calendar_id).to.eql(requestBody.calendarId); + expect(createdCalendar.description).to.eql(requestBody.description); + expect(createdCalendar.job_ids).to.eql(requestBody.job_ids); + + await ml.api.waitForEventsToExistInCalendar(calendarId, requestBody.events); + }); + + it('should not create new calendar for user without required permission', async () => { + const { body } = await supertest + .put(`/api/ml/calendars`) + .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(404); + + expect(body.error).to.eql('Not Found'); + expect(body.message).to.eql('Not Found'); + await ml.api.waitForCalendarNotToExist(calendarId); + }); + + it('should not create new calendar for unauthorized user', async () => { + const { body } = await supertest + .put(`/api/ml/calendars`) + .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(404); + + expect(body.error).to.eql('Not Found'); + expect(body.message).to.eql('Not Found'); + await ml.api.waitForCalendarNotToExist(calendarId); + }); + }); +}; diff --git a/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts new file mode 100644 index 0000000000000..5c5d5a3c432fa --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts @@ -0,0 +1,87 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; + +import { FtrProviderContext } from '../../../ftr_provider_context'; +import { USER } from '../../../../functional/services/ml/security_common'; +import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common'; + +// eslint-disable-next-line import/no-default-export +export default ({ getService }: FtrProviderContext) => { + const supertest = getService('supertestWithoutAuth'); + const ml = getService('ml'); + + describe('delete_calendars', function () { + const calendarId = `test_delete_cal`; + const testCalendar = { + calendar_id: calendarId, + job_ids: ['test_job_1', 'test_job_2'], + description: `Test calendar`, + }; + const testEvents = [ + { description: 'event 1', start_time: 1513641600000, end_time: 1513728000000 }, + { description: 'event 2', start_time: 1513814400000, end_time: 1513900800000 }, + { description: 'event 3', start_time: 1514160000000, end_time: 1514246400000 }, + ]; + + before(async () => { + await ml.testResources.setKibanaTimeZoneToUTC(); + }); + + beforeEach(async () => { + await ml.api.createCalendar(calendarId, testCalendar); + await ml.api.createCalendarEvents(calendarId, testEvents); + }); + + afterEach(async () => { + await ml.api.deleteCalendar(calendarId); + }); + + it('should delete calendar by id', async () => { + const { body } = await supertest + .delete(`/api/ml/calendars/${calendarId}`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .expect(200); + + expect(body.acknowledged).to.eql(true); + await ml.api.waitForCalendarNotToExist(calendarId); + }); + + it('should not delete calendar for user without required permission', async () => { + const { body } = await supertest + .delete(`/api/ml/calendars/${calendarId}`) + .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) + .set(COMMON_REQUEST_HEADERS) + .expect(404); + + expect(body.error).to.eql('Not Found'); + await ml.api.waitForCalendarToExist(calendarId); + }); + + it('should not delete calendar for unauthorized user', async () => { + const { body } = await supertest + .delete(`/api/ml/calendars/${calendarId}`) + .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) + .set(COMMON_REQUEST_HEADERS) + .expect(404); + + expect(body.error).to.eql('Not Found'); + await ml.api.waitForCalendarToExist(calendarId); + }); + + it('should return 404 if invalid calendarId', async () => { + const { body } = await supertest + .delete(`/api/ml/calendars/calendar_id_dne`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .expect(404); + + expect(body.error).to.eql('Not Found'); + }); + }); +}; diff --git a/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts new file mode 100644 index 0000000000000..e115986b2f092 --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts @@ -0,0 +1,145 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../ftr_provider_context'; +import { USER } from '../../../../functional/services/ml/security_common'; +import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common'; + +// eslint-disable-next-line import/no-default-export +export default ({ getService }: FtrProviderContext) => { + const supertest = getService('supertestWithoutAuth'); + const ml = getService('ml'); + + describe('get_calendars', function () { + const testEvents = [ + { description: 'event 1', start_time: 1513641600000, end_time: 1513728000000 }, + { description: 'event 2', start_time: 1513814400000, end_time: 1513900800000 }, + { description: 'event 3', start_time: 1514160000000, end_time: 1514246400000 }, + ]; + + before(async () => { + await ml.testResources.setKibanaTimeZoneToUTC(); + }); + + describe('get multiple calendars', function () { + const testCalendars = [1, 2, 3].map((num) => ({ + calendar_id: `test_get_cal_${num}`, + job_ids: ['test_job_1', 'test_job_2'], + description: `Test calendar ${num}`, + })); + + beforeEach(async () => { + for (const testCalendar of testCalendars) { + await ml.api.createCalendar(testCalendar.calendar_id, testCalendar); + await ml.api.createCalendarEvents(testCalendar.calendar_id, testEvents); + } + }); + + afterEach(async () => { + for (const testCalendar of testCalendars) { + await ml.api.deleteCalendar(testCalendar.calendar_id); + } + }); + + it('should fetch all calendars', async () => { + const { body } = await supertest + .get(`/api/ml/calendars`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .expect(200); + + expect(body).to.have.length(testCalendars.length); + expect(body[0].events).to.have.length(testEvents.length); + ml.api.assertAllEventsExistInCalendar(testEvents, body[0]); + }); + + it('should fetch all calendars for user with view permission', async () => { + const { body } = await supertest + .get(`/api/ml/calendars`) + .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) + .set(COMMON_REQUEST_HEADERS) + .expect(200); + + expect(body).to.have.length(testCalendars.length); + expect(body[0].events).to.have.length(testEvents.length); + ml.api.assertAllEventsExistInCalendar(testEvents, body[0]); + }); + + it('should not fetch calendars for unauthorized user', async () => { + const { body } = await supertest + .get(`/api/ml/calendars`) + .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) + .set(COMMON_REQUEST_HEADERS) + .expect(404); + expect(body.error).to.eql('Not Found'); + }); + }); + + describe('get calendar by id', function () { + const calendarId = `test_get_cal`; + const testCalendar = { + calendar_id: calendarId, + job_ids: ['test_job_1', 'test_job_2'], + description: `Test calendar`, + }; + + beforeEach(async () => { + await ml.api.createCalendar(calendarId, testCalendar); + await ml.api.createCalendarEvents(calendarId, testEvents); + }); + + afterEach(async () => { + await ml.api.deleteCalendar(calendarId); + }); + + it('should fetch calendar & associated events by id', async () => { + const { body } = await supertest + .get(`/api/ml/calendars/${calendarId}`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .expect(200); + + expect(body.job_ids).to.eql(testCalendar.job_ids); + expect(body.description).to.eql(testCalendar.description); + expect(body.events).to.have.length(testEvents.length); + ml.api.assertAllEventsExistInCalendar(testEvents, body); + }); + + it('should fetch calendar & associated events by id for user with view permission', async () => { + const { body } = await supertest + .get(`/api/ml/calendars/${calendarId}`) + .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) + .set(COMMON_REQUEST_HEADERS) + .expect(200); + + expect(body.job_ids).to.eql(testCalendar.job_ids); + expect(body.description).to.eql(testCalendar.description); + expect(body.events).to.have.length(testEvents.length); + ml.api.assertAllEventsExistInCalendar(testEvents, body); + }); + + it('should not fetch calendars for unauthorized user', async () => { + const { body } = await supertest + .get(`/api/ml/calendars/${calendarId}`) + .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) + .set(COMMON_REQUEST_HEADERS) + .expect(404); + + expect(body.error).to.eql('Not Found'); + }); + }); + + it('should return 404 if invalid calendar id', async () => { + const { body } = await supertest + .get(`/api/ml/calendars/calendar_id_dne`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .expect(404); + expect(body.error).to.eql('Not Found'); + }); + }); +}; diff --git a/x-pack/test/api_integration/apis/ml/calendars/helpers.ts b/x-pack/test/api_integration/apis/ml/calendars/helpers.ts new file mode 100644 index 0000000000000..5d143d9b451f2 --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/calendars/helpers.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Calendar, CalendarEvent } from '../../../../../plugins/ml/server/models/calendar'; + +export const assertAllEventsExistInCalendar = ( + eventsToCheck: CalendarEvent[], + calendar: Calendar +): boolean => { + const updatedCalendarEvents = calendar.events as CalendarEvent[]; + let allEventsAreUpdated = true; + for (const eventToCheck of eventsToCheck) { + // if at least one of the events that we need to check is not in the updated events + // no need to continue + if ( + updatedCalendarEvents.findIndex( + (updatedEvent) => + updatedEvent.description === eventToCheck.description && + updatedEvent.start_time === eventToCheck.start_time && + updatedEvent.end_time === eventToCheck.end_time + ) < 0 + ) { + allEventsAreUpdated = false; + break; + } + } + return allEventsAreUpdated; +}; diff --git a/x-pack/test/api_integration/apis/ml/calendars/index.ts b/x-pack/test/api_integration/apis/ml/calendars/index.ts new file mode 100644 index 0000000000000..e7d824205e6cc --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/calendars/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrProviderContext } from '../../../ftr_provider_context'; + +export default function ({ loadTestFile }: FtrProviderContext) { + describe('calendars', function () { + loadTestFile(require.resolve('./create_calendars')); + loadTestFile(require.resolve('./get_calendars')); + loadTestFile(require.resolve('./delete_calendars')); + loadTestFile(require.resolve('./update_calendars')); + }); +} diff --git a/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts new file mode 100644 index 0000000000000..5194370b19e66 --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts @@ -0,0 +1,104 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; + +import { FtrProviderContext } from '../../../ftr_provider_context'; +import { USER } from '../../../../functional/services/ml/security_common'; +import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common'; + +// eslint-disable-next-line import/no-default-export +export default ({ getService }: FtrProviderContext) => { + const supertest = getService('supertestWithoutAuth'); + const ml = getService('ml'); + + describe('update_calendars', function () { + before(async () => { + await ml.testResources.setKibanaTimeZoneToUTC(); + }); + + const calendarId = `test_update_cal`; + const originalCalendar = { + calendar_id: calendarId, + job_ids: ['test_job_1'], + description: `Test calendar`, + }; + const originalEvents = [ + { description: 'event 1', start_time: 1513641600000, end_time: 1513728000000 }, + ]; + + const updateCalendarRequestBody = { + calendarId, + job_ids: ['test_updated_job_1', 'test_updated_job_2'], + description: 'Updated calendar #1', + events: [ + { description: 'updated event 2', start_time: 1513814400000, end_time: 1513900800000 }, + { description: 'updated event 3', start_time: 1514160000000, end_time: 1514246400000 }, + ], + }; + + beforeEach(async () => { + await ml.api.createCalendar(calendarId, originalCalendar); + await ml.api.createCalendarEvents(calendarId, originalEvents); + }); + + afterEach(async () => { + await ml.api.deleteCalendar(calendarId); + }); + + it('should update calendar by id with new settings', async () => { + await supertest + .put(`/api/ml/calendars/${calendarId}`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .send(updateCalendarRequestBody) + .expect(200); + + await ml.api.waitForCalendarToExist(calendarId); + + const getCalendarResult = await ml.api.getCalendar(calendarId); + const getEventsResult = await ml.api.getCalendarEvents(calendarId); + + const updatedCalendar = getCalendarResult.body.calendars[0]; + const updatedEvents = getEventsResult.body.events; + + expect(updatedCalendar.calendar_id).to.eql(updateCalendarRequestBody.calendarId); + expect(updatedCalendar.job_ids).to.have.length(updateCalendarRequestBody.job_ids.length); + expect(updatedEvents).to.have.length(updateCalendarRequestBody.events.length); + await ml.api.waitForEventsToExistInCalendar( + updatedCalendar.calendar_id, + updateCalendarRequestBody.events + ); + }); + + it('should not allow to update calendar for user without required permission ', async () => { + await supertest + .put(`/api/ml/calendars/${calendarId}`) + .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) + .set(COMMON_REQUEST_HEADERS) + .send(updateCalendarRequestBody) + .expect(404); + }); + + it('should not allow to update calendar for unauthorized user', async () => { + await supertest + .put(`/api/ml/calendars/${calendarId}`) + .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) + .set(COMMON_REQUEST_HEADERS) + .send(updateCalendarRequestBody) + .expect(404); + }); + + it('should return error if invalid calendarId ', async () => { + await supertest + .put(`/api/ml/calendars/calendar_id_dne`) + .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) + .set(COMMON_REQUEST_HEADERS) + .send(updateCalendarRequestBody) + .expect(404); + }); + }); +}; diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/index.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/index.ts index 6693561076fdd..99549be8c1868 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/index.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/index.ts @@ -10,5 +10,6 @@ export default function ({ loadTestFile }: FtrProviderContext) { describe('data frame analytics', function () { loadTestFile(require.resolve('./get')); loadTestFile(require.resolve('./delete')); + loadTestFile(require.resolve('./update')); }); } diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/update.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/update.ts new file mode 100644 index 0000000000000..5dc781657619d --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/update.ts @@ -0,0 +1,275 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../ftr_provider_context'; +import { USER } from '../../../../functional/services/ml/security_common'; +import { DataFrameAnalyticsConfig } from '../../../../../plugins/ml/public/application/data_frame_analytics/common'; +import { DeepPartial } from '../../../../../plugins/ml/common/types/common'; +import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common'; + +export default ({ getService }: FtrProviderContext) => { + const esArchiver = getService('esArchiver'); + const supertest = getService('supertestWithoutAuth'); + const ml = getService('ml'); + + const jobId = `bm_${Date.now()}`; + const generateDestinationIndex = (analyticsId: string) => `user-${analyticsId}`; + const commonJobConfig = { + source: { + index: ['ft_bank_marketing'], + query: { + match_all: {}, + }, + }, + analysis: { + classification: { + dependent_variable: 'y', + training_percent: 20, + }, + }, + analyzed_fields: { + includes: [], + excludes: [], + }, + model_memory_limit: '60mb', + allow_lazy_start: false, // default value + max_num_threads: 1, // default value + }; + + const testJobConfigs: Array> = [ + 'Test update job', + 'Test update job description only', + 'Test update job allow_lazy_start only', + 'Test update job model_memory_limit only', + 'Test update job max_num_threads only', + ].map((description, idx) => { + const analyticsId = `${jobId}_${idx}`; + return { + id: analyticsId, + description, + dest: { + index: generateDestinationIndex(analyticsId), + results_field: 'ml', + }, + ...commonJobConfig, + }; + }); + + const editedDescription = 'Edited description'; + + async function createJobs(mockJobConfigs: Array>) { + for (const jobConfig of mockJobConfigs) { + await ml.api.createDataFrameAnalyticsJob(jobConfig as DataFrameAnalyticsConfig); + } + } + + async function getDFAJob(id: string) { + const { body } = await supertest + .get(`/api/ml/data_frame/analytics/${id}`) + .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) + .set(COMMON_REQUEST_HEADERS); + + return body.data_frame_analytics[0]; + } + + describe('UPDATE data_frame/analytics', () => { + before(async () => { + await esArchiver.loadIfNeeded('ml/bm_classification'); + await ml.testResources.setKibanaTimeZoneToUTC(); + await createJobs(testJobConfigs); + }); + + after(async () => { + await ml.api.cleanMlIndices(); + }); + + describe('UpdateDataFrameAnalytics', () => { + it('should update all editable fields of analytics job for specified id', async () => { + const analyticsId = `${jobId}_0`; + + const requestBody = { + description: editedDescription, + model_memory_limit: '61mb', + allow_lazy_start: true, + max_num_threads: 2, + }; + + const { body } = await supertest + .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(200); + + expect(body).not.to.be(undefined); + + const fetchedJob = await getDFAJob(analyticsId); + + expect(fetchedJob.description).to.eql(requestBody.description); + expect(fetchedJob.allow_lazy_start).to.eql(requestBody.allow_lazy_start); + expect(fetchedJob.model_memory_limit).to.eql(requestBody.model_memory_limit); + expect(fetchedJob.max_num_threads).to.eql(requestBody.max_num_threads); + }); + + it('should only update description field of analytics job when description is sent in request', async () => { + const analyticsId = `${jobId}_1`; + + const requestBody = { + description: 'Edited description for job 1', + }; + + const { body } = await supertest + .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(200); + + expect(body).not.to.be(undefined); + + const fetchedJob = await getDFAJob(analyticsId); + + expect(fetchedJob.description).to.eql(requestBody.description); + expect(fetchedJob.allow_lazy_start).to.eql(commonJobConfig.allow_lazy_start); + expect(fetchedJob.model_memory_limit).to.eql(commonJobConfig.model_memory_limit); + expect(fetchedJob.max_num_threads).to.eql(commonJobConfig.max_num_threads); + }); + + it('should only update allow_lazy_start field of analytics job when allow_lazy_start is sent in request', async () => { + const analyticsId = `${jobId}_2`; + + const requestBody = { + allow_lazy_start: true, + }; + + const { body } = await supertest + .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(200); + + expect(body).not.to.be(undefined); + + const fetchedJob = await getDFAJob(analyticsId); + + expect(fetchedJob.allow_lazy_start).to.eql(requestBody.allow_lazy_start); + expect(fetchedJob.description).to.eql(testJobConfigs[2].description); + expect(fetchedJob.model_memory_limit).to.eql(commonJobConfig.model_memory_limit); + expect(fetchedJob.max_num_threads).to.eql(commonJobConfig.max_num_threads); + }); + + it('should only update model_memory_limit field of analytics job when model_memory_limit is sent in request', async () => { + const analyticsId = `${jobId}_3`; + + const requestBody = { + model_memory_limit: '61mb', + }; + + const { body } = await supertest + .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(200); + + expect(body).not.to.be(undefined); + + const fetchedJob = await getDFAJob(analyticsId); + + expect(fetchedJob.model_memory_limit).to.eql(requestBody.model_memory_limit); + expect(fetchedJob.allow_lazy_start).to.eql(commonJobConfig.allow_lazy_start); + expect(fetchedJob.description).to.eql(testJobConfigs[3].description); + expect(fetchedJob.max_num_threads).to.eql(commonJobConfig.max_num_threads); + }); + + it('should only update max_num_threads field of analytics job when max_num_threads is sent in request', async () => { + const analyticsId = `${jobId}_4`; + + const requestBody = { + max_num_threads: 2, + }; + + const { body } = await supertest + .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(200); + + expect(body).not.to.be(undefined); + + const fetchedJob = await getDFAJob(analyticsId); + + expect(fetchedJob.max_num_threads).to.eql(requestBody.max_num_threads); + expect(fetchedJob.model_memory_limit).to.eql(commonJobConfig.model_memory_limit); + expect(fetchedJob.allow_lazy_start).to.eql(commonJobConfig.allow_lazy_start); + expect(fetchedJob.description).to.eql(testJobConfigs[4].description); + }); + + it('should not allow to update analytics job for unauthorized user', async () => { + const analyticsId = `${jobId}_0`; + const requestBody = { + description: 'Unauthorized', + }; + + const { body } = await supertest + .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(404); + + expect(body.error).to.eql('Not Found'); + expect(body.message).to.eql('Not Found'); + + const fetchedJob = await getDFAJob(analyticsId); + // Description should not have changed + expect(fetchedJob.description).to.eql(editedDescription); + }); + + it('should not allow to update analytics job for the user with only view permission', async () => { + const analyticsId = `${jobId}_0`; + const requestBody = { + description: 'View only', + }; + + const { body } = await supertest + .post(`/api/ml/data_frame/analytics/${analyticsId}/_update`) + .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(404); + + expect(body.error).to.eql('Not Found'); + expect(body.message).to.eql('Not Found'); + + const fetchedJob = await getDFAJob(analyticsId); + // Description should not have changed + expect(fetchedJob.description).to.eql(editedDescription); + }); + + it('should show 404 error if job does not exist', async () => { + const requestBody = { + description: 'Not found', + }; + const id = `${jobId}_invalid`; + const message = `[resource_not_found_exception] No known data frame analytics with id [${id}]`; + + const { body } = await supertest + .post(`/api/ml/data_frame/analytics/${id}/_update`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(404); + + expect(body.error).to.eql('Not Found'); + expect(body.message).to.eql(message); + }); + }); + }); +}; diff --git a/x-pack/test/api_integration/apis/ml/filters/create_filters.ts b/x-pack/test/api_integration/apis/ml/filters/create_filters.ts new file mode 100644 index 0000000000000..c175d3a9a3d9c --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/filters/create_filters.ts @@ -0,0 +1,127 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; + +import { FtrProviderContext } from '../../../ftr_provider_context'; +import { USER } from '../../../../functional/services/ml/security_common'; +import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common'; + +// eslint-disable-next-line import/no-default-export +export default ({ getService }: FtrProviderContext) => { + const supertest = getService('supertestWithoutAuth'); + const ml = getService('ml'); + + const testDataList = [ + { + testTitle: 'should successfully create new filter', + user: USER.ML_POWERUSER, + requestBody: { filterId: 'safe_ip_addresses', description: '', items: ['104.236.210.185'] }, + expected: { + responseCode: 200, + responseBody: { + filter_id: 'safe_ip_addresses', + description: '', + items: ['104.236.210.185'], + }, + }, + }, + { + testTitle: 'should not create new filter for user without required permission', + user: USER.ML_VIEWER, + requestBody: { + filterId: 'safe_ip_addresses_view_only', + + description: '', + items: ['104.236.210.185'], + }, + expected: { + responseCode: 404, + responseBody: { + error: 'Not Found', + message: 'Not Found', + }, + }, + }, + { + testTitle: 'should not create new filter for unauthorized user', + user: USER.ML_UNAUTHORIZED, + requestBody: { + filterId: 'safe_ip_addresses_unauthorized', + description: '', + items: ['104.236.210.185'], + }, + expected: { + responseCode: 404, + responseBody: { + error: 'Not Found', + message: 'Not Found', + }, + }, + }, + { + testTitle: 'should return 400 bad request if invalid filterId', + user: USER.ML_POWERUSER, + requestBody: { + filterId: '@invalid_filter_id', + description: '', + items: ['104.236.210.185'], + }, + expected: { + responseCode: 400, + responseBody: { + error: 'Bad Request', + message: 'Invalid filter_id', + }, + }, + }, + { + testTitle: 'should return 400 bad request if invalid items', + user: USER.ML_POWERUSER, + requestBody: { filterId: 'valid_filter', description: '' }, + expected: { + responseCode: 400, + responseBody: { + error: 'Bad Request', + message: 'expected value of type [array] but got [undefined]', + }, + }, + }, + ]; + + describe('create_filters', function () { + before(async () => { + await ml.testResources.setKibanaTimeZoneToUTC(); + }); + + after(async () => { + for (const testData of testDataList) { + const { filterId } = testData.requestBody; + await ml.api.deleteFilter(filterId); + } + }); + + for (const testData of testDataList) { + const { testTitle, user, requestBody, expected } = testData; + it(`${testTitle}`, async () => { + const { body } = await supertest + .put(`/api/ml/filters`) + .auth(user, ml.securityCommon.getPasswordForUser(user)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(expected.responseCode); + if (body.error === undefined) { + // Validate the important parts of the response. + const expectedResponse = testData.expected.responseBody; + expect(body).to.eql(expectedResponse); + } else { + expect(body.error).to.contain(expected.responseBody.error); + expect(body.message).to.contain(expected.responseBody.message); + } + }); + } + }); +}; diff --git a/x-pack/test/api_integration/apis/ml/filters/delete_filters.ts b/x-pack/test/api_integration/apis/ml/filters/delete_filters.ts new file mode 100644 index 0000000000000..bb83a7f720692 --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/filters/delete_filters.ts @@ -0,0 +1,95 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; + +import { FtrProviderContext } from '../../../ftr_provider_context'; +import { USER } from '../../../../functional/services/ml/security_common'; +import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common'; + +// eslint-disable-next-line import/no-default-export +export default ({ getService }: FtrProviderContext) => { + const supertest = getService('supertestWithoutAuth'); + const ml = getService('ml'); + + const items = ['104.236.210.185']; + const validFilters = [ + { + filterId: 'filter_power', + requestBody: { description: 'Test delete filter #1', items }, + }, + { + filterId: 'filter_viewer', + requestBody: { description: 'Test delete filter (viewer)', items }, + }, + { + filterId: 'filter_unauthorized', + requestBody: { description: 'Test delete filter (unauthorized)', items }, + }, + ]; + + describe('delete_filters', function () { + before(async () => { + await ml.testResources.setKibanaTimeZoneToUTC(); + for (const filter of validFilters) { + const { filterId, requestBody } = filter; + await ml.api.createFilter(filterId, requestBody); + } + }); + + after(async () => { + for (const filter of validFilters) { + const { filterId } = filter; + await ml.api.deleteFilter(filterId); + } + }); + + it(`should delete filter by id`, async () => { + const { filterId } = validFilters[0]; + const { body } = await supertest + .delete(`/api/ml/filters/${filterId}`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .expect(200); + + expect(body.acknowledged).to.eql(true); + await ml.api.waitForFilterToNotExist(filterId); + }); + + it(`should not delete filter for user without required permission`, async () => { + const { filterId } = validFilters[1]; + const { body } = await supertest + .delete(`/api/ml/filters/${filterId}`) + .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) + .set(COMMON_REQUEST_HEADERS) + .expect(404); + + expect(body.error).to.eql('Not Found'); + await ml.api.waitForFilterToExist(filterId); + }); + + it(`should not delete filter for unauthorized user`, async () => { + const { filterId } = validFilters[2]; + const { body } = await supertest + .delete(`/api/ml/filters/${filterId}`) + .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) + .set(COMMON_REQUEST_HEADERS) + .expect(404); + + expect(body.error).to.eql('Not Found'); + await ml.api.waitForFilterToExist(filterId); + }); + + it(`should not allow user to delete filter if invalid filterId`, async () => { + const { body } = await supertest + .delete(`/api/ml/filters/filter_id_dne`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .expect(404); + expect(body.error).to.eql('Not Found'); + }); + }); +}; diff --git a/x-pack/test/api_integration/apis/ml/filters/get_filters.ts b/x-pack/test/api_integration/apis/ml/filters/get_filters.ts new file mode 100644 index 0000000000000..3dd6093a9917f --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/filters/get_filters.ts @@ -0,0 +1,98 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; + +import { FtrProviderContext } from '../../../ftr_provider_context'; +import { USER } from '../../../../functional/services/ml/security_common'; +import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common'; + +// eslint-disable-next-line import/no-default-export +export default ({ getService }: FtrProviderContext) => { + const supertest = getService('supertestWithoutAuth'); + const ml = getService('ml'); + + const validFilters = [ + { + filterId: 'filter_1', + requestBody: { description: 'Valid filter #1', items: ['104.236.210.185'] }, + }, + { + filterId: 'filter_2', + requestBody: { description: 'Valid filter #2', items: ['104.236.210.185'] }, + }, + ]; + + describe('get_filters', function () { + before(async () => { + await ml.testResources.setKibanaTimeZoneToUTC(); + for (const filter of validFilters) { + const { filterId, requestBody } = filter; + await ml.api.createFilter(filterId, requestBody); + } + }); + + after(async () => { + for (const filter of validFilters) { + const { filterId } = filter; + await ml.api.deleteFilter(filterId); + } + }); + it(`should fetch all filters`, async () => { + const { body } = await supertest + .get(`/api/ml/filters`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .expect(200); + + expect(body).to.have.length(validFilters.length); + }); + + it(`should not allow to retrieve filters for user without required permission`, async () => { + const { body } = await supertest + .get(`/api/ml/filters`) + .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) + .set(COMMON_REQUEST_HEADERS) + .expect(404); + expect(body.error).to.eql('Not Found'); + expect(body.message).to.eql('Not Found'); + }); + + it(`should not allow to retrieve filters for unauthorized user`, async () => { + const { body } = await supertest + .get(`/api/ml/filters`) + .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) + .set(COMMON_REQUEST_HEADERS) + .expect(404); + + expect(body.error).to.eql('Not Found'); + expect(body.message).to.eql('Not Found'); + }); + + it(`should fetch single filter by id`, async () => { + const { filterId, requestBody } = validFilters[0]; + const { body } = await supertest + .get(`/api/ml/filters/${filterId}`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .expect(200); + + expect(body.filter_id).to.eql(filterId); + expect(body.description).to.eql(requestBody.description); + expect(body.items).to.eql(requestBody.items); + }); + + it(`should return 400 if filterId does not exist`, async () => { + const { body } = await supertest + .get(`/api/ml/filters/filter_id_dne`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .expect(400); + expect(body.error).to.eql('Bad Request'); + expect(body.message).to.contain('Unable to find filter'); + }); + }); +}; diff --git a/x-pack/test/api_integration/apis/ml/filters/index.ts b/x-pack/test/api_integration/apis/ml/filters/index.ts new file mode 100644 index 0000000000000..0c0bc4eab29ec --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/filters/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrProviderContext } from '../../../ftr_provider_context'; + +export default function ({ loadTestFile }: FtrProviderContext) { + describe('filters', function () { + loadTestFile(require.resolve('./create_filters')); + loadTestFile(require.resolve('./get_filters')); + loadTestFile(require.resolve('./delete_filters')); + loadTestFile(require.resolve('./update_filters')); + }); +} diff --git a/x-pack/test/api_integration/apis/ml/filters/update_filters.ts b/x-pack/test/api_integration/apis/ml/filters/update_filters.ts new file mode 100644 index 0000000000000..eb58d545093c4 --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/filters/update_filters.ts @@ -0,0 +1,118 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; + +import { FtrProviderContext } from '../../../ftr_provider_context'; +import { USER } from '../../../../functional/services/ml/security_common'; +import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common'; + +// eslint-disable-next-line import/no-default-export +export default ({ getService }: FtrProviderContext) => { + const supertest = getService('supertestWithoutAuth'); + const ml = getService('ml'); + + const items = ['104.236.210.185']; + const validFilters = [ + { + filterId: 'filter_power', + requestBody: { description: 'Test update filter #1', items }, + }, + { + filterId: 'filter_viewer', + requestBody: { description: 'Test update filter (viewer)', items }, + }, + { + filterId: 'filter_unauthorized', + requestBody: { description: 'Test update filter (unauthorized)', items }, + }, + ]; + + describe('update_filters', function () { + const updateFilterRequestBody = { + description: 'Updated filter #1', + removeItems: items, + addItems: ['my_new_items_1', 'my_new_items_2'], + }; + before(async () => { + await ml.testResources.setKibanaTimeZoneToUTC(); + for (const filter of validFilters) { + const { filterId, requestBody } = filter; + await ml.api.createFilter(filterId, requestBody); + } + }); + + after(async () => { + for (const filter of validFilters) { + const { filterId } = filter; + await ml.api.deleteFilter(filterId); + } + }); + + it(`should update filter by id`, async () => { + const { filterId } = validFilters[0]; + const { body } = await supertest + .put(`/api/ml/filters/${filterId}`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .send(updateFilterRequestBody) + .expect(200); + + expect(body.filter_id).to.eql(filterId); + expect(body.description).to.eql(updateFilterRequestBody.description); + expect(body.items).to.eql(updateFilterRequestBody.addItems); + }); + + it(`should not allow to update filter for user without required permission`, async () => { + const { filterId, requestBody: oldFilterRequest } = validFilters[1]; + const { body } = await supertest + .put(`/api/ml/filters/${filterId}`) + .auth(USER.ML_VIEWER, ml.securityCommon.getPasswordForUser(USER.ML_VIEWER)) + .set(COMMON_REQUEST_HEADERS) + .send(updateFilterRequestBody) + .expect(404); + + // response should return not found + expect(body.error).to.eql('Not Found'); + + // and the filter should not be updated + const response = await ml.api.getFilter(filterId); + const updatedFilter = response.body.filters[0]; + expect(updatedFilter.filter_id).to.eql(filterId); + expect(updatedFilter.description).to.eql(oldFilterRequest.description); + expect(updatedFilter.items).to.eql(oldFilterRequest.items); + }); + + it(`should not allow to update filter for unauthorized user`, async () => { + const { filterId, requestBody: oldFilterRequest } = validFilters[2]; + const { body } = await supertest + .put(`/api/ml/filters/${filterId}`) + .auth(USER.ML_UNAUTHORIZED, ml.securityCommon.getPasswordForUser(USER.ML_UNAUTHORIZED)) + .set(COMMON_REQUEST_HEADERS) + .send(updateFilterRequestBody) + .expect(404); + + expect(body.error).to.eql('Not Found'); + + const response = await ml.api.getFilter(filterId); + const updatedFilter = response.body.filters[0]; + expect(updatedFilter.filter_id).to.eql(filterId); + expect(updatedFilter.description).to.eql(oldFilterRequest.description); + expect(updatedFilter.items).to.eql(oldFilterRequest.items); + }); + + it(`should return appropriate error if invalid filterId`, async () => { + const { body } = await supertest + .put(`/api/ml/filters/filter_id_dne`) + .auth(USER.ML_POWERUSER, ml.securityCommon.getPasswordForUser(USER.ML_POWERUSER)) + .set(COMMON_REQUEST_HEADERS) + .send(updateFilterRequestBody) + .expect(400); + + expect(body.message).to.contain('No filter with id'); + }); + }); +}; diff --git a/x-pack/test/api_integration/apis/ml/index.ts b/x-pack/test/api_integration/apis/ml/index.ts index 5c2e7a6c4b2f7..b29bc47b50394 100644 --- a/x-pack/test/api_integration/apis/ml/index.ts +++ b/x-pack/test/api_integration/apis/ml/index.ts @@ -58,5 +58,7 @@ export default function ({ getService, loadTestFile }: FtrProviderContext) { loadTestFile(require.resolve('./jobs')); loadTestFile(require.resolve('./results')); loadTestFile(require.resolve('./data_frame_analytics')); + loadTestFile(require.resolve('./filters')); + loadTestFile(require.resolve('./calendars')); }); } diff --git a/x-pack/test/api_integration/apis/security/privileges.ts b/x-pack/test/api_integration/apis/security/privileges.ts index 59fcfae5db3cf..07233f1685385 100644 --- a/x-pack/test/api_integration/apis/security/privileges.ts +++ b/x-pack/test/api_integration/apis/security/privileges.ts @@ -38,10 +38,12 @@ export default function ({ getService }: FtrProviderContext) { ml: ['all', 'read'], siem: ['all', 'read'], ingestManager: ['all', 'read'], + builtInAlerts: ['all', 'read'], + actions: ['all', 'read'], }, global: ['all', 'read'], space: ['all', 'read'], - reserved: ['ml_user', 'ml_admin', 'monitoring'], + reserved: ['ml_user', 'ml_admin', 'ml_apm_user', 'monitoring'], }; await supertest diff --git a/x-pack/test/api_integration/apis/security/privileges_basic.ts b/x-pack/test/api_integration/apis/security/privileges_basic.ts index 5c2a2875852d6..74d95fa1e4a76 100644 --- a/x-pack/test/api_integration/apis/security/privileges_basic.ts +++ b/x-pack/test/api_integration/apis/security/privileges_basic.ts @@ -36,10 +36,12 @@ export default function ({ getService }: FtrProviderContext) { ml: ['all', 'read'], siem: ['all', 'read'], ingestManager: ['all', 'read'], + builtInAlerts: ['all', 'read'], + actions: ['all', 'read'], }, global: ['all', 'read'], space: ['all', 'read'], - reserved: ['ml_user', 'ml_admin', 'monitoring'], + reserved: ['ml_user', 'ml_admin', 'ml_apm_user', 'monitoring'], }; await supertest diff --git a/x-pack/test/api_integration/apis/short_urls/feature_controls.ts b/x-pack/test/api_integration/apis/short_urls/feature_controls.ts index 958a19c9d871e..640c60572bf9f 100644 --- a/x-pack/test/api_integration/apis/short_urls/feature_controls.ts +++ b/x-pack/test/api_integration/apis/short_urls/feature_controls.ts @@ -24,30 +24,37 @@ export default function featureControlsTests({ getService }: FtrProviderContext) { featureId: 'discover', canAccess: true, + canCreate: true, }, { featureId: 'dashboard', canAccess: true, + canCreate: true, }, { featureId: 'visualize', canAccess: true, + canCreate: true, }, { featureId: 'infrastructure', canAccess: true, + canCreate: false, }, { featureId: 'canvas', canAccess: true, + canCreate: false, }, { featureId: 'maps', canAccess: true, + canCreate: false, }, { featureId: 'unknown-feature', canAccess: false, + canCreate: false, }, ]; @@ -64,12 +71,46 @@ export default function featureControlsTests({ getService }: FtrProviderContext) }, ], }); + await security.role.create(`${feature.featureId}-minimal-role`, { + kibana: [ + { + base: [], + feature: { + [feature.featureId]: ['minimal_all'], + }, + spaces: ['*'], + }, + ], + }); + await security.role.create(`${feature.featureId}-minimal-shorten-role`, { + kibana: [ + { + base: [], + feature: { + [feature.featureId]: ['minimal_read', 'url_create'], + }, + spaces: ['*'], + }, + ], + }); await security.user.create(`${feature.featureId}-user`, { password: kibanaUserPassword, roles: [`${feature.featureId}-role`], full_name: 'a kibana user', }); + + await security.user.create(`${feature.featureId}-minimal-user`, { + password: kibanaUserPassword, + roles: [`${feature.featureId}-minimal-role`], + full_name: 'a kibana user', + }); + + await security.user.create(`${feature.featureId}-minimal-shorten-user`, { + password: kibanaUserPassword, + roles: [`${feature.featureId}-minimal-shorten-role`], + full_name: 'a kibana user', + }); } await security.user.create(kibanaUsername, { @@ -89,8 +130,16 @@ export default function featureControlsTests({ getService }: FtrProviderContext) }); after(async () => { - const users = features.map((feature) => security.user.delete(`${feature.featureId}-user`)); - const roles = features.map((feature) => security.role.delete(`${feature.featureId}-role`)); + const users = features.flatMap((feature) => [ + security.user.delete(`${feature.featureId}-user`), + security.user.delete(`${feature.featureId}-minimal-user`), + security.user.delete(`${feature.featureId}-minimal-shorten-user`), + ]); + const roles = features.flatMap((feature) => [ + security.role.delete(`${feature.featureId}-role`), + security.role.delete(`${feature.featureId}-minimal-role`), + security.role.delete(`${feature.featureId}-minimal-shorten-role`), + ]); await Promise.all([...users, ...roles]); await security.user.delete(kibanaUsername); }); @@ -112,6 +161,36 @@ export default function featureControlsTests({ getService }: FtrProviderContext) } }); }); + + it(`users with "minimal_all" access to ${feature.featureId} should not be able to create short-urls`, async () => { + await supertest + .post(`/api/shorten_url`) + .auth(`${feature.featureId}-minimal-user`, kibanaUserPassword) + .set('kbn-xsrf', 'foo') + .send({ url: '/app/dashboard' }) + .then((resp: Record) => { + expect(resp.status).to.eql(403); + expect(resp.body.message).to.eql('Unable to create url'); + }); + }); + + it(`users with "url_create" access to ${feature.featureId} ${ + feature.canCreate ? 'should' : 'should not' + } be able to create short-urls`, async () => { + await supertest + .post(`/api/shorten_url`) + .auth(`${feature.featureId}-minimal-shorten-user`, kibanaUserPassword) + .set('kbn-xsrf', 'foo') + .send({ url: '/app/dashboard' }) + .then((resp: Record) => { + if (feature.canCreate) { + expect(resp.status).to.eql(200); + } else { + expect(resp.status).to.eql(403); + expect(resp.body.message).to.eql('Unable to create url'); + } + }); + }); }); }); } diff --git a/x-pack/test/api_integration/apis/uptime/rest/fixtures/ping_histogram.json b/x-pack/test/api_integration/apis/uptime/rest/fixtures/ping_histogram.json index 562ba64c24b0b..85ce545ed92b0 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/fixtures/ping_histogram.json +++ b/x-pack/test/api_integration/apis/uptime/rest/fixtures/ping_histogram.json @@ -1,121 +1,157 @@ { "histogram": [ { - "x": 1568172664000, + "x": 1568172657286, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568172694000, + "x": 1568172680087, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568172724000, + "x": 1568172702888, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568172754000, + "x": 1568172725689, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568172748490, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568172784000, + "x": 1568172771291, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568172814000, + "x": 1568172794092, "downCount": 8, "upCount": 92, "y": 1 }, { - "x": 1568172844000, + "x": 1568172816893, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568172839694, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568172874000, + "x": 1568172862495, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568172904000, + "x": 1568172885296, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568172934000, + "x": 1568172908097, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568172930898, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568172964000, + "x": 1568172953699, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568172994000, + "x": 1568172976500, "downCount": 8, "upCount": 92, "y": 1 }, { - "x": 1568173024000, + "x": 1568172999301, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568173022102, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568173054000, + "x": 1568173044903, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568173084000, + "x": 1568173067704, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568173114000, + "x": 1568173090505, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568173113306, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568173144000, + "x": 1568173136107, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568173174000, + "x": 1568173158908, "downCount": 8, "upCount": 92, "y": 1 }, { - "x": 1568173204000, + "x": 1568173181709, "downCount": 7, "upCount": 93, "y": 1 }, { - "x": 1568173234000, + "x": 1568173204510, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568173227311, "downCount": 7, "upCount": 93, "y": 1 diff --git a/x-pack/test/api_integration/apis/uptime/rest/fixtures/ping_histogram_by_filter.json b/x-pack/test/api_integration/apis/uptime/rest/fixtures/ping_histogram_by_filter.json index 42be715c4acd4..fe5dc9dd3da3f 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/fixtures/ping_histogram_by_filter.json +++ b/x-pack/test/api_integration/apis/uptime/rest/fixtures/ping_histogram_by_filter.json @@ -1,121 +1,157 @@ { "histogram": [ { - "x": 1568172664000, + "x": 1568172657286, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568172694000, + "x": 1568172680087, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568172724000, + "x": 1568172702888, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568172754000, + "x": 1568172725689, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568172748490, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568172784000, + "x": 1568172771291, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568172814000, + "x": 1568172794092, "downCount": 0, "upCount": 92, "y": 1 }, { - "x": 1568172844000, + "x": 1568172816893, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568172839694, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568172874000, + "x": 1568172862495, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568172904000, + "x": 1568172885296, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568172934000, + "x": 1568172908097, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568172930898, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568172964000, + "x": 1568172953699, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568172994000, + "x": 1568172976500, "downCount": 0, "upCount": 92, "y": 1 }, { - "x": 1568173024000, + "x": 1568172999301, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568173022102, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568173054000, + "x": 1568173044903, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568173084000, + "x": 1568173067704, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568173114000, + "x": 1568173090505, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568173113306, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568173144000, + "x": 1568173136107, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568173174000, + "x": 1568173158908, "downCount": 0, "upCount": 92, "y": 1 }, { - "x": 1568173204000, + "x": 1568173181709, "downCount": 0, "upCount": 93, "y": 1 }, { - "x": 1568173234000, + "x": 1568173204510, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568173227311, "downCount": 0, "upCount": 93, "y": 1 diff --git a/x-pack/test/api_integration/apis/uptime/rest/fixtures/ping_histogram_by_id.json b/x-pack/test/api_integration/apis/uptime/rest/fixtures/ping_histogram_by_id.json index 9a726db616325..e54738cf5dbd7 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/fixtures/ping_histogram_by_id.json +++ b/x-pack/test/api_integration/apis/uptime/rest/fixtures/ping_histogram_by_id.json @@ -1,121 +1,157 @@ { "histogram": [ { - "x": 1568172664000, + "x": 1568172657286, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568172694000, + "x": 1568172680087, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568172724000, + "x": 1568172702888, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568172754000, + "x": 1568172725689, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568172748490, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568172784000, + "x": 1568172771291, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568172814000, + "x": 1568172794092, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568172844000, + "x": 1568172816893, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568172839694, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568172874000, + "x": 1568172862495, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568172904000, + "x": 1568172885296, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568172934000, + "x": 1568172908097, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568172930898, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568172964000, + "x": 1568172953699, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568172994000, + "x": 1568172976500, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568173024000, + "x": 1568172999301, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568173022102, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568173054000, + "x": 1568173044903, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568173084000, + "x": 1568173067704, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568173114000, + "x": 1568173090505, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568173113306, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568173144000, + "x": 1568173136107, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568173174000, + "x": 1568173158908, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568173204000, + "x": 1568173181709, "downCount": 0, "upCount": 1, "y": 1 }, { - "x": 1568173234000, + "x": 1568173204510, + "downCount": 0, + "upCount": 0, + "y": 1 + }, + { + "x": 1568173227311, "downCount": 0, "upCount": 1, "y": 1 diff --git a/x-pack/test/api_integration/apis/uptime/rest/ping_histogram.ts b/x-pack/test/api_integration/apis/uptime/rest/ping_histogram.ts index ffcb1a829f0f8..b2504e3b921f7 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/ping_histogram.ts +++ b/x-pack/test/api_integration/apis/uptime/rest/ping_histogram.ts @@ -6,7 +6,6 @@ import { expectFixtureEql } from './helper/expect_fixture_eql'; import { FtrProviderContext } from '../../../ftr_provider_context'; -import { assertCloseTo } from '../../../../../plugins/uptime/server/lib/helper'; export default function ({ getService }: FtrProviderContext) { describe('pingHistogram', () => { @@ -21,10 +20,6 @@ export default function ({ getService }: FtrProviderContext) { ); const data = apiResponse.body; - // manually testing this value and then removing it to avoid flakiness - const { interval } = data; - assertCloseTo(interval, 22801, 100); - delete data.interval; expectFixtureEql(data, 'ping_histogram'); }); @@ -38,9 +33,6 @@ export default function ({ getService }: FtrProviderContext) { ); const data = apiResponse.body; - const { interval } = data; - assertCloseTo(interval, 22801, 100); - delete data.interval; expectFixtureEql(data, 'ping_histogram_by_id'); }); @@ -55,9 +47,6 @@ export default function ({ getService }: FtrProviderContext) { ); const data = apiResponse.body; - const { interval } = data; - assertCloseTo(interval, 22801, 100); - delete data.interval; expectFixtureEql(data, 'ping_histogram_by_filter'); }); }); diff --git a/x-pack/test/api_integration/services/index.ts b/x-pack/test/api_integration/services/index.ts index 75cc2b451ea2e..7113e117582dd 100644 --- a/x-pack/test/api_integration/services/index.ts +++ b/x-pack/test/api_integration/services/index.ts @@ -27,7 +27,6 @@ import { InfraOpsSourceConfigurationProvider } from './infraops_source_configura import { InfraLogSourceConfigurationProvider } from './infra_log_source_configuration'; import { MachineLearningProvider } from './ml'; import { IngestManagerProvider } from '../../common/services/ingest_manager'; -import { ResolverGeneratorProvider } from './resolver'; import { TransformProvider } from './transform'; export const services = { @@ -48,6 +47,5 @@ export const services = { usageAPI: UsageAPIProvider, ml: MachineLearningProvider, ingestManager: IngestManagerProvider, - resolverGenerator: ResolverGeneratorProvider, transform: TransformProvider, }; diff --git a/x-pack/test/apm_api_integration/basic/fixtures/es_archiver/observability_overview/data.json.gz b/x-pack/test/apm_api_integration/basic/fixtures/es_archiver/observability_overview/data.json.gz new file mode 100644 index 0000000000000..23602666f3b43 Binary files /dev/null and b/x-pack/test/apm_api_integration/basic/fixtures/es_archiver/observability_overview/data.json.gz differ diff --git a/x-pack/test/apm_api_integration/basic/fixtures/es_archiver/observability_overview/mappings.json b/x-pack/test/apm_api_integration/basic/fixtures/es_archiver/observability_overview/mappings.json new file mode 100644 index 0000000000000..e6f40fedaab4c --- /dev/null +++ b/x-pack/test/apm_api_integration/basic/fixtures/es_archiver/observability_overview/mappings.json @@ -0,0 +1,4229 @@ +{ + "type": "index", + "value": { + "aliases": { + }, + "index": "apm-8.0.0-onboarding-2020.06.29", + "mappings": { + "_meta": { + "beat": "apm", + "version": "8.0.0" + }, + "date_detection": false, + "dynamic_templates": [ + { + "labels": { + "mapping": { + "type": "keyword" + }, + "match_mapping_type": "string", + "path_match": "labels.*" + } + }, + { + "container.labels": { + "mapping": { + "type": "keyword" + }, + "match_mapping_type": "string", + "path_match": "container.labels.*" + } + }, + { + "dns.answers": { + "mapping": { + "type": "keyword" + }, + "match_mapping_type": "string", + "path_match": "dns.answers.*" + } + }, + { + "log.syslog": { + "mapping": { + "type": "keyword" + }, + "match_mapping_type": "string", + "path_match": "log.syslog.*" + } + }, + { + "network.inner": { + "mapping": { + "type": "keyword" + }, + "match_mapping_type": "string", + "path_match": "network.inner.*" + } + }, + { + "observer.egress": { + "mapping": { + "type": "keyword" + }, + "match_mapping_type": "string", + "path_match": "observer.egress.*" + } + }, + { + "observer.ingress": { + "mapping": { + "type": "keyword" + }, + "match_mapping_type": "string", + "path_match": "observer.ingress.*" + } + }, + { + "fields": { + "mapping": { + "type": "keyword" + }, + "match_mapping_type": "string", + "path_match": "fields.*" + } + }, + { + "docker.container.labels": { + "mapping": { + "type": "keyword" + }, + "match_mapping_type": "string", + "path_match": "docker.container.labels.*" + } + }, + { + "kubernetes.labels.*": { + "mapping": { + "type": "keyword" + }, + "path_match": "kubernetes.labels.*" + } + }, + { + "kubernetes.annotations.*": { + "mapping": { + "type": "keyword" + }, + "path_match": "kubernetes.annotations.*" + } + }, + { + "labels_string": { + "mapping": { + "type": "keyword" + }, + "match_mapping_type": "string", + "path_match": "labels.*" + } + }, + { + "labels_boolean": { + "mapping": { + "type": "boolean" + }, + "match_mapping_type": "boolean", + "path_match": "labels.*" + } + }, + { + "labels_*": { + "mapping": { + "scaling_factor": 1000000, + "type": "scaled_float" + }, + "path_match": "labels.*" + } + }, + { + "transaction.marks": { + "mapping": { + "type": "keyword" + }, + "match_mapping_type": "string", + "path_match": "transaction.marks.*" + } + }, + { + "transaction.marks.*.*": { + "mapping": { + "scaling_factor": 1000000, + "type": "scaled_float" + }, + "path_match": "transaction.marks.*.*" + } + }, + { + "strings_as_keyword": { + "mapping": { + "ignore_above": 1024, + "type": "keyword" + }, + "match_mapping_type": "string" + } + } + ], + "properties": { + "@timestamp": { + "type": "date" + }, + "agent": { + "dynamic": "false", + "properties": { + "ephemeral_id": { + "ignore_above": 1024, + "type": "keyword" + }, + "hostname": { + "path": "agent.name", + "type": "alias" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "as": { + "properties": { + "number": { + "type": "long" + }, + "organization": { + "properties": { + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "child": { + "dynamic": "false", + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "client": { + "dynamic": "false", + "properties": { + "address": { + "ignore_above": 1024, + "type": "keyword" + }, + "as": { + "properties": { + "number": { + "type": "long" + }, + "organization": { + "properties": { + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "bytes": { + "type": "long" + }, + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "geo": { + "properties": { + "city_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "continent_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "location": { + "type": "geo_point" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "ip": { + "type": "ip" + }, + "mac": { + "ignore_above": 1024, + "type": "keyword" + }, + "nat": { + "properties": { + "ip": { + "type": "ip" + }, + "port": { + "type": "long" + } + } + }, + "packets": { + "type": "long" + }, + "port": { + "type": "long" + }, + "registered_domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "top_level_domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "user": { + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "email": { + "ignore_above": 1024, + "type": "keyword" + }, + "full_name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "group": { + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "hash": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "cloud": { + "properties": { + "account": { + "dynamic": "false", + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "availability_zone": { + "ignore_above": 1024, + "type": "keyword" + }, + "image": { + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "instance": { + "dynamic": "false", + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "machine": { + "dynamic": "false", + "properties": { + "type": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "project": { + "dynamic": "false", + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "provider": { + "ignore_above": 1024, + "type": "keyword" + }, + "region": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "code_signature": { + "properties": { + "exists": { + "type": "boolean" + }, + "status": { + "ignore_above": 1024, + "type": "keyword" + }, + "subject_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "trusted": { + "type": "boolean" + }, + "valid": { + "type": "boolean" + } + } + }, + "container": { + "dynamic": "false", + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "image": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "tag": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "labels": { + "type": "object" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "runtime": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "destination": { + "properties": { + "address": { + "ignore_above": 1024, + "type": "keyword" + }, + "as": { + "properties": { + "number": { + "type": "long" + }, + "organization": { + "properties": { + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "bytes": { + "type": "long" + }, + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "geo": { + "properties": { + "city_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "continent_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "location": { + "type": "geo_point" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "ip": { + "type": "ip" + }, + "mac": { + "ignore_above": 1024, + "type": "keyword" + }, + "nat": { + "properties": { + "ip": { + "type": "ip" + }, + "port": { + "type": "long" + } + } + }, + "packets": { + "type": "long" + }, + "port": { + "type": "long" + }, + "registered_domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "top_level_domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "user": { + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "email": { + "ignore_above": 1024, + "type": "keyword" + }, + "full_name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "group": { + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "hash": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "dll": { + "properties": { + "code_signature": { + "properties": { + "exists": { + "type": "boolean" + }, + "status": { + "ignore_above": 1024, + "type": "keyword" + }, + "subject_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "trusted": { + "type": "boolean" + }, + "valid": { + "type": "boolean" + } + } + }, + "hash": { + "properties": { + "md5": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha1": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha256": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha512": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "path": { + "ignore_above": 1024, + "type": "keyword" + }, + "pe": { + "properties": { + "company": { + "ignore_above": 1024, + "type": "keyword" + }, + "description": { + "ignore_above": 1024, + "type": "keyword" + }, + "file_version": { + "ignore_above": 1024, + "type": "keyword" + }, + "original_file_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "product": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "dns": { + "properties": { + "answers": { + "properties": { + "class": { + "ignore_above": 1024, + "type": "keyword" + }, + "data": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "ttl": { + "type": "long" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "header_flags": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "op_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "question": { + "properties": { + "class": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "registered_domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "subdomain": { + "ignore_above": 1024, + "type": "keyword" + }, + "top_level_domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "resolved_ip": { + "type": "ip" + }, + "response_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "docker": { + "properties": { + "container": { + "properties": { + "labels": { + "type": "object" + } + } + } + } + }, + "ecs": { + "properties": { + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "error": { + "dynamic": "false", + "properties": { + "code": { + "ignore_above": 1024, + "type": "keyword" + }, + "culprit": { + "ignore_above": 1024, + "type": "keyword" + }, + "exception": { + "properties": { + "code": { + "ignore_above": 1024, + "type": "keyword" + }, + "handled": { + "type": "boolean" + }, + "message": { + "norms": false, + "type": "text" + }, + "module": { + "ignore_above": 1024, + "type": "keyword" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "grouping_key": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "log": { + "properties": { + "level": { + "ignore_above": 1024, + "type": "keyword" + }, + "logger_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "message": { + "norms": false, + "type": "text" + }, + "param_message": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "message": { + "norms": false, + "type": "text" + }, + "stack_trace": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "event": { + "properties": { + "action": { + "ignore_above": 1024, + "type": "keyword" + }, + "category": { + "ignore_above": 1024, + "type": "keyword" + }, + "code": { + "ignore_above": 1024, + "type": "keyword" + }, + "created": { + "type": "date" + }, + "dataset": { + "ignore_above": 1024, + "type": "keyword" + }, + "duration": { + "type": "long" + }, + "end": { + "type": "date" + }, + "hash": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "ingested": { + "type": "date" + }, + "kind": { + "ignore_above": 1024, + "type": "keyword" + }, + "module": { + "ignore_above": 1024, + "type": "keyword" + }, + "original": { + "ignore_above": 1024, + "type": "keyword" + }, + "outcome": { + "ignore_above": 1024, + "type": "keyword" + }, + "provider": { + "ignore_above": 1024, + "type": "keyword" + }, + "reference": { + "ignore_above": 1024, + "type": "keyword" + }, + "risk_score": { + "type": "float" + }, + "risk_score_norm": { + "type": "float" + }, + "sequence": { + "type": "long" + }, + "severity": { + "type": "long" + }, + "start": { + "type": "date" + }, + "timezone": { + "ignore_above": 1024, + "type": "keyword" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + }, + "url": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "experimental": { + "dynamic": "true", + "type": "object" + }, + "fields": { + "type": "object" + }, + "file": { + "properties": { + "accessed": { + "type": "date" + }, + "attributes": { + "ignore_above": 1024, + "type": "keyword" + }, + "code_signature": { + "properties": { + "exists": { + "type": "boolean" + }, + "status": { + "ignore_above": 1024, + "type": "keyword" + }, + "subject_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "trusted": { + "type": "boolean" + }, + "valid": { + "type": "boolean" + } + } + }, + "created": { + "type": "date" + }, + "ctime": { + "type": "date" + }, + "device": { + "ignore_above": 1024, + "type": "keyword" + }, + "directory": { + "ignore_above": 1024, + "type": "keyword" + }, + "drive_letter": { + "ignore_above": 1, + "type": "keyword" + }, + "extension": { + "ignore_above": 1024, + "type": "keyword" + }, + "gid": { + "ignore_above": 1024, + "type": "keyword" + }, + "group": { + "ignore_above": 1024, + "type": "keyword" + }, + "hash": { + "properties": { + "md5": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha1": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha256": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha512": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "inode": { + "ignore_above": 1024, + "type": "keyword" + }, + "mime_type": { + "ignore_above": 1024, + "type": "keyword" + }, + "mode": { + "ignore_above": 1024, + "type": "keyword" + }, + "mtime": { + "type": "date" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "owner": { + "ignore_above": 1024, + "type": "keyword" + }, + "path": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "pe": { + "properties": { + "company": { + "ignore_above": 1024, + "type": "keyword" + }, + "description": { + "ignore_above": 1024, + "type": "keyword" + }, + "file_version": { + "ignore_above": 1024, + "type": "keyword" + }, + "original_file_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "product": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "size": { + "type": "long" + }, + "target_path": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + }, + "uid": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "geo": { + "properties": { + "city_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "continent_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "location": { + "type": "geo_point" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "group": { + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "hash": { + "properties": { + "md5": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha1": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha256": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha512": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "host": { + "dynamic": "false", + "properties": { + "architecture": { + "ignore_above": 1024, + "type": "keyword" + }, + "containerized": { + "type": "boolean" + }, + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "geo": { + "properties": { + "city_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "continent_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "location": { + "type": "geo_point" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "hostname": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "ip": { + "type": "ip" + }, + "mac": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "os": { + "properties": { + "build": { + "ignore_above": 1024, + "type": "keyword" + }, + "codename": { + "ignore_above": 1024, + "type": "keyword" + }, + "family": { + "ignore_above": 1024, + "type": "keyword" + }, + "full": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "kernel": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "platform": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + }, + "uptime": { + "type": "long" + }, + "user": { + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "email": { + "ignore_above": 1024, + "type": "keyword" + }, + "full_name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "group": { + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "hash": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "http": { + "dynamic": "false", + "properties": { + "request": { + "properties": { + "body": { + "properties": { + "bytes": { + "type": "long" + }, + "content": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "bytes": { + "type": "long" + }, + "headers": { + "enabled": false, + "type": "object" + }, + "method": { + "ignore_above": 1024, + "type": "keyword" + }, + "referrer": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "response": { + "properties": { + "body": { + "properties": { + "bytes": { + "type": "long" + }, + "content": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "bytes": { + "type": "long" + }, + "finished": { + "type": "boolean" + }, + "headers": { + "enabled": false, + "type": "object" + }, + "status_code": { + "type": "long" + } + } + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "interface": { + "properties": { + "alias": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "kubernetes": { + "dynamic": "false", + "properties": { + "annotations": { + "properties": { + "*": { + "type": "object" + } + } + }, + "container": { + "properties": { + "image": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "deployment": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "labels": { + "properties": { + "*": { + "type": "object" + } + } + }, + "namespace": { + "ignore_above": 1024, + "type": "keyword" + }, + "node": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "pod": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "uid": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "replicaset": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "statefulset": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "labels": { + "dynamic": "true", + "type": "object" + }, + "log": { + "properties": { + "level": { + "ignore_above": 1024, + "type": "keyword" + }, + "logger": { + "ignore_above": 1024, + "type": "keyword" + }, + "origin": { + "properties": { + "file": { + "properties": { + "line": { + "type": "long" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "function": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "original": { + "ignore_above": 1024, + "type": "keyword" + }, + "syslog": { + "properties": { + "facility": { + "properties": { + "code": { + "type": "long" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "priority": { + "type": "long" + }, + "severity": { + "properties": { + "code": { + "type": "long" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + } + } + }, + "message": { + "norms": false, + "type": "text" + }, + "network": { + "properties": { + "application": { + "ignore_above": 1024, + "type": "keyword" + }, + "bytes": { + "type": "long" + }, + "community_id": { + "ignore_above": 1024, + "type": "keyword" + }, + "direction": { + "ignore_above": 1024, + "type": "keyword" + }, + "forwarded_ip": { + "type": "ip" + }, + "iana_number": { + "ignore_above": 1024, + "type": "keyword" + }, + "inner": { + "properties": { + "vlan": { + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "packets": { + "type": "long" + }, + "protocol": { + "ignore_above": 1024, + "type": "keyword" + }, + "transport": { + "ignore_above": 1024, + "type": "keyword" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + }, + "vlan": { + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "observer": { + "dynamic": "false", + "properties": { + "egress": { + "properties": { + "interface": { + "properties": { + "alias": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "vlan": { + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "zone": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "geo": { + "properties": { + "city_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "continent_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "location": { + "type": "geo_point" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "hostname": { + "ignore_above": 1024, + "type": "keyword" + }, + "ingress": { + "properties": { + "interface": { + "properties": { + "alias": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "vlan": { + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "zone": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "ip": { + "type": "ip" + }, + "listening": { + "ignore_above": 1024, + "type": "keyword" + }, + "mac": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "os": { + "properties": { + "family": { + "ignore_above": 1024, + "type": "keyword" + }, + "full": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "kernel": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "platform": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "product": { + "ignore_above": 1024, + "type": "keyword" + }, + "serial_number": { + "ignore_above": 1024, + "type": "keyword" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + }, + "vendor": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + }, + "version_major": { + "type": "byte" + } + } + }, + "organization": { + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "os": { + "properties": { + "family": { + "ignore_above": 1024, + "type": "keyword" + }, + "full": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "kernel": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "platform": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "package": { + "properties": { + "architecture": { + "ignore_above": 1024, + "type": "keyword" + }, + "build_version": { + "ignore_above": 1024, + "type": "keyword" + }, + "checksum": { + "ignore_above": 1024, + "type": "keyword" + }, + "description": { + "ignore_above": 1024, + "type": "keyword" + }, + "install_scope": { + "ignore_above": 1024, + "type": "keyword" + }, + "installed": { + "type": "date" + }, + "license": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "path": { + "ignore_above": 1024, + "type": "keyword" + }, + "reference": { + "ignore_above": 1024, + "type": "keyword" + }, + "size": { + "type": "long" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "parent": { + "dynamic": "false", + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "pe": { + "properties": { + "company": { + "ignore_above": 1024, + "type": "keyword" + }, + "description": { + "ignore_above": 1024, + "type": "keyword" + }, + "file_version": { + "ignore_above": 1024, + "type": "keyword" + }, + "original_file_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "product": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "process": { + "dynamic": "false", + "properties": { + "args": { + "ignore_above": 1024, + "type": "keyword" + }, + "args_count": { + "type": "long" + }, + "code_signature": { + "properties": { + "exists": { + "type": "boolean" + }, + "status": { + "ignore_above": 1024, + "type": "keyword" + }, + "subject_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "trusted": { + "type": "boolean" + }, + "valid": { + "type": "boolean" + } + } + }, + "command_line": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "entity_id": { + "ignore_above": 1024, + "type": "keyword" + }, + "executable": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "exit_code": { + "type": "long" + }, + "hash": { + "properties": { + "md5": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha1": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha256": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha512": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "parent": { + "properties": { + "args": { + "ignore_above": 1024, + "type": "keyword" + }, + "args_count": { + "type": "long" + }, + "code_signature": { + "properties": { + "exists": { + "type": "boolean" + }, + "status": { + "ignore_above": 1024, + "type": "keyword" + }, + "subject_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "trusted": { + "type": "boolean" + }, + "valid": { + "type": "boolean" + } + } + }, + "command_line": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "entity_id": { + "ignore_above": 1024, + "type": "keyword" + }, + "executable": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "exit_code": { + "type": "long" + }, + "hash": { + "properties": { + "md5": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha1": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha256": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha512": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "pgid": { + "type": "long" + }, + "pid": { + "type": "long" + }, + "ppid": { + "type": "long" + }, + "start": { + "type": "date" + }, + "thread": { + "properties": { + "id": { + "type": "long" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "title": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "uptime": { + "type": "long" + }, + "working_directory": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "pe": { + "properties": { + "company": { + "ignore_above": 1024, + "type": "keyword" + }, + "description": { + "ignore_above": 1024, + "type": "keyword" + }, + "file_version": { + "ignore_above": 1024, + "type": "keyword" + }, + "original_file_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "product": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "pgid": { + "type": "long" + }, + "pid": { + "type": "long" + }, + "ppid": { + "type": "long" + }, + "start": { + "type": "date" + }, + "thread": { + "properties": { + "id": { + "type": "long" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "title": { + "ignore_above": 1024, + "type": "keyword" + }, + "uptime": { + "type": "long" + }, + "working_directory": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "processor": { + "properties": { + "event": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "profile": { + "dynamic": "false", + "properties": { + "alloc_objects": { + "properties": { + "count": { + "type": "long" + } + } + }, + "alloc_space": { + "properties": { + "bytes": { + "type": "long" + } + } + }, + "cpu": { + "properties": { + "ns": { + "type": "long" + } + } + }, + "duration": { + "type": "long" + }, + "inuse_objects": { + "properties": { + "count": { + "type": "long" + } + } + }, + "inuse_space": { + "properties": { + "bytes": { + "type": "long" + } + } + }, + "samples": { + "properties": { + "count": { + "type": "long" + } + } + }, + "stack": { + "dynamic": "false", + "properties": { + "filename": { + "ignore_above": 1024, + "type": "keyword" + }, + "function": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "line": { + "type": "long" + } + } + }, + "top": { + "dynamic": "false", + "properties": { + "filename": { + "ignore_above": 1024, + "type": "keyword" + }, + "function": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "line": { + "type": "long" + } + } + } + } + }, + "registry": { + "properties": { + "data": { + "properties": { + "bytes": { + "ignore_above": 1024, + "type": "keyword" + }, + "strings": { + "ignore_above": 1024, + "type": "keyword" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "hive": { + "ignore_above": 1024, + "type": "keyword" + }, + "key": { + "ignore_above": 1024, + "type": "keyword" + }, + "path": { + "ignore_above": 1024, + "type": "keyword" + }, + "value": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "related": { + "properties": { + "hash": { + "ignore_above": 1024, + "type": "keyword" + }, + "ip": { + "type": "ip" + }, + "user": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "rule": { + "properties": { + "author": { + "ignore_above": 1024, + "type": "keyword" + }, + "category": { + "ignore_above": 1024, + "type": "keyword" + }, + "description": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "license": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "reference": { + "ignore_above": 1024, + "type": "keyword" + }, + "ruleset": { + "ignore_above": 1024, + "type": "keyword" + }, + "uuid": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "server": { + "properties": { + "address": { + "ignore_above": 1024, + "type": "keyword" + }, + "as": { + "properties": { + "number": { + "type": "long" + }, + "organization": { + "properties": { + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "bytes": { + "type": "long" + }, + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "geo": { + "properties": { + "city_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "continent_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "location": { + "type": "geo_point" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "ip": { + "type": "ip" + }, + "mac": { + "ignore_above": 1024, + "type": "keyword" + }, + "nat": { + "properties": { + "ip": { + "type": "ip" + }, + "port": { + "type": "long" + } + } + }, + "packets": { + "type": "long" + }, + "port": { + "type": "long" + }, + "registered_domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "top_level_domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "user": { + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "email": { + "ignore_above": 1024, + "type": "keyword" + }, + "full_name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "group": { + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "hash": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "service": { + "dynamic": "false", + "properties": { + "environment": { + "ignore_above": 1024, + "type": "keyword" + }, + "ephemeral_id": { + "ignore_above": 1024, + "type": "keyword" + }, + "framework": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "language": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "node": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "runtime": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "state": { + "ignore_above": 1024, + "type": "keyword" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "source": { + "dynamic": "false", + "properties": { + "address": { + "ignore_above": 1024, + "type": "keyword" + }, + "as": { + "properties": { + "number": { + "type": "long" + }, + "organization": { + "properties": { + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "bytes": { + "type": "long" + }, + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "geo": { + "properties": { + "city_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "continent_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "country_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "location": { + "type": "geo_point" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_iso_code": { + "ignore_above": 1024, + "type": "keyword" + }, + "region_name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "ip": { + "type": "ip" + }, + "mac": { + "ignore_above": 1024, + "type": "keyword" + }, + "nat": { + "properties": { + "ip": { + "type": "ip" + }, + "port": { + "type": "long" + } + } + }, + "packets": { + "type": "long" + }, + "port": { + "type": "long" + }, + "registered_domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "top_level_domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "user": { + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "email": { + "ignore_above": 1024, + "type": "keyword" + }, + "full_name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "group": { + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "hash": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "sourcemap": { + "dynamic": "false", + "properties": { + "bundle_filepath": { + "ignore_above": 1024, + "type": "keyword" + }, + "service": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "span": { + "dynamic": "false", + "properties": { + "action": { + "ignore_above": 1024, + "type": "keyword" + }, + "db": { + "dynamic": "false", + "properties": { + "link": { + "ignore_above": 1024, + "type": "keyword" + }, + "rows_affected": { + "type": "long" + } + } + }, + "destination": { + "dynamic": "false", + "properties": { + "service": { + "dynamic": "false", + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "resource": { + "ignore_above": 1024, + "type": "keyword" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "duration": { + "properties": { + "us": { + "type": "long" + } + } + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "message": { + "dynamic": "false", + "properties": { + "age": { + "properties": { + "ms": { + "type": "long" + } + } + }, + "queue": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "self_time": { + "properties": { + "count": { + "type": "long" + }, + "sum": { + "properties": { + "us": { + "type": "long" + } + } + } + } + }, + "start": { + "properties": { + "us": { + "type": "long" + } + } + }, + "subtype": { + "ignore_above": 1024, + "type": "keyword" + }, + "sync": { + "type": "boolean" + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "system": { + "properties": { + "cpu": { + "properties": { + "total": { + "properties": { + "norm": { + "properties": { + "pct": { + "scaling_factor": 1000, + "type": "scaled_float" + } + } + } + } + } + } + }, + "memory": { + "properties": { + "actual": { + "properties": { + "free": { + "type": "long" + } + } + }, + "total": { + "type": "long" + } + } + }, + "process": { + "properties": { + "cpu": { + "properties": { + "total": { + "properties": { + "norm": { + "properties": { + "pct": { + "scaling_factor": 1000, + "type": "scaled_float" + } + } + } + } + } + } + }, + "memory": { + "properties": { + "rss": { + "properties": { + "bytes": { + "type": "long" + } + } + }, + "size": { + "type": "long" + } + } + } + } + } + } + }, + "tags": { + "ignore_above": 1024, + "type": "keyword" + }, + "threat": { + "properties": { + "framework": { + "ignore_above": 1024, + "type": "keyword" + }, + "tactic": { + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "reference": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "technique": { + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "reference": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "timeseries": { + "properties": { + "instance": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "timestamp": { + "properties": { + "us": { + "type": "long" + } + } + }, + "tls": { + "properties": { + "cipher": { + "ignore_above": 1024, + "type": "keyword" + }, + "client": { + "properties": { + "certificate": { + "ignore_above": 1024, + "type": "keyword" + }, + "certificate_chain": { + "ignore_above": 1024, + "type": "keyword" + }, + "hash": { + "properties": { + "md5": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha1": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha256": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "issuer": { + "ignore_above": 1024, + "type": "keyword" + }, + "ja3": { + "ignore_above": 1024, + "type": "keyword" + }, + "not_after": { + "type": "date" + }, + "not_before": { + "type": "date" + }, + "server_name": { + "ignore_above": 1024, + "type": "keyword" + }, + "subject": { + "ignore_above": 1024, + "type": "keyword" + }, + "supported_ciphers": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "curve": { + "ignore_above": 1024, + "type": "keyword" + }, + "established": { + "type": "boolean" + }, + "next_protocol": { + "ignore_above": 1024, + "type": "keyword" + }, + "resumed": { + "type": "boolean" + }, + "server": { + "properties": { + "certificate": { + "ignore_above": 1024, + "type": "keyword" + }, + "certificate_chain": { + "ignore_above": 1024, + "type": "keyword" + }, + "hash": { + "properties": { + "md5": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha1": { + "ignore_above": 1024, + "type": "keyword" + }, + "sha256": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "issuer": { + "ignore_above": 1024, + "type": "keyword" + }, + "ja3s": { + "ignore_above": 1024, + "type": "keyword" + }, + "not_after": { + "type": "date" + }, + "not_before": { + "type": "date" + }, + "subject": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + }, + "version_protocol": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "trace": { + "dynamic": "false", + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "tracing": { + "properties": { + "trace": { + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "transaction": { + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "transaction": { + "dynamic": "false", + "properties": { + "breakdown": { + "properties": { + "count": { + "type": "long" + } + } + }, + "duration": { + "properties": { + "count": { + "type": "long" + }, + "histogram": { + "type": "histogram" + }, + "sum": { + "properties": { + "us": { + "type": "long" + } + } + }, + "us": { + "type": "long" + } + } + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "marks": { + "dynamic": "true", + "properties": { + "*": { + "properties": { + "*": { + "dynamic": "true", + "type": "object" + } + } + } + } + }, + "message": { + "dynamic": "false", + "properties": { + "age": { + "properties": { + "ms": { + "type": "long" + } + } + }, + "queue": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "result": { + "ignore_above": 1024, + "type": "keyword" + }, + "root": { + "type": "boolean" + }, + "sampled": { + "type": "boolean" + }, + "self_time": { + "properties": { + "count": { + "type": "long" + }, + "sum": { + "properties": { + "us": { + "type": "long" + } + } + } + } + }, + "span_count": { + "properties": { + "dropped": { + "type": "long" + } + } + }, + "type": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "url": { + "dynamic": "false", + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "extension": { + "ignore_above": 1024, + "type": "keyword" + }, + "fragment": { + "ignore_above": 1024, + "type": "keyword" + }, + "full": { + "ignore_above": 1024, + "type": "keyword" + }, + "original": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "password": { + "ignore_above": 1024, + "type": "keyword" + }, + "path": { + "ignore_above": 1024, + "type": "keyword" + }, + "port": { + "type": "long" + }, + "query": { + "ignore_above": 1024, + "type": "keyword" + }, + "registered_domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "scheme": { + "ignore_above": 1024, + "type": "keyword" + }, + "top_level_domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "username": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "user": { + "dynamic": "false", + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "email": { + "ignore_above": 1024, + "type": "keyword" + }, + "full_name": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "group": { + "properties": { + "domain": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "hash": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "user_agent": { + "dynamic": "false", + "properties": { + "device": { + "properties": { + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "original": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "os": { + "properties": { + "family": { + "ignore_above": 1024, + "type": "keyword" + }, + "full": { + "ignore_above": 1024, + "type": "keyword" + }, + "kernel": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "platform": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "view spans": { + "ignore_above": 1024, + "type": "keyword" + }, + "vlan": { + "properties": { + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "vulnerability": { + "properties": { + "category": { + "ignore_above": 1024, + "type": "keyword" + }, + "classification": { + "ignore_above": 1024, + "type": "keyword" + }, + "description": { + "fields": { + "text": { + "norms": false, + "type": "text" + } + }, + "ignore_above": 1024, + "type": "keyword" + }, + "enumeration": { + "ignore_above": 1024, + "type": "keyword" + }, + "id": { + "ignore_above": 1024, + "type": "keyword" + }, + "reference": { + "ignore_above": 1024, + "type": "keyword" + }, + "report_id": { + "ignore_above": 1024, + "type": "keyword" + }, + "scanner": { + "properties": { + "vendor": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "score": { + "properties": { + "base": { + "type": "float" + }, + "environmental": { + "type": "float" + }, + "temporal": { + "type": "float" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "severity": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + }, + "settings": { + "index": { + "codec": "best_compression", + "mapping": { + "total_fields": { + "limit": "2000" + } + }, + "number_of_replicas": "0", + "number_of_shards": "1", + "query": { + "default_field": [ + "message", + "tags", + "agent.ephemeral_id", + "agent.id", + "agent.name", + "agent.type", + "agent.version", + "as.organization.name", + "client.address", + "client.as.organization.name", + "client.domain", + "client.geo.city_name", + "client.geo.continent_name", + "client.geo.country_iso_code", + "client.geo.country_name", + "client.geo.name", + "client.geo.region_iso_code", + "client.geo.region_name", + "client.mac", + "client.registered_domain", + "client.top_level_domain", + "client.user.domain", + "client.user.email", + "client.user.full_name", + "client.user.group.domain", + "client.user.group.id", + "client.user.group.name", + "client.user.hash", + "client.user.id", + "client.user.name", + "cloud.account.id", + "cloud.availability_zone", + "cloud.instance.id", + "cloud.instance.name", + "cloud.machine.type", + "cloud.provider", + "cloud.region", + "container.id", + "container.image.name", + "container.image.tag", + "container.name", + "container.runtime", + "destination.address", + "destination.as.organization.name", + "destination.domain", + "destination.geo.city_name", + "destination.geo.continent_name", + "destination.geo.country_iso_code", + "destination.geo.country_name", + "destination.geo.name", + "destination.geo.region_iso_code", + "destination.geo.region_name", + "destination.mac", + "destination.registered_domain", + "destination.top_level_domain", + "destination.user.domain", + "destination.user.email", + "destination.user.full_name", + "destination.user.group.domain", + "destination.user.group.id", + "destination.user.group.name", + "destination.user.hash", + "destination.user.id", + "destination.user.name", + "dns.answers.class", + "dns.answers.data", + "dns.answers.name", + "dns.answers.type", + "dns.header_flags", + "dns.id", + "dns.op_code", + "dns.question.class", + "dns.question.name", + "dns.question.registered_domain", + "dns.question.subdomain", + "dns.question.top_level_domain", + "dns.question.type", + "dns.response_code", + "dns.type", + "ecs.version", + "error.code", + "error.id", + "error.message", + "error.stack_trace", + "error.type", + "event.action", + "event.category", + "event.code", + "event.dataset", + "event.hash", + "event.id", + "event.kind", + "event.module", + "event.original", + "event.outcome", + "event.provider", + "event.timezone", + "event.type", + "file.device", + "file.directory", + "file.extension", + "file.gid", + "file.group", + "file.hash.md5", + "file.hash.sha1", + "file.hash.sha256", + "file.hash.sha512", + "file.inode", + "file.mode", + "file.name", + "file.owner", + "file.path", + "file.target_path", + "file.type", + "file.uid", + "geo.city_name", + "geo.continent_name", + "geo.country_iso_code", + "geo.country_name", + "geo.name", + "geo.region_iso_code", + "geo.region_name", + "group.domain", + "group.id", + "group.name", + "hash.md5", + "hash.sha1", + "hash.sha256", + "hash.sha512", + "host.architecture", + "host.geo.city_name", + "host.geo.continent_name", + "host.geo.country_iso_code", + "host.geo.country_name", + "host.geo.name", + "host.geo.region_iso_code", + "host.geo.region_name", + "host.hostname", + "host.id", + "host.mac", + "host.name", + "host.os.family", + "host.os.full", + "host.os.kernel", + "host.os.name", + "host.os.platform", + "host.os.version", + "host.type", + "host.user.domain", + "host.user.email", + "host.user.full_name", + "host.user.group.domain", + "host.user.group.id", + "host.user.group.name", + "host.user.hash", + "host.user.id", + "host.user.name", + "http.request.body.content", + "http.request.method", + "http.request.referrer", + "http.response.body.content", + "http.version", + "log.level", + "log.logger", + "log.origin.file.name", + "log.origin.function", + "log.original", + "log.syslog.facility.name", + "log.syslog.severity.name", + "network.application", + "network.community_id", + "network.direction", + "network.iana_number", + "network.name", + "network.protocol", + "network.transport", + "network.type", + "observer.geo.city_name", + "observer.geo.continent_name", + "observer.geo.country_iso_code", + "observer.geo.country_name", + "observer.geo.name", + "observer.geo.region_iso_code", + "observer.geo.region_name", + "observer.hostname", + "observer.mac", + "observer.name", + "observer.os.family", + "observer.os.full", + "observer.os.kernel", + "observer.os.name", + "observer.os.platform", + "observer.os.version", + "observer.product", + "observer.serial_number", + "observer.type", + "observer.vendor", + "observer.version", + "organization.id", + "organization.name", + "os.family", + "os.full", + "os.kernel", + "os.name", + "os.platform", + "os.version", + "package.architecture", + "package.checksum", + "package.description", + "package.install_scope", + "package.license", + "package.name", + "package.path", + "package.version", + "process.args", + "text", + "process.executable", + "process.hash.md5", + "process.hash.sha1", + "process.hash.sha256", + "process.hash.sha512", + "process.name", + "text", + "text", + "text", + "text", + "text", + "process.thread.name", + "process.title", + "process.working_directory", + "server.address", + "server.as.organization.name", + "server.domain", + "server.geo.city_name", + "server.geo.continent_name", + "server.geo.country_iso_code", + "server.geo.country_name", + "server.geo.name", + "server.geo.region_iso_code", + "server.geo.region_name", + "server.mac", + "server.registered_domain", + "server.top_level_domain", + "server.user.domain", + "server.user.email", + "server.user.full_name", + "server.user.group.domain", + "server.user.group.id", + "server.user.group.name", + "server.user.hash", + "server.user.id", + "server.user.name", + "service.ephemeral_id", + "service.id", + "service.name", + "service.node.name", + "service.state", + "service.type", + "service.version", + "source.address", + "source.as.organization.name", + "source.domain", + "source.geo.city_name", + "source.geo.continent_name", + "source.geo.country_iso_code", + "source.geo.country_name", + "source.geo.name", + "source.geo.region_iso_code", + "source.geo.region_name", + "source.mac", + "source.registered_domain", + "source.top_level_domain", + "source.user.domain", + "source.user.email", + "source.user.full_name", + "source.user.group.domain", + "source.user.group.id", + "source.user.group.name", + "source.user.hash", + "source.user.id", + "source.user.name", + "threat.framework", + "threat.tactic.id", + "threat.tactic.name", + "threat.tactic.reference", + "threat.technique.id", + "threat.technique.name", + "threat.technique.reference", + "tracing.trace.id", + "tracing.transaction.id", + "url.domain", + "url.extension", + "url.fragment", + "url.full", + "url.original", + "url.password", + "url.path", + "url.query", + "url.registered_domain", + "url.scheme", + "url.top_level_domain", + "url.username", + "user.domain", + "user.email", + "user.full_name", + "user.group.domain", + "user.group.id", + "user.group.name", + "user.hash", + "user.id", + "user.name", + "user_agent.device.name", + "user_agent.name", + "text", + "user_agent.original", + "user_agent.os.family", + "user_agent.os.full", + "user_agent.os.kernel", + "user_agent.os.name", + "user_agent.os.platform", + "user_agent.os.version", + "user_agent.version", + "text", + "timeseries.instance", + "cloud.project.id", + "cloud.image.id", + "host.os.build", + "host.os.codename", + "kubernetes.pod.name", + "kubernetes.pod.uid", + "kubernetes.namespace", + "kubernetes.node.name", + "kubernetes.replicaset.name", + "kubernetes.deployment.name", + "kubernetes.statefulset.name", + "kubernetes.container.name", + "kubernetes.container.image", + "processor.name", + "processor.event", + "url.scheme", + "url.full", + "url.domain", + "url.path", + "url.query", + "url.fragment", + "http.version", + "http.request.method", + "http.request.referrer", + "service.name", + "service.version", + "service.environment", + "service.node.name", + "service.language.name", + "service.language.version", + "service.runtime.name", + "service.runtime.version", + "service.framework.name", + "service.framework.version", + "transaction.id", + "transaction.type", + "text", + "transaction.name", + "span.type", + "span.subtype", + "trace.id", + "parent.id", + "agent.name", + "agent.version", + "agent.ephemeral_id", + "container.id", + "kubernetes.namespace", + "kubernetes.node.name", + "kubernetes.pod.name", + "kubernetes.pod.uid", + "host.architecture", + "host.hostname", + "host.name", + "host.os.platform", + "process.args", + "process.title", + "observer.listening", + "observer.hostname", + "observer.version", + "observer.type", + "user.name", + "user.id", + "user.email", + "destination.address", + "text", + "user_agent.original", + "user_agent.name", + "user_agent.version", + "user_agent.device.name", + "user_agent.os.platform", + "user_agent.os.name", + "user_agent.os.full", + "user_agent.os.family", + "user_agent.os.version", + "user_agent.os.kernel", + "cloud.account.id", + "cloud.account.name", + "cloud.availability_zone", + "cloud.instance.id", + "cloud.instance.name", + "cloud.machine.type", + "cloud.project.id", + "cloud.project.name", + "cloud.provider", + "cloud.region", + "error.id", + "error.culprit", + "error.grouping_key", + "error.exception.code", + "error.exception.message", + "error.exception.module", + "error.exception.type", + "error.log.level", + "error.log.logger_name", + "error.log.message", + "error.log.param_message", + "profile.top.id", + "profile.top.function", + "profile.top.filename", + "profile.stack.id", + "profile.stack.function", + "profile.stack.filename", + "sourcemap.service.name", + "sourcemap.service.version", + "sourcemap.bundle_filepath", + "view spans", + "child.id", + "span.id", + "span.name", + "span.action", + "span.db.link", + "span.destination.service.type", + "span.destination.service.name", + "span.destination.service.resource", + "span.message.queue.name", + "transaction.result", + "transaction.message.queue.name", + "fields.*" + ] + }, + "refresh_interval": "1ms" + } + } + } +} \ No newline at end of file diff --git a/x-pack/test/apm_api_integration/basic/tests/index.ts b/x-pack/test/apm_api_integration/basic/tests/index.ts index 873aa478ad080..b6a32ace5db56 100644 --- a/x-pack/test/apm_api_integration/basic/tests/index.ts +++ b/x-pack/test/apm_api_integration/basic/tests/index.ts @@ -35,6 +35,13 @@ export default function apmApiIntegrationTests({ loadTestFile }: FtrProviderCont loadTestFile(require.resolve('./transaction_groups/top_transaction_groups')); loadTestFile(require.resolve('./transaction_groups/transaction_charts')); loadTestFile(require.resolve('./transaction_groups/error_rate')); + loadTestFile(require.resolve('./transaction_groups/breakdown')); + loadTestFile(require.resolve('./transaction_groups/avg_duration_by_browser')); + }); + + describe('Observability overview', function () { + loadTestFile(require.resolve('./observability_overview/has_data')); + loadTestFile(require.resolve('./observability_overview/observability_overview')); }); }); } diff --git a/x-pack/test/apm_api_integration/basic/tests/observability_overview/has_data.ts b/x-pack/test/apm_api_integration/basic/tests/observability_overview/has_data.ts new file mode 100644 index 0000000000000..127721e8e2112 --- /dev/null +++ b/x-pack/test/apm_api_integration/basic/tests/observability_overview/has_data.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../common/ftr_provider_context'; + +export default function ApiTest({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const esArchiver = getService('esArchiver'); + + describe('Has data', () => { + describe('when data is not loaded', () => { + it('returns false when there is no data', async () => { + const response = await supertest.get('/api/apm/observability_overview/has_data'); + expect(response.status).to.be(200); + expect(response.body).to.eql(false); + }); + }); + describe('when only onboarding data is loaded', () => { + before(() => esArchiver.load('observability_overview')); + after(() => esArchiver.unload('observability_overview')); + it('returns false when there is only onboarding data', async () => { + const response = await supertest.get('/api/apm/observability_overview/has_data'); + expect(response.status).to.be(200); + expect(response.body).to.eql(false); + }); + }); + describe('when data is loaded', () => { + before(() => esArchiver.load('8.0.0')); + after(() => esArchiver.unload('8.0.0')); + + it('returns true when there is at least one document on transaction, error or metrics indices', async () => { + const response = await supertest.get('/api/apm/observability_overview/has_data'); + expect(response.status).to.be(200); + expect(response.body).to.eql(true); + }); + }); + }); +} diff --git a/x-pack/test/apm_api_integration/basic/tests/observability_overview/observability_overview.ts b/x-pack/test/apm_api_integration/basic/tests/observability_overview/observability_overview.ts new file mode 100644 index 0000000000000..bd8b0c6126faa --- /dev/null +++ b/x-pack/test/apm_api_integration/basic/tests/observability_overview/observability_overview.ts @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../common/ftr_provider_context'; + +export default function ApiTest({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const esArchiver = getService('esArchiver'); + + // url parameters + const start = encodeURIComponent('2020-06-29T06:00:00.000Z'); + const end = encodeURIComponent('2020-06-29T10:00:00.000Z'); + const bucketSize = '60s'; + + describe('Observability overview', () => { + describe('when data is not loaded', () => { + it('handles the empty state', async () => { + const response = await supertest.get( + `/api/apm/observability_overview?start=${start}&end=${end}&bucketSize=${bucketSize}` + ); + expect(response.status).to.be(200); + expect(response.body).to.eql({ serviceCount: 0, transactionCoordinates: [] }); + }); + }); + describe('when data is loaded', () => { + before(() => esArchiver.load('8.0.0')); + after(() => esArchiver.unload('8.0.0')); + + it('returns the service count and transaction coordinates', async () => { + const response = await supertest.get( + `/api/apm/observability_overview?start=${start}&end=${end}&bucketSize=${bucketSize}` + ); + expect(response.status).to.be(200); + expect(response.body).to.eql({ + serviceCount: 3, + transactionCoordinates: [ + { x: 1593413220000, y: 0.016666666666666666 }, + { x: 1593413280000, y: 1.0458333333333334 }, + ], + }); + }); + }); + }); +} diff --git a/x-pack/test/apm_api_integration/basic/tests/traces/expectation/top_traces.expectation.json b/x-pack/test/apm_api_integration/basic/tests/traces/expectation/top_traces.expectation.json index bacb340292f93..4db040e92e7fa 100644 --- a/x-pack/test/apm_api_integration/basic/tests/traces/expectation/top_traces.expectation.json +++ b/x-pack/test/apm_api_integration/basic/tests/traces/expectation/top_traces.expectation.json @@ -1,20 +1,35 @@ [ { - "name": "Process payment", + "key": { + "service.name": "opbeans-node", + "transaction.name": "Process payment" + }, + "averageResponseTime": 1745009, + "transactionsPerMinute": 0.25, + "impact": 100, "sample": { "@timestamp": "2020-06-29T06:48:29.892Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:39.379730Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:39.379730Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "observer": { "ephemeral_id": "99908b73-9813-4a73-baa6-993db405523a", @@ -34,59 +49,97 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "timestamp": { "us": 1593413309892019 }, - "trace": { "id": "bc393b659bef63291b6fa08e6f1d3f14" }, + "timestamp": { + "us": 1593413309892019 + }, + "trace": { + "id": "bc393b659bef63291b6fa08e6f1d3f14" + }, "transaction": { - "duration": { "us": 1745009 }, + "duration": { + "us": 1745009 + }, "id": "a58333df6d851cf1", "name": "Process payment", "result": "success", "sampled": true, - "span_count": { "started": 2 }, + "span_count": { + "started": 2 + }, "type": "Worker" } - }, - "p95": 1744896, - "averageResponseTime": 1745009, - "transactionsPerMinute": 0.25, - "impact": 100 + } }, { - "name": "GET /api", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /api" + }, + "averageResponseTime": 49816.15625, + "transactionsPerMinute": 8, + "impact": 91.32732325394932, "sample": { - "@timestamp": "2020-06-29T06:48:41.454Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "@timestamp": "2020-06-29T06:48:06.969Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.992834Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:08.306961Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -96,11 +149,18 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Type": ["application/json;charset=UTF-8"], - "Date": ["Mon, 29 Jun 2020 06:48:41 GMT"], - "Transfer-Encoding": ["chunked"], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "0" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:06 GMT" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -130,61 +190,103 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413321454009 }, - "trace": { "id": "0507830eeff93f7bf1a354e4031097b3" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413286969018 + }, + "trace": { + "id": "87a828bcedd44d9e872d8f552fb04aa6" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 8334 }, - "id": "878250a8b937445d", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 25229 + }, + "id": "b1843afd04271423", "name": "GET /api", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "request" }, "url": { "domain": "opbeans-node", - "full": "http://opbeans-node:3000/api/products/6", - "original": "/api/products/6", - "path": "/api/products/6", + "full": "http://opbeans-node:3000/api/orders/474", + "original": "/api/orders/474", + "path": "/api/orders/474", "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 81888, - "averageResponseTime": 49816.15625, - "transactionsPerMinute": 8, - "impact": 91.32732325394932 + } }, { - "name": "/dashboard", + "key": { + "service.name": "client", + "transaction.name": "/dashboard" + }, + "averageResponseTime": 208000, + "transactionsPerMinute": 0.75, + "impact": 35.56882613781033, "sample": { - "@timestamp": "2020-06-29T06:48:21.621Z", - "agent": { "name": "rum-js", "version": "5.2.0" }, - "client": { "ip": "172.18.0.8" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:22.625275Z" }, + "@timestamp": "2020-06-29T06:48:07.275Z", + "agent": { + "name": "rum-js", + "version": "5.2.0" + }, + "client": { + "ip": "172.18.0.8" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:08.291261Z" + }, "http": { - "request": { "referrer": "" }, + "request": { + "referrer": "" + }, "response": { "decoded_body_size": 813, "encoded_body_size": 813, @@ -199,52 +301,73 @@ "version": "8.0.0", "version_major": 8 }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { - "language": { "name": "javascript" }, + "language": { + "name": "javascript" + }, "name": "client", "version": "1.0.0" }, - "source": { "ip": "172.18.0.8" }, - "timestamp": { "us": 1593413301621808 }, - "trace": { "id": "ee0ce8b38b8d5945829fc1c9432538bf" }, + "source": { + "ip": "172.18.0.8" + }, + "timestamp": { + "us": 1593413287275113 + }, + "trace": { + "id": "ca86ffcac7753ec8733933bd8fd45d11" + }, "transaction": { "custom": { "userConfig": { - "featureFlags": ["double-trouble", "4423-hotfix"], + "featureFlags": [ + "double-trouble", + "4423-hotfix" + ], "showDashboard": true } }, - "duration": { "us": 109000 }, - "id": "c546a6716b681bf2", + "duration": { + "us": 342000 + }, + "id": "c40f735132c8e864", "marks": { "agent": { - "domComplete": 98, - "domInteractive": 87, - "timeToFirstByte": 3 + "domComplete": 335, + "domInteractive": 327, + "timeToFirstByte": 16 }, "navigationTiming": { - "connectEnd": 0, - "connectStart": 0, - "domComplete": 98, - "domContentLoadedEventEnd": 87, - "domContentLoadedEventStart": 87, - "domInteractive": 87, - "domLoading": 8, - "domainLookupEnd": 0, - "domainLookupStart": 0, + "connectEnd": 12, + "connectStart": 12, + "domComplete": 335, + "domContentLoadedEventEnd": 327, + "domContentLoadedEventStart": 327, + "domInteractive": 327, + "domLoading": 21, + "domainLookupEnd": 12, + "domainLookupStart": 10, "fetchStart": 0, - "loadEventEnd": 98, - "loadEventStart": 98, - "requestStart": 1, - "responseEnd": 8, - "responseStart": 3 + "loadEventEnd": 335, + "loadEventStart": 335, + "requestStart": 12, + "responseEnd": 17, + "responseStart": 16 } }, "name": "/dashboard", - "page": { "referer": "", "url": "http://opbeans-node:3000/dashboard" }, + "page": { + "referer": "", + "url": "http://opbeans-node:3000/dashboard" + }, "sampled": true, - "span_count": { "started": 8 }, + "span_count": { + "started": 9 + }, "type": "page-load" }, "url": { @@ -261,50 +384,75 @@ "name": "arthurdent" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "HeadlessChrome", "original": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36", - "os": { "name": "Linux" }, + "os": { + "name": "Linux" + }, "version": "79.0.3945" } - }, - "p95": 341504, - "averageResponseTime": 208000, - "transactionsPerMinute": 0.75, - "impact": 35.56882613781033 + } }, { - "name": "DispatcherServlet#doGet", + "key": { + "service.name": "opbeans-java", + "transaction.name": "DispatcherServlet#doGet" + }, + "averageResponseTime": 36010.53846153846, + "transactionsPerMinute": 3.25, + "impact": 26.61043592713186, "sample": { - "@timestamp": "2020-06-29T06:48:40.104Z", + "@timestamp": "2020-06-29T06:48:10.529Z", "agent": { "ephemeral_id": "222af346-6dd9-45ef-ac85-d86b67edd2de", "name": "java", "version": "1.17.1-SNAPSHOT" }, - "client": { "ip": "172.18.0.9" }, + "client": { + "ip": "172.18.0.9" + }, "container": { "id": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:46.706956Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:15.757591Z" + }, "host": { "architecture": "amd64", "hostname": "918ebbd99b4f", "ip": "172.18.0.6", "name": "918ebbd99b4f", - "os": { "platform": "Linux" } + "os": { + "platform": "Linux" + } }, "http": { "request": { "headers": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate"], - "Host": ["172.18.0.6:3000"], - "User-Agent": ["Python/3.7 aiohttp/3.3.2"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Host": [ + "172.18.0.6:3000" + ], + "User-Agent": [ + "Python/3.7 aiohttp/3.3.2" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "172.18.0.9" } + "socket": { + "encrypted": false, + "remote_address": "172.18.0.9" + } }, "response": { "finished": true, @@ -321,77 +469,132 @@ "version": "8.0.0", "version_major": 8 }, - "process": { "pid": 6, "ppid": 1, "title": "/opt/java/openjdk/bin/java" }, - "processor": { "event": "transaction", "name": "transaction" }, + "process": { + "pid": 6, + "ppid": 1, + "title": "/opt/java/openjdk/bin/java" + }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "Servlet API" }, - "language": { "name": "Java", "version": "11.0.7" }, + "framework": { + "name": "Servlet API" + }, + "language": { + "name": "Java", + "version": "11.0.7" + }, "name": "opbeans-java", "node": { "name": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "runtime": { "name": "Java", "version": "11.0.7" }, + "runtime": { + "name": "Java", + "version": "11.0.7" + }, "version": "None" }, - "source": { "ip": "172.18.0.9" }, - "timestamp": { "us": 1593413320104008 }, - "trace": { "id": "90bd7780b32cc51a7f4c200b1e0c170f" }, + "source": { + "ip": "172.18.0.9" + }, + "timestamp": { + "us": 1593413290529006 + }, + "trace": { + "id": "66e3db4cf016b138a43d319d15174891" + }, "transaction": { - "duration": { "us": 8896 }, - "id": "40b22b21e92bbb20", + "duration": { + "us": 34366 + }, + "id": "7ea720a0175e7ffa", "name": "DispatcherServlet#doGet", "result": "HTTP 2xx", "sampled": true, - "span_count": { "dropped": 0, "started": 1 }, + "span_count": { + "dropped": 0, + "started": 1 + }, "type": "request" }, "url": { "domain": "172.18.0.6", - "full": "http://172.18.0.6:3000/api/orders", - "path": "/api/orders", + "full": "http://172.18.0.6:3000/api/products", + "path": "/api/products", "port": 3000, "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "Python/3.7 aiohttp/3.3.2" } - }, - "p95": 34528, - "averageResponseTime": 36010.53846153846, - "transactionsPerMinute": 3.25, - "impact": 26.61043592713186 + } }, { - "name": "POST /api/orders", + "key": { + "service.name": "opbeans-node", + "transaction.name": "POST /api/orders" + }, + "averageResponseTime": 270684, + "transactionsPerMinute": 0.25, + "impact": 15.261616628971955, "sample": { "@timestamp": "2020-06-29T06:48:39.953Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.991549Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:43.991549Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { - "body": { "original": "[REDACTED]" }, + "body": { + "original": "[REDACTED]" + }, "headers": { - "Accept": ["application/json"], - "Connection": ["close"], - "Content-Length": ["129"], - "Content-Type": ["application/json"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Accept": [ + "application/json" + ], + "Connection": [ + "close" + ], + "Content-Length": [ + "129" + ], + "Content-Type": [ + "application/json" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "post", "socket": { @@ -401,12 +604,24 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["13"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:40 GMT"], - "Etag": ["W/\"d-eEOWU4Cnr5DZ23ErRUeYu9oOIks\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "13" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:40 GMT" + ], + "Etag": [ + "W/\"d-eEOWU4Cnr5DZ23ErRUeYu9oOIks\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -436,29 +651,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413319953033 }, - "trace": { "id": "52b8fda5f6df745b990740ba18378620" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413319953033 + }, + "trace": { + "id": "52b8fda5f6df745b990740ba18378620" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 270684 }, + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 270684 + }, "id": "a3afc2a112e9c893", "name": "POST /api/orders", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 16 }, + "span_count": { + "started": 16 + }, "type": "request" }, "url": { @@ -469,50 +707,77 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 270336, - "averageResponseTime": 270684, - "transactionsPerMinute": 0.25, - "impact": 15.261616628971955 + } }, { - "name": "ResourceHttpRequestHandler", + "key": { + "service.name": "opbeans-java", + "transaction.name": "ResourceHttpRequestHandler" + }, + "averageResponseTime": 14419.42857142857, + "transactionsPerMinute": 3.5, + "impact": 11.30657439844125, "sample": { - "@timestamp": "2020-06-29T06:48:44.376Z", + "@timestamp": "2020-06-29T06:48:06.640Z", "agent": { "ephemeral_id": "222af346-6dd9-45ef-ac85-d86b67edd2de", "name": "java", "version": "1.17.1-SNAPSHOT" }, - "client": { "ip": "172.18.0.9" }, + "client": { + "ip": "172.18.0.9" + }, "container": { "id": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:46.720380Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:15.517678Z" + }, "host": { "architecture": "amd64", "hostname": "918ebbd99b4f", "ip": "172.18.0.6", "name": "918ebbd99b4f", - "os": { "platform": "Linux" } + "os": { + "platform": "Linux" + } }, "http": { "request": { "headers": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate"], - "Host": ["172.18.0.6:3000"], - "User-Agent": ["Python/3.7 aiohttp/3.3.2"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Host": [ + "172.18.0.6:3000" + ], + "User-Agent": [ + "Python/3.7 aiohttp/3.3.2" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "172.18.0.9" } + "socket": { + "encrypted": false, + "remote_address": "172.18.0.9" + } }, "response": { "finished": true, @@ -529,63 +794,100 @@ "version": "8.0.0", "version_major": 8 }, - "process": { "pid": 6, "ppid": 1, "title": "/opt/java/openjdk/bin/java" }, - "processor": { "event": "transaction", "name": "transaction" }, + "process": { + "pid": 6, + "ppid": 1, + "title": "/opt/java/openjdk/bin/java" + }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "Spring Web MVC", "version": "5.0.6.RELEASE" }, - "language": { "name": "Java", "version": "11.0.7" }, + "framework": { + "name": "Spring Web MVC", + "version": "5.0.6.RELEASE" + }, + "language": { + "name": "Java", + "version": "11.0.7" + }, "name": "opbeans-java", "node": { "name": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "runtime": { "name": "Java", "version": "11.0.7" }, + "runtime": { + "name": "Java", + "version": "11.0.7" + }, "version": "None" }, - "source": { "ip": "172.18.0.9" }, - "timestamp": { "us": 1593413324376010 }, - "trace": { "id": "7e70dc471913473e7d3bffda9b27d720" }, + "source": { + "ip": "172.18.0.9" + }, + "timestamp": { + "us": 1593413286640008 + }, + "trace": { + "id": "81d8ffb0a39e755eed400f6486e15672" + }, "transaction": { - "duration": { "us": 1420 }, - "id": "5c4e9f4b0846c2f8", + "duration": { + "us": 2953 + }, + "id": "353d42a2f9046e99", "name": "ResourceHttpRequestHandler", "result": "HTTP 4xx", "sampled": true, - "span_count": { "dropped": 0, "started": 0 }, + "span_count": { + "dropped": 0, + "started": 0 + }, "type": "request" }, "url": { "domain": "172.18.0.6", - "full": "http://172.18.0.6:3000/api/types", - "path": "/api/types", + "full": "http://172.18.0.6:3000/api/types/3", + "path": "/api/types/3", "port": 3000, "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "Python/3.7 aiohttp/3.3.2" } - }, - "p95": 4120, - "averageResponseTime": 14419.42857142857, - "transactionsPerMinute": 3.5, - "impact": 11.30657439844125 + } }, { - "name": "/orders", + "key": { + "service.name": "client", + "transaction.name": "/orders" + }, + "averageResponseTime": 81500, + "transactionsPerMinute": 0.5, + "impact": 9.072365225837785, "sample": { - "@timestamp": "2020-06-29T06:48:38.358Z", - "agent": { "name": "rum-js", "version": "5.2.0" }, - "client": { "ip": "172.18.0.8" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:39.365914Z" }, + "@timestamp": "2020-06-29T06:48:29.296Z", + "agent": { + "name": "rum-js", + "version": "5.2.0" + }, + "client": { + "ip": "172.18.0.8" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:29.986555Z" + }, "http": { - "request": { "referrer": "" }, - "response": { - "decoded_body_size": 813, - "encoded_body_size": 813, - "transfer_size": 962 + "request": { + "referrer": "" } }, "observer": { @@ -596,53 +898,50 @@ "version": "8.0.0", "version_major": 8 }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { - "language": { "name": "javascript" }, + "language": { + "name": "javascript" + }, "name": "client", "version": "1.0.0" }, - "source": { "ip": "172.18.0.8" }, - "timestamp": { "us": 1593413318358392 }, - "trace": { "id": "c1dea08a4128e776fd9965ccf8c8da99" }, + "source": { + "ip": "172.18.0.8" + }, + "timestamp": { + "us": 1593413309296660 + }, + "trace": { + "id": "978b56807e0b7a27cbc41a0dfb665f47" + }, "transaction": { "custom": { "userConfig": { - "featureFlags": ["double-trouble", "4423-hotfix"], + "featureFlags": [ + "double-trouble", + "4423-hotfix" + ], "showDashboard": true } }, - "duration": { "us": 140000 }, - "id": "4f2ea2796645d6e5", - "marks": { - "agent": { - "domComplete": 126, - "domInteractive": 116, - "timeToFirstByte": 3 - }, - "navigationTiming": { - "connectEnd": 0, - "connectStart": 0, - "domComplete": 126, - "domContentLoadedEventEnd": 116, - "domContentLoadedEventStart": 116, - "domInteractive": 116, - "domLoading": 20, - "domainLookupEnd": 0, - "domainLookupStart": 0, - "fetchStart": 0, - "loadEventEnd": 126, - "loadEventStart": 126, - "requestStart": 1, - "responseEnd": 3, - "responseStart": 3 - } + "duration": { + "us": 23000 }, + "id": "c3801eadbdef5c7c", "name": "/orders", - "page": { "referer": "", "url": "http://opbeans-node:3000/orders" }, + "page": { + "referer": "", + "url": "http://opbeans-node:3000/orders" + }, "sampled": true, - "span_count": { "started": 7 }, - "type": "page-load" + "span_count": { + "started": 1 + }, + "type": "route-change" }, "url": { "domain": "opbeans-node", @@ -652,59 +951,94 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "adastra@example.com", "id": "3", "name": "trillian" }, + "user": { + "email": "arthur.dent@example.com", + "id": "1", + "name": "arthurdent" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "HeadlessChrome", "original": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36", - "os": { "name": "Linux" }, + "os": { + "name": "Linux" + }, "version": "79.0.3945" } - }, - "p95": 140160, - "averageResponseTime": 81500, - "transactionsPerMinute": 0.5, - "impact": 9.072365225837785 + } }, { - "name": "APIRestController#customer", + "key": { + "service.name": "opbeans-java", + "transaction.name": "APIRestController#customer" + }, + "averageResponseTime": 19370.6, + "transactionsPerMinute": 1.25, + "impact": 5.270496679320978, "sample": { - "@timestamp": "2020-06-29T06:48:38.893Z", + "@timestamp": "2020-06-29T06:48:08.631Z", "agent": { "ephemeral_id": "222af346-6dd9-45ef-ac85-d86b67edd2de", "name": "java", "version": "1.17.1-SNAPSHOT" }, - "client": { "ip": "172.18.0.9" }, + "client": { + "ip": "172.18.0.9" + }, "container": { "id": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:46.680126Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:15.536897Z" + }, "host": { "architecture": "amd64", "hostname": "918ebbd99b4f", "ip": "172.18.0.6", "name": "918ebbd99b4f", - "os": { "platform": "Linux" } + "os": { + "platform": "Linux" + } }, "http": { "request": { "headers": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate"], - "Host": ["172.18.0.6:3000"], - "User-Agent": ["Python/3.7 aiohttp/3.3.2"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Host": [ + "172.18.0.6:3000" + ], + "User-Agent": [ + "Python/3.7 aiohttp/3.3.2" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "172.18.0.9" } + "socket": { + "encrypted": false, + "remote_address": "172.18.0.9" + } }, "response": { "finished": true, "headers": { - "Content-Type": ["application/json;charset=UTF-8"], - "Date": ["Mon, 29 Jun 2020 06:48:38 GMT"], - "Transfer-Encoding": ["chunked"] + "Content-Type": [ + "application/json;charset=UTF-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:08 GMT" + ], + "Transfer-Encoding": [ + "chunked" + ] }, "headers_sent": true, "status_code": 200 @@ -719,59 +1053,101 @@ "version": "8.0.0", "version_major": 8 }, - "process": { "pid": 6, "ppid": 1, "title": "/opt/java/openjdk/bin/java" }, - "processor": { "event": "transaction", "name": "transaction" }, + "process": { + "pid": 6, + "ppid": 1, + "title": "/opt/java/openjdk/bin/java" + }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "Spring Web MVC", "version": "5.0.6.RELEASE" }, - "language": { "name": "Java", "version": "11.0.7" }, + "framework": { + "name": "Spring Web MVC", + "version": "5.0.6.RELEASE" + }, + "language": { + "name": "Java", + "version": "11.0.7" + }, "name": "opbeans-java", "node": { "name": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "runtime": { "name": "Java", "version": "11.0.7" }, + "runtime": { + "name": "Java", + "version": "11.0.7" + }, "version": "None" }, - "source": { "ip": "172.18.0.9" }, - "timestamp": { "us": 1593413318893006 }, - "trace": { "id": "efcf3446b51d080dbde1339969cf79a0" }, + "source": { + "ip": "172.18.0.9" + }, + "timestamp": { + "us": 1593413288631008 + }, + "trace": { + "id": "c00da24c5c793cd679ce3df47cee8f37" + }, "transaction": { - "duration": { "us": 4594 }, - "id": "31ef64d71933e846", + "duration": { + "us": 76826 + }, + "id": "3c8403055ff75866", "name": "APIRestController#customer", "result": "HTTP 2xx", "sampled": true, - "span_count": { "dropped": 0, "started": 2 }, + "span_count": { + "dropped": 0, + "started": 2 + }, "type": "request" }, "url": { "domain": "172.18.0.6", - "full": "http://172.18.0.6:3000/api/customers/235", - "path": "/api/customers/235", + "full": "http://172.18.0.6:3000/api/customers/56", + "path": "/api/customers/56", "port": 3000, "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "Python/3.7 aiohttp/3.3.2" } - }, - "p95": 77280, - "averageResponseTime": 19370.6, - "transactionsPerMinute": 1.25, - "impact": 5.270496679320978 + } }, { - "name": "/products", + "key": { + "service.name": "client", + "transaction.name": "/products" + }, + "averageResponseTime": 77000, + "transactionsPerMinute": 0.25, + "impact": 4.129424578484989, "sample": { "@timestamp": "2020-06-29T06:48:48.824Z", - "agent": { "name": "rum-js", "version": "5.2.0" }, - "client": { "ip": "172.18.0.8" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:49.293664Z" }, + "agent": { + "name": "rum-js", + "version": "5.2.0" + }, + "client": { + "ip": "172.18.0.8" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:49.293664Z" + }, "http": { - "request": { "referrer": "" }, + "request": { + "referrer": "" + }, "response": { "decoded_body_size": 813, "encoded_body_size": 813, @@ -786,23 +1162,39 @@ "version": "8.0.0", "version_major": 8 }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { - "language": { "name": "javascript" }, + "language": { + "name": "javascript" + }, "name": "client", "version": "1.0.0" }, - "source": { "ip": "172.18.0.8" }, - "timestamp": { "us": 1593413328824656 }, - "trace": { "id": "f6c4a9197bbd080bd45072970f251525" }, + "source": { + "ip": "172.18.0.8" + }, + "timestamp": { + "us": 1593413328824656 + }, + "trace": { + "id": "f6c4a9197bbd080bd45072970f251525" + }, "transaction": { "custom": { "userConfig": { - "featureFlags": ["double-trouble", "4423-hotfix"], + "featureFlags": [ + "double-trouble", + "4423-hotfix" + ], "showDashboard": true } }, - "duration": { "us": 77000 }, + "duration": { + "us": 77000 + }, "id": "a11ede1968973bc5", "marks": { "agent": { @@ -829,9 +1221,14 @@ } }, "name": "/products", - "page": { "referer": "", "url": "http://opbeans-node:3000/products" }, + "page": { + "referer": "", + "url": "http://opbeans-node:3000/products" + }, "sampled": true, - "span_count": { "started": 5 }, + "span_count": { + "started": 5 + }, "type": "page-load" }, "url": { @@ -842,29 +1239,52 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "z@example.com", "id": "4", "name": "zaphod" }, + "user": { + "email": "z@example.com", + "id": "4", + "name": "zaphod" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "HeadlessChrome", "original": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36", - "os": { "name": "Linux" }, + "os": { + "name": "Linux" + }, "version": "79.0.3945" } - }, - "p95": 76800, - "averageResponseTime": 77000, - "transactionsPerMinute": 0.25, - "impact": 4.129424578484989 + } }, { - "name": "/customers", + "key": { + "service.name": "client", + "transaction.name": "/customers" + }, + "averageResponseTime": 33500, + "transactionsPerMinute": 0.5, + "impact": 3.5546640380951287, "sample": { - "@timestamp": "2020-06-29T06:48:48.287Z", - "agent": { "name": "rum-js", "version": "5.2.0" }, - "client": { "ip": "172.18.0.8" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:49.292535Z" }, - "http": { "request": { "referrer": "" } }, + "@timestamp": "2020-06-29T06:48:35.071Z", + "agent": { + "name": "rum-js", + "version": "5.2.0" + }, + "client": { + "ip": "172.18.0.8" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:36.077184Z" + }, + "http": { + "request": { + "referrer": "" + } + }, "observer": { "ephemeral_id": "99908b73-9813-4a73-baa6-993db405523a", "hostname": "aa0bd613aa4c", @@ -873,28 +1293,49 @@ "version": "8.0.0", "version_major": 8 }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { - "language": { "name": "javascript" }, + "language": { + "name": "javascript" + }, "name": "client", "version": "1.0.0" }, - "source": { "ip": "172.18.0.8" }, - "timestamp": { "us": 1593413328287946 }, - "trace": { "id": "48d130530a1fc0b2b99d138d3461bad4" }, + "source": { + "ip": "172.18.0.8" + }, + "timestamp": { + "us": 1593413315071116 + }, + "trace": { + "id": "547a92e82a25387321d1b967f2dd0f48" + }, "transaction": { "custom": { "userConfig": { - "featureFlags": ["double-trouble", "4423-hotfix"], + "featureFlags": [ + "double-trouble", + "4423-hotfix" + ], "showDashboard": true } }, - "duration": { "us": 39000 }, - "id": "2f3a2b0fd3016d3e", + "duration": { + "us": 28000 + }, + "id": "d24f9b9dacb83450", "name": "/customers", - "page": { "referer": "", "url": "http://opbeans-node:3000/customers" }, + "page": { + "referer": "", + "url": "http://opbeans-node:3000/customers" + }, "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "route-change" }, "url": { @@ -905,59 +1346,94 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "adastra@example.com", "id": "3", "name": "trillian" }, + "user": { + "email": "arthur.dent@example.com", + "id": "1", + "name": "arthurdent" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "HeadlessChrome", "original": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36", - "os": { "name": "Linux" }, + "os": { + "name": "Linux" + }, "version": "79.0.3945" } - }, - "p95": 39040, - "averageResponseTime": 33500, - "transactionsPerMinute": 0.5, - "impact": 3.5546640380951287 + } }, { - "name": "APIRestController#customers", + "key": { + "service.name": "opbeans-java", + "transaction.name": "APIRestController#customers" + }, + "averageResponseTime": 16690.75, + "transactionsPerMinute": 1, + "impact": 3.541042213287889, "sample": { - "@timestamp": "2020-06-29T06:48:43.765Z", + "@timestamp": "2020-06-29T06:48:22.372Z", "agent": { "ephemeral_id": "222af346-6dd9-45ef-ac85-d86b67edd2de", "name": "java", "version": "1.17.1-SNAPSHOT" }, - "client": { "ip": "172.18.0.9" }, + "client": { + "ip": "172.18.0.9" + }, "container": { "id": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:46.716850Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:25.888154Z" + }, "host": { "architecture": "amd64", "hostname": "918ebbd99b4f", "ip": "172.18.0.6", "name": "918ebbd99b4f", - "os": { "platform": "Linux" } + "os": { + "platform": "Linux" + } }, "http": { "request": { "headers": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate"], - "Host": ["172.18.0.6:3000"], - "User-Agent": ["Python/3.7 aiohttp/3.3.2"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Host": [ + "172.18.0.6:3000" + ], + "User-Agent": [ + "Python/3.7 aiohttp/3.3.2" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "172.18.0.9" } + "socket": { + "encrypted": false, + "remote_address": "172.18.0.9" + } }, "response": { "finished": true, "headers": { - "Content-Type": ["application/json;charset=UTF-8"], - "Date": ["Mon, 29 Jun 2020 06:48:43 GMT"], - "Transfer-Encoding": ["chunked"] + "Content-Type": [ + "application/json;charset=UTF-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:21 GMT" + ], + "Transfer-Encoding": [ + "chunked" + ] }, "headers_sent": true, "status_code": 500 @@ -972,29 +1448,56 @@ "version": "8.0.0", "version_major": 8 }, - "process": { "pid": 6, "ppid": 1, "title": "/opt/java/openjdk/bin/java" }, - "processor": { "event": "transaction", "name": "transaction" }, + "process": { + "pid": 6, + "ppid": 1, + "title": "/opt/java/openjdk/bin/java" + }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "Spring Web MVC", "version": "5.0.6.RELEASE" }, - "language": { "name": "Java", "version": "11.0.7" }, + "framework": { + "name": "Spring Web MVC", + "version": "5.0.6.RELEASE" + }, + "language": { + "name": "Java", + "version": "11.0.7" + }, "name": "opbeans-java", "node": { "name": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "runtime": { "name": "Java", "version": "11.0.7" }, + "runtime": { + "name": "Java", + "version": "11.0.7" + }, "version": "None" }, - "source": { "ip": "172.18.0.9" }, - "timestamp": { "us": 1593413323765008 }, - "trace": { "id": "affce4cea9b60bd5b635dc1bd2e4ce79" }, + "source": { + "ip": "172.18.0.9" + }, + "timestamp": { + "us": 1593413302372009 + }, + "trace": { + "id": "21dd795dc3a260b1bf7ebbbac1e86fb8" + }, "transaction": { - "duration": { "us": 10880 }, - "id": "cfe0a84b49b4a340", + "duration": { + "us": 14795 + }, + "id": "0157fc513282138f", "name": "APIRestController#customers", "result": "HTTP 5xx", "sampled": true, - "span_count": { "dropped": 0, "started": 2 }, + "span_count": { + "dropped": 0, + "started": 2 + }, "type": "request" }, "url": { @@ -1005,40 +1508,61 @@ "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "Python/3.7 aiohttp/3.3.2" } - }, - "p95": 26432, - "averageResponseTime": 16690.75, - "transactionsPerMinute": 1, - "impact": 3.541042213287889 + } }, { - "name": "GET /log-message", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /log-message" + }, + "averageResponseTime": 32667.5, + "transactionsPerMinute": 0.5, + "impact": 3.458966408120217, "sample": { - "@timestamp": "2020-06-29T06:48:28.944Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "@timestamp": "2020-06-29T06:48:25.944Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:39.370695Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:29.976822Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -1048,12 +1572,24 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["24"], - "Content-Type": ["text/html; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:28 GMT"], - "Etag": ["W/\"18-MS3VbhH7auHMzO0fUuNF6v14N/M\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "24" + ], + "Content-Type": [ + "text/html; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:25 GMT" + ], + "Etag": [ + "W/\"18-MS3VbhH7auHMzO0fUuNF6v14N/M\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 500 }, @@ -1083,29 +1619,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413308944016 }, - "trace": { "id": "afabe4cb397616f5ec35a2f3da49ba62" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413305944023 + }, + "trace": { + "id": "cd2ad726ad164d701c5d3103cbab0c81" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 26788 }, - "id": "cc8c4261387507cf", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 38547 + }, + "id": "9e41667eb64dea55", "name": "GET /log-message", "result": "HTTP 5xx", "sampled": true, - "span_count": { "started": 0 }, + "span_count": { + "started": 0 + }, "type": "request" }, "url": { @@ -1116,60 +1675,82 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 38528, - "averageResponseTime": 32667.5, - "transactionsPerMinute": 0.5, - "impact": 3.458966408120217 + } }, { - "name": "APIRestController#stats", + "key": { + "service.name": "opbeans-java", + "transaction.name": "APIRestController#stats" + }, + "averageResponseTime": 15535, + "transactionsPerMinute": 1, + "impact": 3.275330415465657, "sample": { - "@timestamp": "2020-06-29T06:48:42.549Z", + "@timestamp": "2020-06-29T06:48:09.912Z", "agent": { "ephemeral_id": "222af346-6dd9-45ef-ac85-d86b67edd2de", "name": "java", "version": "1.17.1-SNAPSHOT" }, - "client": { "ip": "172.18.0.9" }, + "client": { + "ip": "172.18.0.9" + }, "container": { "id": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:46.715898Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:15.543824Z" + }, "host": { "architecture": "amd64", "hostname": "918ebbd99b4f", "ip": "172.18.0.6", "name": "918ebbd99b4f", - "os": { "platform": "Linux" } + "os": { + "platform": "Linux" + } }, "http": { "request": { "headers": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate"], - "Host": ["172.18.0.6:3000"], - "User-Agent": ["Python/3.7 aiohttp/3.3.2"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Host": [ + "172.18.0.6:3000" + ], + "User-Agent": [ + "Python/3.7 aiohttp/3.3.2" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "172.18.0.9" } + "socket": { + "encrypted": false, + "remote_address": "172.18.0.9" + } }, "response": { "finished": true, - "headers": { - "Content-Type": ["application/json;charset=UTF-8"], - "Date": ["Mon, 29 Jun 2020 06:48:42 GMT"], - "Transfer-Encoding": ["chunked"] - }, "headers_sent": true, - "status_code": 200 + "status_code": 500 }, "version": "1.1" }, @@ -1181,29 +1762,56 @@ "version": "8.0.0", "version_major": 8 }, - "process": { "pid": 6, "ppid": 1, "title": "/opt/java/openjdk/bin/java" }, - "processor": { "event": "transaction", "name": "transaction" }, + "process": { + "pid": 6, + "ppid": 1, + "title": "/opt/java/openjdk/bin/java" + }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "Spring Web MVC", "version": "5.0.6.RELEASE" }, - "language": { "name": "Java", "version": "11.0.7" }, + "framework": { + "name": "Spring Web MVC", + "version": "5.0.6.RELEASE" + }, + "language": { + "name": "Java", + "version": "11.0.7" + }, "name": "opbeans-java", "node": { "name": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "runtime": { "name": "Java", "version": "11.0.7" }, + "runtime": { + "name": "Java", + "version": "11.0.7" + }, "version": "None" }, - "source": { "ip": "172.18.0.9" }, - "timestamp": { "us": 1593413322549008 }, - "trace": { "id": "c3556e143784f94d4b4220dd40687fae" }, + "source": { + "ip": "172.18.0.9" + }, + "timestamp": { + "us": 1593413289912007 + }, + "trace": { + "id": "a17ceae4e18d50430ca15ecca5a3e69f" + }, "transaction": { - "duration": { "us": 9166 }, - "id": "ac40e567f63c3eef", + "duration": { + "us": 10930 + }, + "id": "9fb330060bb73271", "name": "APIRestController#stats", - "result": "HTTP 2xx", + "result": "HTTP 5xx", "sampled": true, - "span_count": { "dropped": 0, "started": 5 }, + "span_count": { + "dropped": 0, + "started": 5 + }, "type": "request" }, "url": { @@ -1214,40 +1822,61 @@ "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "Python/3.7 aiohttp/3.3.2" } - }, - "p95": 32064, - "averageResponseTime": 15535, - "transactionsPerMinute": 1, - "impact": 3.275330415465657 + } }, { - "name": "GET /api/customers", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /api/customers" + }, + "averageResponseTime": 20092, + "transactionsPerMinute": 0.75, + "impact": 3.168195050736987, "sample": { - "@timestamp": "2020-06-29T06:48:37.952Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "@timestamp": "2020-06-29T06:48:28.444Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:39.492402Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:29.982737Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -1257,12 +1886,24 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["186769"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:37 GMT"], - "Etag": ["W/\"2d991-yG3J8W/roH7fSxXTudZrO27Ax9s\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "186769" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:28 GMT" + ], + "Etag": [ + "W/\"2d991-yG3J8W/roH7fSxXTudZrO27Ax9s\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -1292,29 +1933,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413317952016 }, - "trace": { "id": "5d99327edae38ed735e8d7a6028cf719" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413308444015 + }, + "trace": { + "id": "792fb0b00256164e88b277ec40b65e14" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 16824 }, - "id": "071808429ec9d00b", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 26471 + }, + "id": "6c1f848752563d2b", "name": "GET /api/customers", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 2 }, + "span_count": { + "started": 2 + }, "type": "request" }, "url": { @@ -1325,42 +1989,67 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 26368, - "averageResponseTime": 20092, - "transactionsPerMinute": 0.75, - "impact": 3.168195050736987 + } }, { - "name": "GET /api/products/:id", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /api/products/:id" + }, + "averageResponseTime": 13516.5, + "transactionsPerMinute": 1, + "impact": 2.8112687551548836, "sample": { - "@timestamp": "2020-06-29T06:48:24.977Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "@timestamp": "2020-06-29T06:47:57.555Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:27.004717Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:47:59.085077Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -1370,12 +2059,24 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["231"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:24 GMT"], - "Etag": ["W/\"e7-kkuzj37GZDzXDh0CWqh5Gan0VO4\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "231" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:47:57 GMT" + ], + "Etag": [ + "W/\"e7-6JlJegaJ+ir0C8I8EmmOjms1dnc\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -1401,79 +2102,127 @@ "/usr/local/lib/node_modules/pm2/lib/ProcessContainer.js", "ecosystem-workload.config.js" ], - "pid": 137, + "pid": 87, "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413304977014 }, - "trace": { "id": "b9b290bca14c99962fa9a1c509401630" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413277555176 + }, + "trace": { + "id": "8365e1763f19e4067b88521d4d9247a0" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 4482 }, - "id": "b8d8284ff1fc25d6", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 37709 + }, + "id": "be2722a418272f10", "name": "GET /api/products/:id", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "request" }, "url": { "domain": "opbeans-node", - "full": "http://opbeans-node:3000/api/products/3", - "original": "/api/products/3", - "path": "/api/products/3", + "full": "http://opbeans-node:3000/api/products/1", + "original": "/api/products/1", + "path": "/api/products/1", "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 37856, - "averageResponseTime": 13516.5, - "transactionsPerMinute": 1, - "impact": 2.8112687551548836 + } }, { - "name": "GET /api/types", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /api/types" + }, + "averageResponseTime": 26992.5, + "transactionsPerMinute": 0.5, + "impact": 2.8066131947777255, "sample": { - "@timestamp": "2020-06-29T06:48:26.443Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "@timestamp": "2020-06-29T06:47:52.935Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:29.977518Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:47:55.471071Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -1483,12 +2232,24 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["112"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:26 GMT"], - "Etag": ["W/\"70-1z6hT7P1WHgBgS/BeUEVeHhOCQU\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "112" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:47:52 GMT" + ], + "Etag": [ + "W/\"70-1z6hT7P1WHgBgS/BeUEVeHhOCQU\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -1514,33 +2275,56 @@ "/usr/local/lib/node_modules/pm2/lib/ProcessContainer.js", "ecosystem-workload.config.js" ], - "pid": 137, + "pid": 63, "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413306443014 }, - "trace": { "id": "be3f4eb50d253afc032c90eacaa85072" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413272935117 + }, + "trace": { + "id": "2946c536a33d163d0c984d00d1f3839a" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 8892 }, - "id": "ccce129bb8c6b125", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 45093 + }, + "id": "103482fda88b9400", "name": "GET /api/types", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 2 }, + "span_count": { + "started": 2 + }, "type": "request" }, "url": { @@ -1551,42 +2335,67 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 45248, - "averageResponseTime": 26992.5, - "transactionsPerMinute": 0.5, - "impact": 2.8066131947777255 + } }, { - "name": "GET static file", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET static file" + }, + "averageResponseTime": 3492.9285714285716, + "transactionsPerMinute": 3.5, + "impact": 2.5144049360435208, "sample": { - "@timestamp": "2020-06-29T06:48:40.953Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "@timestamp": "2020-06-29T06:47:53.427Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.992454Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:47:55.472070Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -1596,15 +2405,33 @@ }, "response": { "headers": { - "Accept-Ranges": ["bytes"], - "Cache-Control": ["public, max-age=0"], - "Connection": ["close"], - "Content-Length": ["15086"], - "Content-Type": ["image/x-icon"], - "Date": ["Mon, 29 Jun 2020 06:48:40 GMT"], - "Etag": ["W/\"3aee-1725aff14f0\""], - "Last-Modified": ["Thu, 28 May 2020 11:16:06 GMT"], - "X-Powered-By": ["Express"] + "Accept-Ranges": [ + "bytes" + ], + "Cache-Control": [ + "public, max-age=0" + ], + "Connection": [ + "close" + ], + "Content-Length": [ + "15086" + ], + "Content-Type": [ + "image/x-icon" + ], + "Date": [ + "Mon, 29 Jun 2020 06:47:53 GMT" + ], + "Etag": [ + "W/\"3aee-1725aff14f0\"" + ], + "Last-Modified": [ + "Thu, 28 May 2020 11:16:06 GMT" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -1624,32 +2451,53 @@ "/usr/local/lib/node_modules/pm2/lib/ProcessContainer.js", "ecosystem-workload.config.js" ], - "pid": 137, + "pid": 63, "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413320953016 }, - "trace": { "id": "292393440bbe04385f3c2e3715ac35fe" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413273427016 + }, + "trace": { + "id": "ec8a804fedf28fcf81d5682d69a16970" + }, "transaction": { - "duration": { "us": 1671 }, - "id": "d1d964ca1865dce3", + "duration": { + "us": 4934 + }, + "id": "ab90a62901b770e6", "name": "GET static file", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 0 }, + "span_count": { + "started": 0 + }, "type": "request" }, "url": { @@ -1661,55 +2509,84 @@ "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 11900, - "averageResponseTime": 3492.9285714285716, - "transactionsPerMinute": 3.5, - "impact": 2.5144049360435208 + } }, { - "name": "APIRestController#customerWhoBought", + "key": { + "service.name": "opbeans-java", + "transaction.name": "APIRestController#customerWhoBought" + }, + "averageResponseTime": 3742.153846153846, + "transactionsPerMinute": 3.25, + "impact": 2.4998634943716573, "sample": { - "@timestamp": "2020-06-29T06:48:44.982Z", + "@timestamp": "2020-06-29T06:48:11.166Z", "agent": { "ephemeral_id": "222af346-6dd9-45ef-ac85-d86b67edd2de", "name": "java", "version": "1.17.1-SNAPSHOT" }, - "client": { "ip": "172.18.0.9" }, + "client": { + "ip": "172.18.0.9" + }, "container": { "id": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:46.721114Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:15.763228Z" + }, "host": { "architecture": "amd64", "hostname": "918ebbd99b4f", "ip": "172.18.0.6", "name": "918ebbd99b4f", - "os": { "platform": "Linux" } + "os": { + "platform": "Linux" + } }, "http": { "request": { "headers": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate"], - "Host": ["172.18.0.6:3000"], - "User-Agent": ["Python/3.7 aiohttp/3.3.2"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Host": [ + "172.18.0.6:3000" + ], + "User-Agent": [ + "Python/3.7 aiohttp/3.3.2" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "172.18.0.9" } + "socket": { + "encrypted": false, + "remote_address": "172.18.0.9" + } }, "response": { "finished": true, "headers": { - "Content-Type": ["application/json;charset=UTF-8"], - "Date": ["Mon, 29 Jun 2020 06:48:44 GMT"], - "Transfer-Encoding": ["chunked"] + "Content-Type": [ + "application/json;charset=UTF-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:10 GMT" + ], + "Transfer-Encoding": [ + "chunked" + ] }, "headers_sent": true, "status_code": 200 @@ -1724,73 +2601,121 @@ "version": "8.0.0", "version_major": 8 }, - "process": { "pid": 6, "ppid": 1, "title": "/opt/java/openjdk/bin/java" }, - "processor": { "event": "transaction", "name": "transaction" }, + "process": { + "pid": 6, + "ppid": 1, + "title": "/opt/java/openjdk/bin/java" + }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "Spring Web MVC", "version": "5.0.6.RELEASE" }, - "language": { "name": "Java", "version": "11.0.7" }, + "framework": { + "name": "Spring Web MVC", + "version": "5.0.6.RELEASE" + }, + "language": { + "name": "Java", + "version": "11.0.7" + }, "name": "opbeans-java", "node": { "name": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "runtime": { "name": "Java", "version": "11.0.7" }, + "runtime": { + "name": "Java", + "version": "11.0.7" + }, "version": "None" }, - "source": { "ip": "172.18.0.9" }, - "timestamp": { "us": 1593413324982008 }, - "trace": { "id": "e5ce8ba877f69510e7abc3f0d11c1e4f" }, + "source": { + "ip": "172.18.0.9" + }, + "timestamp": { + "us": 1593413291166005 + }, + "trace": { + "id": "fa0d353eb7967b344ed37674f40b2884" + }, "transaction": { - "duration": { "us": 2797 }, - "id": "b8c1bd3b31b197d3", + "duration": { + "us": 4453 + }, + "id": "bce4ce4b09ded6ca", "name": "APIRestController#customerWhoBought", "result": "HTTP 2xx", "sampled": true, - "span_count": { "dropped": 0, "started": 1 }, + "span_count": { + "dropped": 0, + "started": 2 + }, "type": "request" }, "url": { "domain": "172.18.0.6", - "full": "http://172.18.0.6:3000/api/products/5/customers", - "path": "/api/products/5/customers", + "full": "http://172.18.0.6:3000/api/products/3/customers", + "path": "/api/products/3/customers", "port": 3000, "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "Python/3.7 aiohttp/3.3.2" } - }, - "p95": 4464, - "averageResponseTime": 3742.153846153846, - "transactionsPerMinute": 3.25, - "impact": 2.4998634943716573 + } }, { - "name": "GET /log-error", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /log-error" + }, + "averageResponseTime": 35846, + "transactionsPerMinute": 0.25, + "impact": 1.7640550505645587, "sample": { "@timestamp": "2020-06-29T06:48:07.467Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:18.533253Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:18.533253Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -1800,12 +2725,24 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["24"], - "Content-Type": ["text/html; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:07 GMT"], - "Etag": ["W/\"18-MS3VbhH7auHMzO0fUuNF6v14N/M\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "24" + ], + "Content-Type": [ + "text/html; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:07 GMT" + ], + "Etag": [ + "W/\"18-MS3VbhH7auHMzO0fUuNF6v14N/M\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 500 }, @@ -1835,29 +2772,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413287467017 }, - "trace": { "id": "d518b2c4d72cd2aaf1e39bad7ebcbdbb" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413287467017 + }, + "trace": { + "id": "d518b2c4d72cd2aaf1e39bad7ebcbdbb" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 35846 }, + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 35846 + }, "id": "c7a30c1b076907ec", "name": "GET /log-error", "result": "HTTP 5xx", "sampled": true, - "span_count": { "started": 0 }, + "span_count": { + "started": 0 + }, "type": "request" }, "url": { @@ -1868,57 +2828,90 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 35840, - "averageResponseTime": 35846, - "transactionsPerMinute": 0.25, - "impact": 1.7640550505645587 + } }, { - "name": "APIRestController#topProducts", + "key": { + "service.name": "opbeans-java", + "transaction.name": "APIRestController#topProducts" + }, + "averageResponseTime": 4825, + "transactionsPerMinute": 1.75, + "impact": 1.6450221426498186, "sample": { - "@timestamp": "2020-06-29T06:48:45.587Z", + "@timestamp": "2020-06-29T06:48:11.778Z", "agent": { "ephemeral_id": "222af346-6dd9-45ef-ac85-d86b67edd2de", "name": "java", "version": "1.17.1-SNAPSHOT" }, - "client": { "ip": "172.18.0.9" }, + "client": { + "ip": "172.18.0.9" + }, "container": { "id": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:46.770758Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:15.764351Z" + }, "host": { "architecture": "amd64", "hostname": "918ebbd99b4f", "ip": "172.18.0.6", "name": "918ebbd99b4f", - "os": { "platform": "Linux" } + "os": { + "platform": "Linux" + } }, "http": { "request": { "headers": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate"], - "Host": ["172.18.0.6:3000"], - "User-Agent": ["Python/3.7 aiohttp/3.3.2"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Host": [ + "172.18.0.6:3000" + ], + "User-Agent": [ + "Python/3.7 aiohttp/3.3.2" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "172.18.0.9" } + "socket": { + "encrypted": false, + "remote_address": "172.18.0.9" + } }, "response": { "finished": true, "headers": { - "Content-Type": ["application/json;charset=UTF-8"], - "Date": ["Mon, 29 Jun 2020 06:48:44 GMT"], - "Transfer-Encoding": ["chunked"] + "Content-Type": [ + "application/json;charset=UTF-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:11 GMT" + ], + "Transfer-Encoding": [ + "chunked" + ] }, "headers_sent": true, "status_code": 200 @@ -1933,29 +2926,56 @@ "version": "8.0.0", "version_major": 8 }, - "process": { "pid": 6, "ppid": 1, "title": "/opt/java/openjdk/bin/java" }, - "processor": { "event": "transaction", "name": "transaction" }, + "process": { + "pid": 6, + "ppid": 1, + "title": "/opt/java/openjdk/bin/java" + }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "Spring Web MVC", "version": "5.0.6.RELEASE" }, - "language": { "name": "Java", "version": "11.0.7" }, + "framework": { + "name": "Spring Web MVC", + "version": "5.0.6.RELEASE" + }, + "language": { + "name": "Java", + "version": "11.0.7" + }, "name": "opbeans-java", "node": { "name": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "runtime": { "name": "Java", "version": "11.0.7" }, + "runtime": { + "name": "Java", + "version": "11.0.7" + }, "version": "None" }, - "source": { "ip": "172.18.0.9" }, - "timestamp": { "us": 1593413325587007 }, - "trace": { "id": "4470d0cc076e22018e2dd258a25c8812" }, + "source": { + "ip": "172.18.0.9" + }, + "timestamp": { + "us": 1593413291778008 + }, + "trace": { + "id": "d65e9816f1f6db3961867f7b6d1d4e6a" + }, "transaction": { - "duration": { "us": 4070 }, - "id": "cb860b712121d0d8", + "duration": { + "us": 4168 + }, + "id": "a72f4bb8149ecdc5", "name": "APIRestController#topProducts", "result": "HTTP 2xx", "sampled": true, - "span_count": { "dropped": 0, "started": 1 }, + "span_count": { + "dropped": 0, + "started": 2 + }, "type": "request" }, "url": { @@ -1966,40 +2986,61 @@ "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "Python/3.7 aiohttp/3.3.2" } - }, - "p95": 7344, - "averageResponseTime": 4825, - "transactionsPerMinute": 1.75, - "impact": 1.6450221426498186 + } }, { - "name": "GET /api/products/top", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /api/products/top" + }, + "averageResponseTime": 33097, + "transactionsPerMinute": 0.25, + "impact": 1.6060533780113861, "sample": { "@timestamp": "2020-06-29T06:48:01.200Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:02.734903Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:02.734903Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -2009,12 +3050,24 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["2"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:01 GMT"], - "Etag": ["W/\"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "2" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:01 GMT" + ], + "Etag": [ + "W/\"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -2044,29 +3097,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413281200133 }, - "trace": { "id": "195f32efeb6f91e2f71b6bc8bb74ae3a" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413281200133 + }, + "trace": { + "id": "195f32efeb6f91e2f71b6bc8bb74ae3a" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 33097 }, + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 33097 + }, "id": "22e72956dfc8967a", "name": "GET /api/products/top", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "request" }, "url": { @@ -2077,42 +3153,67 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 33024, - "averageResponseTime": 33097, - "transactionsPerMinute": 0.25, - "impact": 1.6060533780113861 + } }, { - "name": "GET /api/products", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /api/products" + }, + "averageResponseTime": 6583, + "transactionsPerMinute": 1, + "impact": 1.2172278724376455, "sample": { - "@timestamp": "2020-06-29T06:48:23.477Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "@timestamp": "2020-06-29T06:48:21.475Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:27.001228Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:26.996210Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -2122,12 +3223,24 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["1023"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:23 GMT"], - "Etag": ["W/\"3ff-VyOxcDApb+a/lnjkm9FeTOGSDrs\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "1023" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:21 GMT" + ], + "Etag": [ + "W/\"3ff-VyOxcDApb+a/lnjkm9FeTOGSDrs\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -2157,29 +3270,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413303477028 }, - "trace": { "id": "9f26158b9a3915577b3cccc17636ea01" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413301475015 + }, + "trace": { + "id": "389b26b16949c7f783223de4f14b788c" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 7150 }, - "id": "27ff4add22ac2e1b", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 6775 + }, + "id": "d2d4088a0b104fb4", "name": "GET /api/products", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 2 }, + "span_count": { + "started": 2 + }, "type": "request" }, "url": { @@ -2190,46 +3326,79 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 8160, - "averageResponseTime": 6583, - "transactionsPerMinute": 1, - "impact": 1.2172278724376455 + } }, { - "name": "POST /api", + "key": { + "service.name": "opbeans-node", + "transaction.name": "POST /api" + }, + "averageResponseTime": 20011, + "transactionsPerMinute": 0.25, + "impact": 0.853921734857215, "sample": { "@timestamp": "2020-06-29T06:48:25.478Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:27.005671Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:27.005671Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { - "body": { "original": "[REDACTED]" }, + "body": { + "original": "[REDACTED]" + }, "headers": { - "Accept": ["application/json"], - "Connection": ["close"], - "Content-Length": ["129"], - "Content-Type": ["application/json"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Accept": [ + "application/json" + ], + "Connection": [ + "close" + ], + "Content-Length": [ + "129" + ], + "Content-Type": [ + "application/json" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "post", "socket": { @@ -2239,12 +3408,24 @@ }, "response": { "headers": { - "Allow": ["GET"], - "Connection": ["close"], - "Content-Type": ["application/json;charset=UTF-8"], - "Date": ["Mon, 29 Jun 2020 06:48:25 GMT"], - "Transfer-Encoding": ["chunked"], - "X-Powered-By": ["Express"] + "Allow": [ + "GET" + ], + "Connection": [ + "close" + ], + "Content-Type": [ + "application/json;charset=UTF-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:25 GMT" + ], + "Transfer-Encoding": [ + "chunked" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 405 }, @@ -2274,29 +3455,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413305478010 }, - "trace": { "id": "4bd9027dd1e355ec742970e2d6333124" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413305478010 + }, + "trace": { + "id": "4bd9027dd1e355ec742970e2d6333124" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 20011 }, + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 20011 + }, "id": "94104435cf151478", "name": "POST /api", "result": "HTTP 4xx", "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "request" }, "url": { @@ -2307,42 +3511,67 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 19968, - "averageResponseTime": 20011, - "transactionsPerMinute": 0.25, - "impact": 0.853921734857215 + } }, { - "name": "GET /api/types/:id", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /api/types/:id" + }, + "averageResponseTime": 8181, + "transactionsPerMinute": 0.5, + "impact": 0.6441916136689552, "sample": { - "@timestamp": "2020-06-29T06:48:12.972Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "@timestamp": "2020-06-29T06:47:53.928Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:18.543436Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:47:55.472718Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -2352,12 +3581,24 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["205"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:12 GMT"], - "Etag": ["W/\"cd-pFMi1QOVY6YqWe+nwcbZVviCths\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "205" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:47:53 GMT" + ], + "Etag": [ + "W/\"cd-pFMi1QOVY6YqWe+nwcbZVviCths\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -2383,33 +3624,56 @@ "/usr/local/lib/node_modules/pm2/lib/ProcessContainer.js", "ecosystem-workload.config.js" ], - "pid": 137, + "pid": 63, "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413292972011 }, - "trace": { "id": "aea65cef5f902dda5d8e38f9fb38864d" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413273928016 + }, + "trace": { + "id": "0becaafb422bfeb69e047bf7153aa469" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 6300 }, - "id": "a5bdbe43ac05fae2", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 10062 + }, + "id": "0cee4574091bda3b", "name": "GET /api/types/:id", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 2 }, + "span_count": { + "started": 2 + }, "type": "request" }, "url": { @@ -2420,42 +3684,67 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 10080, - "averageResponseTime": 8181, - "transactionsPerMinute": 0.5, - "impact": 0.6441916136689552 + } }, { - "name": "GET /api/stats", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /api/stats" + }, + "averageResponseTime": 5098, + "transactionsPerMinute": 0.75, + "impact": 0.582807187955318, "sample": { - "@timestamp": "2020-06-29T06:48:39.451Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "@timestamp": "2020-06-29T06:48:34.949Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.984824Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:39.479316Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -2465,12 +3754,24 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["92"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:39 GMT"], - "Etag": ["W/\"5c-6I+bqIiLxvkWuwBUnTxhBoK4lBk\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "92" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:34 GMT" + ], + "Etag": [ + "W/\"5c-6I+bqIiLxvkWuwBUnTxhBoK4lBk\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -2500,29 +3801,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413319451016 }, - "trace": { "id": "a05787cb03a0af0863fab5e05de942f1" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413314949017 + }, + "trace": { + "id": "616b3b77abd5534c61d6c0438469aee2" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 5050 }, - "id": "a7e004eba8f021ce", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 5459 + }, + "id": "5b4971de59d2099d", "name": "GET /api/stats", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 4 }, + "span_count": { + "started": 4 + }, "type": "request" }, "url": { @@ -2533,42 +3857,67 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 5440, - "averageResponseTime": 5098, - "transactionsPerMinute": 0.75, - "impact": 0.582807187955318 + } }, { - "name": "GET /api/orders", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /api/orders" + }, + "averageResponseTime": 7624.5, + "transactionsPerMinute": 0.5, + "impact": 0.5802207655235637, "sample": { "@timestamp": "2020-06-29T06:48:35.450Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:39.483715Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:39.483715Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -2578,12 +3927,24 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["2"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:35 GMT"], - "Etag": ["W/\"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "2" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:35 GMT" + ], + "Etag": [ + "W/\"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -2613,29 +3974,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413315450014 }, - "trace": { "id": "2da70ccf10599b271f65273d169cde9f" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413315450014 + }, + "trace": { + "id": "2da70ccf10599b271f65273d169cde9f" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 8784 }, + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 8784 + }, "id": "a3f4a4f339758440", "name": "GET /api/orders", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 2 }, + "span_count": { + "started": 2 + }, "type": "request" }, "url": { @@ -2646,42 +4030,67 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 8800, - "averageResponseTime": 7624.5, - "transactionsPerMinute": 0.5, - "impact": 0.5802207655235637 + } }, { - "name": "GET /api/orders/:id", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /api/orders/:id" + }, + "averageResponseTime": 4749.666666666667, + "transactionsPerMinute": 0.75, + "impact": 0.5227447114845778, "sample": { "@timestamp": "2020-06-29T06:48:35.951Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:39.484133Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:39.484133Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -2691,10 +4100,18 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["0"], - "Date": ["Mon, 29 Jun 2020 06:48:35 GMT"], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "0" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:35 GMT" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 404 }, @@ -2724,29 +4141,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413315951017 }, - "trace": { "id": "95979caa80e6622cbbb2d308800c3016" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413315951017 + }, + "trace": { + "id": "95979caa80e6622cbbb2d308800c3016" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 3210 }, + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 3210 + }, "id": "30344988dace0b43", "name": "GET /api/orders/:id", "result": "HTTP 4xx", "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "request" }, "url": { @@ -2757,57 +4197,90 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 7184, - "averageResponseTime": 4749.666666666667, - "transactionsPerMinute": 0.75, - "impact": 0.5227447114845778 + } }, { - "name": "APIRestController#products", + "key": { + "service.name": "opbeans-java", + "transaction.name": "APIRestController#products" + }, + "averageResponseTime": 6787, + "transactionsPerMinute": 0.5, + "impact": 0.4839483750082622, "sample": { - "@timestamp": "2020-06-29T06:48:27.824Z", + "@timestamp": "2020-06-29T06:48:13.595Z", "agent": { "ephemeral_id": "222af346-6dd9-45ef-ac85-d86b67edd2de", "name": "java", "version": "1.17.1-SNAPSHOT" }, - "client": { "ip": "172.18.0.9" }, + "client": { + "ip": "172.18.0.9" + }, "container": { "id": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:36.087688Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:15.755614Z" + }, "host": { "architecture": "amd64", "hostname": "918ebbd99b4f", "ip": "172.18.0.6", "name": "918ebbd99b4f", - "os": { "platform": "Linux" } + "os": { + "platform": "Linux" + } }, "http": { "request": { "headers": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate"], - "Host": ["172.18.0.6:3000"], - "User-Agent": ["Python/3.7 aiohttp/3.3.2"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Host": [ + "172.18.0.6:3000" + ], + "User-Agent": [ + "Python/3.7 aiohttp/3.3.2" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "172.18.0.9" } + "socket": { + "encrypted": false, + "remote_address": "172.18.0.9" + } }, "response": { "finished": true, "headers": { - "Content-Type": ["application/json;charset=UTF-8"], - "Date": ["Mon, 29 Jun 2020 06:48:27 GMT"], - "Transfer-Encoding": ["chunked"] + "Content-Type": [ + "application/json;charset=UTF-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:12 GMT" + ], + "Transfer-Encoding": [ + "chunked" + ] }, "headers_sent": true, "status_code": 200 @@ -2822,29 +4295,56 @@ "version": "8.0.0", "version_major": 8 }, - "process": { "pid": 6, "ppid": 1, "title": "/opt/java/openjdk/bin/java" }, - "processor": { "event": "transaction", "name": "transaction" }, + "process": { + "pid": 6, + "ppid": 1, + "title": "/opt/java/openjdk/bin/java" + }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "Spring Web MVC", "version": "5.0.6.RELEASE" }, - "language": { "name": "Java", "version": "11.0.7" }, + "framework": { + "name": "Spring Web MVC", + "version": "5.0.6.RELEASE" + }, + "language": { + "name": "Java", + "version": "11.0.7" + }, "name": "opbeans-java", "node": { "name": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "runtime": { "name": "Java", "version": "11.0.7" }, + "runtime": { + "name": "Java", + "version": "11.0.7" + }, "version": "None" }, - "source": { "ip": "172.18.0.9" }, - "timestamp": { "us": 1593413307824008 }, - "trace": { "id": "a6adb17bd5a5d1c0eabb9f36cb626dd5" }, + "source": { + "ip": "172.18.0.9" + }, + "timestamp": { + "us": 1593413293595007 + }, + "trace": { + "id": "8519b6c3dbc32a0582228506526e1d74" + }, "transaction": { - "duration": { "us": 5645 }, - "id": "df3e726eaa003d96", + "duration": { + "us": 7929 + }, + "id": "b0354de660cd3698", "name": "APIRestController#products", "result": "HTTP 2xx", "sampled": true, - "span_count": { "dropped": 0, "started": 3 }, + "span_count": { + "dropped": 0, + "started": 3 + }, "type": "request" }, "url": { @@ -2855,40 +4355,61 @@ "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "Python/3.7 aiohttp/3.3.2" } - }, - "p95": 7904, - "averageResponseTime": 6787, - "transactionsPerMinute": 0.5, - "impact": 0.4839483750082622 + } }, { - "name": "GET /api/products/:id/customers", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /api/products/:id/customers" + }, + "averageResponseTime": 4757, + "transactionsPerMinute": 0.5, + "impact": 0.25059559560997896, "sample": { - "@timestamp": "2020-06-29T06:48:41.956Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "@timestamp": "2020-06-29T06:48:22.977Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.994692Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:27.000765Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -2898,12 +4419,24 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["2"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:41 GMT"], - "Etag": ["W/\"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "2" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:22 GMT" + ], + "Etag": [ + "W/\"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -2933,90 +4466,146 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413321956016 }, - "trace": { "id": "f735ac5fca8f83eebc748f4a2e009e61" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413302977008 + }, + "trace": { + "id": "da8f22fe652ccb6680b3029ab6efd284" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 3896 }, - "id": "b24ce95c855f83a4", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 5618 + }, + "id": "bc51c1523afaf57a", "name": "GET /api/products/:id/customers", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "request" }, "url": { "domain": "opbeans-node", - "full": "http://opbeans-node:3000/api/products/5/customers", - "original": "/api/products/5/customers", - "path": "/api/products/5/customers", + "full": "http://opbeans-node:3000/api/products/3/customers", + "original": "/api/products/3/customers", + "path": "/api/products/3/customers", "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 5616, - "averageResponseTime": 4757, - "transactionsPerMinute": 0.5, - "impact": 0.25059559560997896 + } }, { - "name": "APIRestController#product", + "key": { + "service.name": "opbeans-java", + "transaction.name": "APIRestController#product" + }, + "averageResponseTime": 4713.5, + "transactionsPerMinute": 0.5, + "impact": 0.24559517890858723, "sample": { - "@timestamp": "2020-06-29T06:48:41.941Z", + "@timestamp": "2020-06-29T06:48:36.383Z", "agent": { "ephemeral_id": "222af346-6dd9-45ef-ac85-d86b67edd2de", "name": "java", "version": "1.17.1-SNAPSHOT" }, - "client": { "ip": "172.18.0.9" }, + "client": { + "ip": "172.18.0.9" + }, "container": { "id": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:46.709268Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:46.666467Z" + }, "host": { "architecture": "amd64", "hostname": "918ebbd99b4f", "ip": "172.18.0.6", "name": "918ebbd99b4f", - "os": { "platform": "Linux" } + "os": { + "platform": "Linux" + } }, "http": { "request": { "headers": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate"], - "Host": ["172.18.0.6:3000"], - "User-Agent": ["Python/3.7 aiohttp/3.3.2"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Host": [ + "172.18.0.6:3000" + ], + "User-Agent": [ + "Python/3.7 aiohttp/3.3.2" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "172.18.0.9" } + "socket": { + "encrypted": false, + "remote_address": "172.18.0.9" + } }, "response": { "finished": true, "headers": { - "Content-Type": ["application/json;charset=UTF-8"], - "Date": ["Mon, 29 Jun 2020 06:48:41 GMT"], - "Transfer-Encoding": ["chunked"] + "Content-Type": [ + "application/json;charset=UTF-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:36 GMT" + ], + "Transfer-Encoding": [ + "chunked" + ] }, "headers_sent": true, "status_code": 200 @@ -3031,81 +4620,131 @@ "version": "8.0.0", "version_major": 8 }, - "process": { "pid": 6, "ppid": 1, "title": "/opt/java/openjdk/bin/java" }, - "processor": { "event": "transaction", "name": "transaction" }, + "process": { + "pid": 6, + "ppid": 1, + "title": "/opt/java/openjdk/bin/java" + }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "Spring Web MVC", "version": "5.0.6.RELEASE" }, - "language": { "name": "Java", "version": "11.0.7" }, + "framework": { + "name": "Spring Web MVC", + "version": "5.0.6.RELEASE" + }, + "language": { + "name": "Java", + "version": "11.0.7" + }, "name": "opbeans-java", "node": { "name": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "runtime": { "name": "Java", "version": "11.0.7" }, + "runtime": { + "name": "Java", + "version": "11.0.7" + }, "version": "None" }, - "source": { "ip": "172.18.0.9" }, - "timestamp": { "us": 1593413321941007 }, - "trace": { "id": "88a2b9ca970cdd38dfa1b5646d26b897" }, + "source": { + "ip": "172.18.0.9" + }, + "timestamp": { + "us": 1593413316383008 + }, + "trace": { + "id": "386b450aef87fc079b20136eda542af1" + }, "transaction": { - "duration": { "us": 4539 }, - "id": "24ee0e4812cfed62", + "duration": { + "us": 4888 + }, + "id": "5a4aa02158b5658c", "name": "APIRestController#product", "result": "HTTP 2xx", "sampled": true, - "span_count": { "dropped": 0, "started": 2 }, + "span_count": { + "dropped": 0, + "started": 3 + }, "type": "request" }, "url": { "domain": "172.18.0.6", - "full": "http://172.18.0.6:3000/api/products/4", - "path": "/api/products/4", + "full": "http://172.18.0.6:3000/api/products/1", + "path": "/api/products/1", "port": 3000, "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "Python/3.7 aiohttp/3.3.2" } - }, - "p95": 4864, - "averageResponseTime": 4713.5, - "transactionsPerMinute": 0.5, - "impact": 0.24559517890858723 + } }, { - "name": "APIRestController#order", + "key": { + "service.name": "opbeans-java", + "transaction.name": "APIRestController#order" + }, + "averageResponseTime": 3392.5, + "transactionsPerMinute": 0.5, + "impact": 0.09374344413758617, "sample": { - "@timestamp": "2020-06-29T06:48:33.314Z", + "@timestamp": "2020-06-29T06:48:07.416Z", "agent": { "ephemeral_id": "222af346-6dd9-45ef-ac85-d86b67edd2de", "name": "java", "version": "1.17.1-SNAPSHOT" }, - "client": { "ip": "172.18.0.9" }, + "client": { + "ip": "172.18.0.9" + }, "container": { "id": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:36.137777Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:15.534378Z" + }, "host": { "architecture": "amd64", "hostname": "918ebbd99b4f", "ip": "172.18.0.6", "name": "918ebbd99b4f", - "os": { "platform": "Linux" } + "os": { + "platform": "Linux" + } }, "http": { "request": { "headers": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate"], - "Host": ["172.18.0.6:3000"], - "User-Agent": ["Python/3.7 aiohttp/3.3.2"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Host": [ + "172.18.0.6:3000" + ], + "User-Agent": [ + "Python/3.7 aiohttp/3.3.2" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "172.18.0.9" } + "socket": { + "encrypted": false, + "remote_address": "172.18.0.9" + } }, "response": { "finished": true, @@ -3122,88 +4761,144 @@ "version": "8.0.0", "version_major": 8 }, - "process": { "pid": 6, "ppid": 1, "title": "/opt/java/openjdk/bin/java" }, - "processor": { "event": "transaction", "name": "transaction" }, + "process": { + "pid": 6, + "ppid": 1, + "title": "/opt/java/openjdk/bin/java" + }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "Spring Web MVC", "version": "5.0.6.RELEASE" }, - "language": { "name": "Java", "version": "11.0.7" }, + "framework": { + "name": "Spring Web MVC", + "version": "5.0.6.RELEASE" + }, + "language": { + "name": "Java", + "version": "11.0.7" + }, "name": "opbeans-java", "node": { "name": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "runtime": { "name": "Java", "version": "11.0.7" }, + "runtime": { + "name": "Java", + "version": "11.0.7" + }, "version": "None" }, - "source": { "ip": "172.18.0.9" }, - "timestamp": { "us": 1593413313314007 }, - "trace": { "id": "aaf67f944393124080d1e4de804dc6eb" }, + "source": { + "ip": "172.18.0.9" + }, + "timestamp": { + "us": 1593413287416007 + }, + "trace": { + "id": "25c46380df3d44a192ed07279a08b329" + }, "transaction": { - "duration": { "us": 2503 }, - "id": "f7f9f5e0f8a3a0d4", + "duration": { + "us": 4282 + }, + "id": "d4d5b23c685d2ee5", "name": "APIRestController#order", "result": "HTTP 2xx", "sampled": true, - "span_count": { "dropped": 0, "started": 1 }, + "span_count": { + "dropped": 0, + "started": 1 + }, "type": "request" }, "url": { "domain": "172.18.0.6", - "full": "http://172.18.0.6:3000/api/orders/906", - "path": "/api/orders/906", + "full": "http://172.18.0.6:3000/api/orders/391", + "path": "/api/orders/391", "port": 3000, "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "Python/3.7 aiohttp/3.3.2" } - }, - "p95": 4272, - "averageResponseTime": 3392.5, - "transactionsPerMinute": 0.5, - "impact": 0.09374344413758617 + } }, { - "name": "APIRestController#orders", + "key": { + "service.name": "opbeans-java", + "transaction.name": "APIRestController#orders" + }, + "averageResponseTime": 3147, + "transactionsPerMinute": 0.5, + "impact": 0.06552270160444405, "sample": { - "@timestamp": "2020-06-29T06:48:39.500Z", + "@timestamp": "2020-06-29T06:48:16.028Z", "agent": { "ephemeral_id": "222af346-6dd9-45ef-ac85-d86b67edd2de", "name": "java", "version": "1.17.1-SNAPSHOT" }, - "client": { "ip": "172.18.0.9" }, + "client": { + "ip": "172.18.0.9" + }, "container": { "id": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:46.706280Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:25.800962Z" + }, "host": { "architecture": "amd64", "hostname": "918ebbd99b4f", "ip": "172.18.0.6", "name": "918ebbd99b4f", - "os": { "platform": "Linux" } + "os": { + "platform": "Linux" + } }, "http": { "request": { "headers": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate"], - "Host": ["172.18.0.6:3000"], - "User-Agent": ["Python/3.7 aiohttp/3.3.2"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Host": [ + "172.18.0.6:3000" + ], + "User-Agent": [ + "Python/3.7 aiohttp/3.3.2" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "172.18.0.9" } + "socket": { + "encrypted": false, + "remote_address": "172.18.0.9" + } }, "response": { "finished": true, "headers": { - "Content-Type": ["application/json;charset=UTF-8"], - "Date": ["Mon, 29 Jun 2020 06:48:38 GMT"], - "Transfer-Encoding": ["chunked"] + "Content-Type": [ + "application/json;charset=UTF-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:15 GMT" + ], + "Transfer-Encoding": [ + "chunked" + ] }, "headers_sent": true, "status_code": 200 @@ -3218,29 +4913,56 @@ "version": "8.0.0", "version_major": 8 }, - "process": { "pid": 6, "ppid": 1, "title": "/opt/java/openjdk/bin/java" }, - "processor": { "event": "transaction", "name": "transaction" }, + "process": { + "pid": 6, + "ppid": 1, + "title": "/opt/java/openjdk/bin/java" + }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "Spring Web MVC", "version": "5.0.6.RELEASE" }, - "language": { "name": "Java", "version": "11.0.7" }, + "framework": { + "name": "Spring Web MVC", + "version": "5.0.6.RELEASE" + }, + "language": { + "name": "Java", + "version": "11.0.7" + }, "name": "opbeans-java", "node": { "name": "918ebbd99b4f40003cf5713c080bb8120fa3bbe7ac4a96acb3aec558ced91ec0" }, - "runtime": { "name": "Java", "version": "11.0.7" }, + "runtime": { + "name": "Java", + "version": "11.0.7" + }, "version": "None" }, - "source": { "ip": "172.18.0.9" }, - "timestamp": { "us": 1593413319500008 }, - "trace": { "id": "f89b02f09a2e7a7f2cc3478f53d4a495" }, + "source": { + "ip": "172.18.0.9" + }, + "timestamp": { + "us": 1593413296028008 + }, + "trace": { + "id": "4110227ecacbccf79894165ae5df932d" + }, "transaction": { - "duration": { "us": 3391 }, - "id": "41c8c4300ee2ccda", + "duration": { + "us": 2903 + }, + "id": "8e3732f0f0da942b", "name": "APIRestController#orders", "result": "HTTP 2xx", "sampled": true, - "span_count": { "dropped": 0, "started": 2 }, + "span_count": { + "dropped": 0, + "started": 1 + }, "type": "request" }, "url": { @@ -3251,40 +4973,61 @@ "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "Python/3.7 aiohttp/3.3.2" } - }, - "p95": 3376, - "averageResponseTime": 3147, - "transactionsPerMinute": 0.5, - "impact": 0.06552270160444405 + } }, { - "name": "GET /throw-error", + "key": { + "service.name": "opbeans-node", + "transaction.name": "GET /throw-error" + }, + "averageResponseTime": 2577, + "transactionsPerMinute": 0.5, + "impact": 0, "sample": { - "@timestamp": "2020-06-29T06:48:42.954Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, + "@timestamp": "2020-06-29T06:48:19.975Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.996435Z" }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:21.012520Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", "socket": { @@ -3294,13 +5037,27 @@ }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["148"], - "Content-Security-Policy": ["default-src 'none'"], - "Content-Type": ["text/html; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:42 GMT"], - "X-Content-Type-Options": ["nosniff"], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "148" + ], + "Content-Security-Policy": [ + "default-src 'none'" + ], + "Content-Type": [ + "text/html; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:19 GMT" + ], + "X-Content-Type-Options": [ + "nosniff" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 500 }, @@ -3330,29 +5087,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413322954016 }, - "trace": { "id": "9d5aee7443a43db9820f622a10dfac6e" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413299975019 + }, + "trace": { + "id": "106f3a55b0b0ea327d1bbe4be66c3bcc" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 1928 }, - "id": "8e6fc8c3f99e8fc9", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 3226 + }, + "id": "247b9141552a9e73", "name": "GET /throw-error", "result": "HTTP 5xx", "sampled": true, - "span_count": { "started": 0 }, + "span_count": { + "started": 0 + }, "type": "request" }, "url": { @@ -3363,16 +5143,18 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 3224, - "averageResponseTime": 2577, - "transactionsPerMinute": 0.5, - "impact": 0 + } } ] diff --git a/x-pack/test/apm_api_integration/basic/tests/traces/top_traces.ts b/x-pack/test/apm_api_integration/basic/tests/traces/top_traces.ts index e96cb20a68fda..b4a037436adb8 100644 --- a/x-pack/test/apm_api_integration/basic/tests/traces/top_traces.ts +++ b/x-pack/test/apm_api_integration/basic/tests/traces/top_traces.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import expect from '@kbn/expect'; +import { sortBy, omit } from 'lodash'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import expectTopTraces from './expectation/top_traces.expectation.json'; @@ -46,8 +47,28 @@ export default function ApiTest({ getService }: FtrProviderContext) { expect(response.body.items.length).to.be(33); }); - it('returns the correct buckets and samples', async () => { - expect(response.body.items).to.eql(expectTopTraces); + it('returns the correct buckets', async () => { + const responseWithoutSamples = sortBy( + response.body.items.map((item: any) => omit(item, 'sample')), + 'impact' + ); + + const expectedTracesWithoutSamples = sortBy( + expectTopTraces.map((item: any) => omit(item, 'sample')), + 'impact' + ); + + expect(responseWithoutSamples).to.eql(expectedTracesWithoutSamples); + }); + + it('returns a sample', async () => { + // sample should provide enough information to deeplink to a transaction detail page + response.body.items.forEach((item: any) => { + expect(item.sample.trace.id).to.be.an('string'); + expect(item.sample.transaction.id).to.be.an('string'); + expect(item.sample.service.name).to.be(item.key['service.name']); + expect(item.sample.transaction.name).to.be(item.key['transaction.name']); + }); }); }); }); diff --git a/x-pack/test/apm_api_integration/basic/tests/transaction_groups/avg_duration_by_browser.ts b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/avg_duration_by_browser.ts new file mode 100644 index 0000000000000..690935ddc7f6a --- /dev/null +++ b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/avg_duration_by_browser.ts @@ -0,0 +1,53 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../common/ftr_provider_context'; +import expectedAvgDurationByBrowser from './expectation/avg_duration_by_browser.json'; +import expectedAvgDurationByBrowserWithTransactionName from './expectation/avg_duration_by_browser_transaction_name.json'; + +export default function ApiTest({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const esArchiver = getService('esArchiver'); + + const start = encodeURIComponent('2020-06-29T06:45:00.000Z'); + const end = encodeURIComponent('2020-06-29T06:49:00.000Z'); + const transactionName = '/products'; + const uiFilters = encodeURIComponent(JSON.stringify({})); + + describe('Average duration by browser', () => { + describe('when data is not loaded', () => { + it('handles the empty state', async () => { + const response = await supertest.get( + `/api/apm/services/client/transaction_groups/avg_duration_by_browser?start=${start}&end=${end}&uiFilters=${uiFilters}` + ); + expect(response.status).to.be(200); + expect(response.body).to.eql([]); + }); + }); + + describe('when data is loaded', () => { + before(() => esArchiver.load('8.0.0')); + after(() => esArchiver.unload('8.0.0')); + + it('returns the average duration by browser', async () => { + const response = await supertest.get( + `/api/apm/services/client/transaction_groups/avg_duration_by_browser?start=${start}&end=${end}&uiFilters=${uiFilters}` + ); + + expect(response.status).to.be(200); + expect(response.body).to.eql(expectedAvgDurationByBrowser); + }); + it('returns the average duration by browser filtering by transaction name', async () => { + const response = await supertest.get( + `/api/apm/services/client/transaction_groups/avg_duration_by_browser?start=${start}&end=${end}&uiFilters=${uiFilters}&transactionName=${transactionName}` + ); + + expect(response.status).to.be(200); + expect(response.body).to.eql(expectedAvgDurationByBrowserWithTransactionName); + }); + }); + }); +} diff --git a/x-pack/test/apm_api_integration/basic/tests/transaction_groups/breakdown.ts b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/breakdown.ts new file mode 100644 index 0000000000000..5b61112a374c1 --- /dev/null +++ b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/breakdown.ts @@ -0,0 +1,67 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../common/ftr_provider_context'; +import expectedBreakdown from './expectation/breakdown.json'; +import expectedBreakdownWithTransactionName from './expectation/breakdown_transaction_name.json'; + +export default function ApiTest({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const esArchiver = getService('esArchiver'); + + const start = encodeURIComponent('2020-06-29T06:45:00.000Z'); + const end = encodeURIComponent('2020-06-29T06:49:00.000Z'); + const transactionType = 'request'; + const transactionName = 'GET /api'; + const uiFilters = encodeURIComponent(JSON.stringify({})); + + describe('Breakdown', () => { + describe('when data is not loaded', () => { + it('handles the empty state', async () => { + const response = await supertest.get( + `/api/apm/services/opbeans-node/transaction_groups/breakdown?start=${start}&end=${end}&uiFilters=${uiFilters}&transactionType=${transactionType}` + ); + expect(response.status).to.be(200); + expect(response.body).to.eql({ kpis: [], timeseries: [] }); + }); + }); + + describe('when data is loaded', () => { + before(() => esArchiver.load('8.0.0')); + after(() => esArchiver.unload('8.0.0')); + + it('returns the transaction breakdown for a service', async () => { + const response = await supertest.get( + `/api/apm/services/opbeans-node/transaction_groups/breakdown?start=${start}&end=${end}&uiFilters=${uiFilters}&transactionType=${transactionType}` + ); + + expect(response.status).to.be(200); + expect(response.body).to.eql(expectedBreakdown); + }); + it('returns the transaction breakdown for a transaction group', async () => { + const response = await supertest.get( + `/api/apm/services/opbeans-node/transaction_groups/breakdown?start=${start}&end=${end}&uiFilters=${uiFilters}&transactionType=${transactionType}&transactionName=${transactionName}` + ); + + expect(response.status).to.be(200); + expect(response.body).to.eql(expectedBreakdownWithTransactionName); + }); + it('returns the top 4 by percentage and sorts them by name', async () => { + const response = await supertest.get( + `/api/apm/services/opbeans-node/transaction_groups/breakdown?start=${start}&end=${end}&uiFilters=${uiFilters}&transactionType=${transactionType}` + ); + + expect(response.status).to.be(200); + expect(response.body.kpis.map((kpi: { name: string }) => kpi.name)).to.eql([ + 'app', + 'http', + 'postgresql', + 'redis', + ]); + }); + }); + }); +} diff --git a/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/avg_duration_by_browser.json b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/avg_duration_by_browser.json new file mode 100644 index 0000000000000..cd53af3bf7080 --- /dev/null +++ b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/avg_duration_by_browser.json @@ -0,0 +1,735 @@ +[ + { + "title":"HeadlessChrome", + "data":[ + { + "x":1593413100000 + }, + { + "x":1593413101000 + }, + { + "x":1593413102000 + }, + { + "x":1593413103000 + }, + { + "x":1593413104000 + }, + { + "x":1593413105000 + }, + { + "x":1593413106000 + }, + { + "x":1593413107000 + }, + { + "x":1593413108000 + }, + { + "x":1593413109000 + }, + { + "x":1593413110000 + }, + { + "x":1593413111000 + }, + { + "x":1593413112000 + }, + { + "x":1593413113000 + }, + { + "x":1593413114000 + }, + { + "x":1593413115000 + }, + { + "x":1593413116000 + }, + { + "x":1593413117000 + }, + { + "x":1593413118000 + }, + { + "x":1593413119000 + }, + { + "x":1593413120000 + }, + { + "x":1593413121000 + }, + { + "x":1593413122000 + }, + { + "x":1593413123000 + }, + { + "x":1593413124000 + }, + { + "x":1593413125000 + }, + { + "x":1593413126000 + }, + { + "x":1593413127000 + }, + { + "x":1593413128000 + }, + { + "x":1593413129000 + }, + { + "x":1593413130000 + }, + { + "x":1593413131000 + }, + { + "x":1593413132000 + }, + { + "x":1593413133000 + }, + { + "x":1593413134000 + }, + { + "x":1593413135000 + }, + { + "x":1593413136000 + }, + { + "x":1593413137000 + }, + { + "x":1593413138000 + }, + { + "x":1593413139000 + }, + { + "x":1593413140000 + }, + { + "x":1593413141000 + }, + { + "x":1593413142000 + }, + { + "x":1593413143000 + }, + { + "x":1593413144000 + }, + { + "x":1593413145000 + }, + { + "x":1593413146000 + }, + { + "x":1593413147000 + }, + { + "x":1593413148000 + }, + { + "x":1593413149000 + }, + { + "x":1593413150000 + }, + { + "x":1593413151000 + }, + { + "x":1593413152000 + }, + { + "x":1593413153000 + }, + { + "x":1593413154000 + }, + { + "x":1593413155000 + }, + { + "x":1593413156000 + }, + { + "x":1593413157000 + }, + { + "x":1593413158000 + }, + { + "x":1593413159000 + }, + { + "x":1593413160000 + }, + { + "x":1593413161000 + }, + { + "x":1593413162000 + }, + { + "x":1593413163000 + }, + { + "x":1593413164000 + }, + { + "x":1593413165000 + }, + { + "x":1593413166000 + }, + { + "x":1593413167000 + }, + { + "x":1593413168000 + }, + { + "x":1593413169000 + }, + { + "x":1593413170000 + }, + { + "x":1593413171000 + }, + { + "x":1593413172000 + }, + { + "x":1593413173000 + }, + { + "x":1593413174000 + }, + { + "x":1593413175000 + }, + { + "x":1593413176000 + }, + { + "x":1593413177000 + }, + { + "x":1593413178000 + }, + { + "x":1593413179000 + }, + { + "x":1593413180000 + }, + { + "x":1593413181000 + }, + { + "x":1593413182000 + }, + { + "x":1593413183000 + }, + { + "x":1593413184000 + }, + { + "x":1593413185000 + }, + { + "x":1593413186000 + }, + { + "x":1593413187000 + }, + { + "x":1593413188000 + }, + { + "x":1593413189000 + }, + { + "x":1593413190000 + }, + { + "x":1593413191000 + }, + { + "x":1593413192000 + }, + { + "x":1593413193000 + }, + { + "x":1593413194000 + }, + { + "x":1593413195000 + }, + { + "x":1593413196000 + }, + { + "x":1593413197000 + }, + { + "x":1593413198000 + }, + { + "x":1593413199000 + }, + { + "x":1593413200000 + }, + { + "x":1593413201000 + }, + { + "x":1593413202000 + }, + { + "x":1593413203000 + }, + { + "x":1593413204000 + }, + { + "x":1593413205000 + }, + { + "x":1593413206000 + }, + { + "x":1593413207000 + }, + { + "x":1593413208000 + }, + { + "x":1593413209000 + }, + { + "x":1593413210000 + }, + { + "x":1593413211000 + }, + { + "x":1593413212000 + }, + { + "x":1593413213000 + }, + { + "x":1593413214000 + }, + { + "x":1593413215000 + }, + { + "x":1593413216000 + }, + { + "x":1593413217000 + }, + { + "x":1593413218000 + }, + { + "x":1593413219000 + }, + { + "x":1593413220000 + }, + { + "x":1593413221000 + }, + { + "x":1593413222000 + }, + { + "x":1593413223000 + }, + { + "x":1593413224000 + }, + { + "x":1593413225000 + }, + { + "x":1593413226000 + }, + { + "x":1593413227000 + }, + { + "x":1593413228000 + }, + { + "x":1593413229000 + }, + { + "x":1593413230000 + }, + { + "x":1593413231000 + }, + { + "x":1593413232000 + }, + { + "x":1593413233000 + }, + { + "x":1593413234000 + }, + { + "x":1593413235000 + }, + { + "x":1593413236000 + }, + { + "x":1593413237000 + }, + { + "x":1593413238000 + }, + { + "x":1593413239000 + }, + { + "x":1593413240000 + }, + { + "x":1593413241000 + }, + { + "x":1593413242000 + }, + { + "x":1593413243000 + }, + { + "x":1593413244000 + }, + { + "x":1593413245000 + }, + { + "x":1593413246000 + }, + { + "x":1593413247000 + }, + { + "x":1593413248000 + }, + { + "x":1593413249000 + }, + { + "x":1593413250000 + }, + { + "x":1593413251000 + }, + { + "x":1593413252000 + }, + { + "x":1593413253000 + }, + { + "x":1593413254000 + }, + { + "x":1593413255000 + }, + { + "x":1593413256000 + }, + { + "x":1593413257000 + }, + { + "x":1593413258000 + }, + { + "x":1593413259000 + }, + { + "x":1593413260000 + }, + { + "x":1593413261000 + }, + { + "x":1593413262000 + }, + { + "x":1593413263000 + }, + { + "x":1593413264000 + }, + { + "x":1593413265000 + }, + { + "x":1593413266000 + }, + { + "x":1593413267000 + }, + { + "x":1593413268000 + }, + { + "x":1593413269000 + }, + { + "x":1593413270000 + }, + { + "x":1593413271000 + }, + { + "x":1593413272000 + }, + { + "x":1593413273000 + }, + { + "x":1593413274000 + }, + { + "x":1593413275000 + }, + { + "x":1593413276000 + }, + { + "x":1593413277000 + }, + { + "x":1593413278000 + }, + { + "x":1593413279000 + }, + { + "x":1593413280000 + }, + { + "x":1593413281000 + }, + { + "x":1593413282000 + }, + { + "x":1593413283000 + }, + { + "x":1593413284000 + }, + { + "x":1593413285000 + }, + { + "x":1593413286000 + }, + { + "x":1593413287000, + "y":342000 + }, + { + "x":1593413288000 + }, + { + "x":1593413289000 + }, + { + "x":1593413290000 + }, + { + "x":1593413291000 + }, + { + "x":1593413292000 + }, + { + "x":1593413293000 + }, + { + "x":1593413294000 + }, + { + "x":1593413295000 + }, + { + "x":1593413296000 + }, + { + "x":1593413297000 + }, + { + "x":1593413298000, + "y":173000 + }, + { + "x":1593413299000 + }, + { + "x":1593413300000 + }, + { + "x":1593413301000, + "y":109000 + }, + { + "x":1593413302000 + }, + { + "x":1593413303000 + }, + { + "x":1593413304000 + }, + { + "x":1593413305000 + }, + { + "x":1593413306000 + }, + { + "x":1593413307000 + }, + { + "x":1593413308000 + }, + { + "x":1593413309000 + }, + { + "x":1593413310000 + }, + { + "x":1593413311000 + }, + { + "x":1593413312000 + }, + { + "x":1593413313000 + }, + { + "x":1593413314000 + }, + { + "x":1593413315000 + }, + { + "x":1593413316000 + }, + { + "x":1593413317000 + }, + { + "x":1593413318000, + "y":140000 + }, + { + "x":1593413319000 + }, + { + "x":1593413320000 + }, + { + "x":1593413321000 + }, + { + "x":1593413322000 + }, + { + "x":1593413323000 + }, + { + "x":1593413324000 + }, + { + "x":1593413325000 + }, + { + "x":1593413326000 + }, + { + "x":1593413327000 + }, + { + "x":1593413328000, + "y":77000 + }, + { + "x":1593413329000 + }, + { + "x":1593413330000 + }, + { + "x":1593413331000 + }, + { + "x":1593413332000 + }, + { + "x":1593413333000 + }, + { + "x":1593413334000 + }, + { + "x":1593413335000 + }, + { + "x":1593413336000 + }, + { + "x":1593413337000 + }, + { + "x":1593413338000 + }, + { + "x":1593413339000 + }, + { + "x":1593413340000 + } + ] + } +] \ No newline at end of file diff --git a/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/avg_duration_by_browser_transaction_name.json b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/avg_duration_by_browser_transaction_name.json new file mode 100644 index 0000000000000..107302831d55f --- /dev/null +++ b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/avg_duration_by_browser_transaction_name.json @@ -0,0 +1,731 @@ +[ + { + "title":"HeadlessChrome", + "data":[ + { + "x":1593413100000 + }, + { + "x":1593413101000 + }, + { + "x":1593413102000 + }, + { + "x":1593413103000 + }, + { + "x":1593413104000 + }, + { + "x":1593413105000 + }, + { + "x":1593413106000 + }, + { + "x":1593413107000 + }, + { + "x":1593413108000 + }, + { + "x":1593413109000 + }, + { + "x":1593413110000 + }, + { + "x":1593413111000 + }, + { + "x":1593413112000 + }, + { + "x":1593413113000 + }, + { + "x":1593413114000 + }, + { + "x":1593413115000 + }, + { + "x":1593413116000 + }, + { + "x":1593413117000 + }, + { + "x":1593413118000 + }, + { + "x":1593413119000 + }, + { + "x":1593413120000 + }, + { + "x":1593413121000 + }, + { + "x":1593413122000 + }, + { + "x":1593413123000 + }, + { + "x":1593413124000 + }, + { + "x":1593413125000 + }, + { + "x":1593413126000 + }, + { + "x":1593413127000 + }, + { + "x":1593413128000 + }, + { + "x":1593413129000 + }, + { + "x":1593413130000 + }, + { + "x":1593413131000 + }, + { + "x":1593413132000 + }, + { + "x":1593413133000 + }, + { + "x":1593413134000 + }, + { + "x":1593413135000 + }, + { + "x":1593413136000 + }, + { + "x":1593413137000 + }, + { + "x":1593413138000 + }, + { + "x":1593413139000 + }, + { + "x":1593413140000 + }, + { + "x":1593413141000 + }, + { + "x":1593413142000 + }, + { + "x":1593413143000 + }, + { + "x":1593413144000 + }, + { + "x":1593413145000 + }, + { + "x":1593413146000 + }, + { + "x":1593413147000 + }, + { + "x":1593413148000 + }, + { + "x":1593413149000 + }, + { + "x":1593413150000 + }, + { + "x":1593413151000 + }, + { + "x":1593413152000 + }, + { + "x":1593413153000 + }, + { + "x":1593413154000 + }, + { + "x":1593413155000 + }, + { + "x":1593413156000 + }, + { + "x":1593413157000 + }, + { + "x":1593413158000 + }, + { + "x":1593413159000 + }, + { + "x":1593413160000 + }, + { + "x":1593413161000 + }, + { + "x":1593413162000 + }, + { + "x":1593413163000 + }, + { + "x":1593413164000 + }, + { + "x":1593413165000 + }, + { + "x":1593413166000 + }, + { + "x":1593413167000 + }, + { + "x":1593413168000 + }, + { + "x":1593413169000 + }, + { + "x":1593413170000 + }, + { + "x":1593413171000 + }, + { + "x":1593413172000 + }, + { + "x":1593413173000 + }, + { + "x":1593413174000 + }, + { + "x":1593413175000 + }, + { + "x":1593413176000 + }, + { + "x":1593413177000 + }, + { + "x":1593413178000 + }, + { + "x":1593413179000 + }, + { + "x":1593413180000 + }, + { + "x":1593413181000 + }, + { + "x":1593413182000 + }, + { + "x":1593413183000 + }, + { + "x":1593413184000 + }, + { + "x":1593413185000 + }, + { + "x":1593413186000 + }, + { + "x":1593413187000 + }, + { + "x":1593413188000 + }, + { + "x":1593413189000 + }, + { + "x":1593413190000 + }, + { + "x":1593413191000 + }, + { + "x":1593413192000 + }, + { + "x":1593413193000 + }, + { + "x":1593413194000 + }, + { + "x":1593413195000 + }, + { + "x":1593413196000 + }, + { + "x":1593413197000 + }, + { + "x":1593413198000 + }, + { + "x":1593413199000 + }, + { + "x":1593413200000 + }, + { + "x":1593413201000 + }, + { + "x":1593413202000 + }, + { + "x":1593413203000 + }, + { + "x":1593413204000 + }, + { + "x":1593413205000 + }, + { + "x":1593413206000 + }, + { + "x":1593413207000 + }, + { + "x":1593413208000 + }, + { + "x":1593413209000 + }, + { + "x":1593413210000 + }, + { + "x":1593413211000 + }, + { + "x":1593413212000 + }, + { + "x":1593413213000 + }, + { + "x":1593413214000 + }, + { + "x":1593413215000 + }, + { + "x":1593413216000 + }, + { + "x":1593413217000 + }, + { + "x":1593413218000 + }, + { + "x":1593413219000 + }, + { + "x":1593413220000 + }, + { + "x":1593413221000 + }, + { + "x":1593413222000 + }, + { + "x":1593413223000 + }, + { + "x":1593413224000 + }, + { + "x":1593413225000 + }, + { + "x":1593413226000 + }, + { + "x":1593413227000 + }, + { + "x":1593413228000 + }, + { + "x":1593413229000 + }, + { + "x":1593413230000 + }, + { + "x":1593413231000 + }, + { + "x":1593413232000 + }, + { + "x":1593413233000 + }, + { + "x":1593413234000 + }, + { + "x":1593413235000 + }, + { + "x":1593413236000 + }, + { + "x":1593413237000 + }, + { + "x":1593413238000 + }, + { + "x":1593413239000 + }, + { + "x":1593413240000 + }, + { + "x":1593413241000 + }, + { + "x":1593413242000 + }, + { + "x":1593413243000 + }, + { + "x":1593413244000 + }, + { + "x":1593413245000 + }, + { + "x":1593413246000 + }, + { + "x":1593413247000 + }, + { + "x":1593413248000 + }, + { + "x":1593413249000 + }, + { + "x":1593413250000 + }, + { + "x":1593413251000 + }, + { + "x":1593413252000 + }, + { + "x":1593413253000 + }, + { + "x":1593413254000 + }, + { + "x":1593413255000 + }, + { + "x":1593413256000 + }, + { + "x":1593413257000 + }, + { + "x":1593413258000 + }, + { + "x":1593413259000 + }, + { + "x":1593413260000 + }, + { + "x":1593413261000 + }, + { + "x":1593413262000 + }, + { + "x":1593413263000 + }, + { + "x":1593413264000 + }, + { + "x":1593413265000 + }, + { + "x":1593413266000 + }, + { + "x":1593413267000 + }, + { + "x":1593413268000 + }, + { + "x":1593413269000 + }, + { + "x":1593413270000 + }, + { + "x":1593413271000 + }, + { + "x":1593413272000 + }, + { + "x":1593413273000 + }, + { + "x":1593413274000 + }, + { + "x":1593413275000 + }, + { + "x":1593413276000 + }, + { + "x":1593413277000 + }, + { + "x":1593413278000 + }, + { + "x":1593413279000 + }, + { + "x":1593413280000 + }, + { + "x":1593413281000 + }, + { + "x":1593413282000 + }, + { + "x":1593413283000 + }, + { + "x":1593413284000 + }, + { + "x":1593413285000 + }, + { + "x":1593413286000 + }, + { + "x":1593413287000 + }, + { + "x":1593413288000 + }, + { + "x":1593413289000 + }, + { + "x":1593413290000 + }, + { + "x":1593413291000 + }, + { + "x":1593413292000 + }, + { + "x":1593413293000 + }, + { + "x":1593413294000 + }, + { + "x":1593413295000 + }, + { + "x":1593413296000 + }, + { + "x":1593413297000 + }, + { + "x":1593413298000 + }, + { + "x":1593413299000 + }, + { + "x":1593413300000 + }, + { + "x":1593413301000 + }, + { + "x":1593413302000 + }, + { + "x":1593413303000 + }, + { + "x":1593413304000 + }, + { + "x":1593413305000 + }, + { + "x":1593413306000 + }, + { + "x":1593413307000 + }, + { + "x":1593413308000 + }, + { + "x":1593413309000 + }, + { + "x":1593413310000 + }, + { + "x":1593413311000 + }, + { + "x":1593413312000 + }, + { + "x":1593413313000 + }, + { + "x":1593413314000 + }, + { + "x":1593413315000 + }, + { + "x":1593413316000 + }, + { + "x":1593413317000 + }, + { + "x":1593413318000 + }, + { + "x":1593413319000 + }, + { + "x":1593413320000 + }, + { + "x":1593413321000 + }, + { + "x":1593413322000 + }, + { + "x":1593413323000 + }, + { + "x":1593413324000 + }, + { + "x":1593413325000 + }, + { + "x":1593413326000 + }, + { + "x":1593413327000 + }, + { + "x":1593413328000, + "y":77000 + }, + { + "x":1593413329000 + }, + { + "x":1593413330000 + }, + { + "x":1593413331000 + }, + { + "x":1593413332000 + }, + { + "x":1593413333000 + }, + { + "x":1593413334000 + }, + { + "x":1593413335000 + }, + { + "x":1593413336000 + }, + { + "x":1593413337000 + }, + { + "x":1593413338000 + }, + { + "x":1593413339000 + }, + { + "x":1593413340000 + } + ] + } +] \ No newline at end of file diff --git a/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/breakdown.json b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/breakdown.json new file mode 100644 index 0000000000000..3b884a9eb7907 --- /dev/null +++ b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/breakdown.json @@ -0,0 +1,202 @@ +{ + "kpis":[ + { + "name":"app", + "percentage":0.16700861715223636, + "color":"#54b399" + }, + { + "name":"http", + "percentage":0.7702092736971686, + "color":"#6092c0" + }, + { + "name":"postgresql", + "percentage":0.0508822322527698, + "color":"#d36086" + }, + { + "name":"redis", + "percentage":0.011899876897825195, + "color":"#9170b8" + } + ], + "timeseries":[ + { + "title":"app", + "color":"#54b399", + "type":"areaStacked", + "data":[ + { + "x":1593413100000, + "y":null + }, + { + "x":1593413130000, + "y":null + }, + { + "x":1593413160000, + "y":null + }, + { + "x":1593413190000, + "y":null + }, + { + "x":1593413220000, + "y":null + }, + { + "x":1593413250000, + "y":null + }, + { + "x":1593413280000, + "y":null + }, + { + "x":1593413310000, + "y":0.16700861715223636 + }, + { + "x":1593413340000, + "y":null + } + ], + "hideLegend":true + }, + { + "title":"http", + "color":"#6092c0", + "type":"areaStacked", + "data":[ + { + "x":1593413100000, + "y":null + }, + { + "x":1593413130000, + "y":null + }, + { + "x":1593413160000, + "y":null + }, + { + "x":1593413190000, + "y":null + }, + { + "x":1593413220000, + "y":null + }, + { + "x":1593413250000, + "y":null + }, + { + "x":1593413280000, + "y":null + }, + { + "x":1593413310000, + "y":0.7702092736971686 + }, + { + "x":1593413340000, + "y":null + } + ], + "hideLegend":true + }, + { + "title":"postgresql", + "color":"#d36086", + "type":"areaStacked", + "data":[ + { + "x":1593413100000, + "y":null + }, + { + "x":1593413130000, + "y":null + }, + { + "x":1593413160000, + "y":null + }, + { + "x":1593413190000, + "y":null + }, + { + "x":1593413220000, + "y":null + }, + { + "x":1593413250000, + "y":null + }, + { + "x":1593413280000, + "y":null + }, + { + "x":1593413310000, + "y":0.0508822322527698 + }, + { + "x":1593413340000, + "y":null + } + ], + "hideLegend":true + }, + { + "title":"redis", + "color":"#9170b8", + "type":"areaStacked", + "data":[ + { + "x":1593413100000, + "y":null + }, + { + "x":1593413130000, + "y":null + }, + { + "x":1593413160000, + "y":null + }, + { + "x":1593413190000, + "y":null + }, + { + "x":1593413220000, + "y":null + }, + { + "x":1593413250000, + "y":null + }, + { + "x":1593413280000, + "y":null + }, + { + "x":1593413310000, + "y":0.011899876897825195 + }, + { + "x":1593413340000, + "y":null + } + ], + "hideLegend":true + } + ] +} \ No newline at end of file diff --git a/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/breakdown_transaction_name.json b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/breakdown_transaction_name.json new file mode 100644 index 0000000000000..b4f8e376d3609 --- /dev/null +++ b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/breakdown_transaction_name.json @@ -0,0 +1,55 @@ +{ + "kpis":[ + { + "name":"app", + "percentage":1, + "color":"#54b399" + } + ], + "timeseries":[ + { + "title":"app", + "color":"#54b399", + "type":"areaStacked", + "data":[ + { + "x":1593413100000, + "y":null + }, + { + "x":1593413130000, + "y":null + }, + { + "x":1593413160000, + "y":null + }, + { + "x":1593413190000, + "y":null + }, + { + "x":1593413220000, + "y":null + }, + { + "x":1593413250000, + "y":null + }, + { + "x":1593413280000, + "y":null + }, + { + "x":1593413310000, + "y":1 + }, + { + "x":1593413340000, + "y":null + } + ], + "hideLegend":true + } + ] +} \ No newline at end of file diff --git a/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/top_transaction_groups.json b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/top_transaction_groups.json index 7d314e75e4d1d..29c55d4ef1b5c 100644 --- a/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/top_transaction_groups.json +++ b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/expectation/top_transaction_groups.json @@ -1,38 +1,86 @@ { "items": [ { - "name": "GET /api", + "key": "GET /api", + "averageResponseTime": 51175.73170731707, + "transactionsPerMinute": 10.25, + "impact": 100, + "p95": 259040, "sample": { - "@timestamp": "2020-06-29T06:48:41.454Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.992834Z" }, + "@timestamp": "2020-06-29T06:48:06.862Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.8" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:08.305742Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Connection": [ + "keep-alive" + ], + "Host": [ + "opbeans-node:3000" + ], + "Referer": [ + "http://opbeans-node:3000/dashboard" + ], + "Traceparent": [ + "00-ca86ffcac7753ec8733933bd8fd45d11-5dcb98c9c9021cfc-01" + ], + "User-Agent": [ + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.8" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Type": ["application/json;charset=UTF-8"], - "Date": ["Mon, 29 Jun 2020 06:48:41 GMT"], - "Transfer-Encoding": ["chunked"], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Type": [ + "application/json;charset=UTF-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:06 GMT" + ], + "Transfer-Encoding": [ + "chunked" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -52,6 +100,9 @@ "version": "8.0.0", "version_major": 8 }, + "parent": { + "id": "5dcb98c9c9021cfc" + }, "process": { "args": [ "/usr/local/bin/node", @@ -62,87 +113,164 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413321454009 }, - "trace": { "id": "0507830eeff93f7bf1a354e4031097b3" }, + "source": { + "ip": "172.18.0.8" + }, + "timestamp": { + "us": 1593413286862021 + }, + "trace": { + "id": "ca86ffcac7753ec8733933bd8fd45d11" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 8334 }, - "id": "878250a8b937445d", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 15738 + }, + "id": "c95371db21c6f407", "name": "GET /api", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "request" }, "url": { "domain": "opbeans-node", - "full": "http://opbeans-node:3000/api/products/6", - "original": "/api/products/6", - "path": "/api/products/6", + "full": "http://opbeans-node:3000/api/products/top", + "original": "/api/products/top", + "path": "/api/products/top", "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, - "name": "Other", - "original": "workload/2.4.3" + "device": { + "name": "Other" + }, + "name": "HeadlessChrome", + "original": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36", + "os": { + "name": "Linux" + }, + "version": "79.0.3945" } - }, - "p95": 259040, - "averageResponseTime": 51175.73170731707, - "transactionsPerMinute": 10.25, - "impact": 100 + } }, { - "name": "POST /api/orders", + "key": "POST /api/orders", + "averageResponseTime": 270684, + "transactionsPerMinute": 0.25, + "impact": 12.686265169840583, + "p95": 270336, "sample": { "@timestamp": "2020-06-29T06:48:39.953Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.991549Z" }, + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:43.991549Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { - "body": { "original": "[REDACTED]" }, + "body": { + "original": "[REDACTED]" + }, "headers": { - "Accept": ["application/json"], - "Connection": ["close"], - "Content-Length": ["129"], - "Content-Type": ["application/json"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Accept": [ + "application/json" + ], + "Connection": [ + "close" + ], + "Content-Length": [ + "129" + ], + "Content-Type": [ + "application/json" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "post", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["13"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:40 GMT"], - "Etag": ["W/\"d-eEOWU4Cnr5DZ23ErRUeYu9oOIks\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "13" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:40 GMT" + ], + "Etag": [ + "W/\"d-eEOWU4Cnr5DZ23ErRUeYu9oOIks\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -172,27 +300,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413319953033 }, - "trace": { "id": "52b8fda5f6df745b990740ba18378620" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413319953033 + }, + "trace": { + "id": "52b8fda5f6df745b990740ba18378620" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 270684 }, + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 270684 + }, "id": "a3afc2a112e9c893", "name": "POST /api/orders", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 16 }, + "span_count": { + "started": 16 + }, "type": "request" }, "url": { @@ -203,52 +356,92 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 270336, - "averageResponseTime": 270684, - "transactionsPerMinute": 0.25, - "impact": 12.686265169840583 + } }, { - "name": "GET /api/customers", + "key": "GET /api/customers", + "averageResponseTime": 16896.8, + "transactionsPerMinute": 1.25, + "impact": 3.790160870423129, + "p95": 26432, "sample": { - "@timestamp": "2020-06-29T06:48:37.952Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:39.492402Z" }, + "@timestamp": "2020-06-29T06:48:28.444Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:29.982737Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["186769"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:37 GMT"], - "Etag": ["W/\"2d991-yG3J8W/roH7fSxXTudZrO27Ax9s\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "186769" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:28 GMT" + ], + "Etag": [ + "W/\"2d991-yG3J8W/roH7fSxXTudZrO27Ax9s\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -278,27 +471,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413317952016 }, - "trace": { "id": "5d99327edae38ed735e8d7a6028cf719" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413308444015 + }, + "trace": { + "id": "792fb0b00256164e88b277ec40b65e14" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 16824 }, - "id": "071808429ec9d00b", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 26471 + }, + "id": "6c1f848752563d2b", "name": "GET /api/customers", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 2 }, + "span_count": { + "started": 2 + }, "type": "request" }, "url": { @@ -309,52 +527,92 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 26432, - "averageResponseTime": 16896.8, - "transactionsPerMinute": 1.25, - "impact": 3.790160870423129 + } }, { - "name": "GET /log-message", + "key": "GET /log-message", + "averageResponseTime": 32667.5, + "transactionsPerMinute": 0.5, + "impact": 2.875276331059301, + "p95": 38528, "sample": { - "@timestamp": "2020-06-29T06:48:28.944Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:39.370695Z" }, + "@timestamp": "2020-06-29T06:48:25.944Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:29.976822Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["24"], - "Content-Type": ["text/html; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:28 GMT"], - "Etag": ["W/\"18-MS3VbhH7auHMzO0fUuNF6v14N/M\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "24" + ], + "Content-Type": [ + "text/html; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:25 GMT" + ], + "Etag": [ + "W/\"18-MS3VbhH7auHMzO0fUuNF6v14N/M\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 500 }, @@ -384,27 +642,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413308944016 }, - "trace": { "id": "afabe4cb397616f5ec35a2f3da49ba62" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413305944023 + }, + "trace": { + "id": "cd2ad726ad164d701c5d3103cbab0c81" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 26788 }, - "id": "cc8c4261387507cf", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 38547 + }, + "id": "9e41667eb64dea55", "name": "GET /log-message", "result": "HTTP 5xx", "sampled": true, - "span_count": { "started": 0 }, + "span_count": { + "started": 0 + }, "type": "request" }, "url": { @@ -415,51 +698,89 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 38528, - "averageResponseTime": 32667.5, - "transactionsPerMinute": 0.5, - "impact": 2.875276331059301 + } }, { - "name": "GET /*", + "key": "GET /*", + "averageResponseTime": 3262.95, + "transactionsPerMinute": 5, + "impact": 2.8716452680799467, + "p95": 4472, "sample": { - "@timestamp": "2020-06-29T06:48:42.454Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.995202Z" }, + "@timestamp": "2020-06-29T06:48:25.064Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:27.005197Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "Wget" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["813"], - "Content-Type": ["text/html"], - "Date": ["Mon, 29 Jun 2020 06:48:42 GMT"], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "813" + ], + "Content-Type": [ + "text/html" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:25 GMT" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -479,7 +800,9 @@ "version": "8.0.0", "version_major": 8 }, - "parent": { "id": "5baa6c3bedc93f9d" }, + "parent": { + "id": "f673ceaf4583f0f2" + }, "process": { "args": [ "/usr/local/bin/node", @@ -490,27 +813,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413322454015 }, - "trace": { "id": "022b01256b291a4c417199d91ec8755f" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413305064023 + }, + "trace": { + "id": "30c12f4d8ef77a5be1b4464e5d2235bc" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 1737 }, - "id": "eff3e45e0d9529d9", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 3004 + }, + "id": "18a00dfdb919a978", "name": "GET /*", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 0 }, + "span_count": { + "started": 0 + }, "type": "request" }, "url": { @@ -521,59 +869,104 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, - "name": "Other", - "original": "workload/2.4.3" + "device": { + "name": "Other" + }, + "name": "Wget", + "original": "Wget" } - }, - "p95": 4472, - "averageResponseTime": 3262.95, - "transactionsPerMinute": 5, - "impact": 2.8716452680799467 + } }, { - "name": "GET /api/orders", + "key": "GET /api/orders", + "averageResponseTime": 7615.625, + "transactionsPerMinute": 2, + "impact": 2.6645791239678345, + "p95": 11616, "sample": { - "@timestamp": "2020-06-29T06:48:40.106Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.6" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.988104Z" }, + "@timestamp": "2020-06-29T06:48:28.782Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.8" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:29.983252Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { "Accept": [ - "text/plain, application/json, application/x-jackson-smile, application/cbor, application/*+json, */*" + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Connection": [ + "keep-alive" ], - "Connection": ["keep-alive"], - "Elastic-Apm-Traceparent": [ - "00-90bd7780b32cc51a7f4c200b1e0c170f-5ff346d602ce27b0-01" + "Host": [ + "opbeans-node:3000" ], - "Host": ["opbeans-node:3000"], - "Traceparent": ["00-90bd7780b32cc51a7f4c200b1e0c170f-5ff346d602ce27b0-01"], - "User-Agent": ["Java/11.0.7"] + "Referer": [ + "http://opbeans-node:3000/orders" + ], + "Traceparent": [ + "00-978b56807e0b7a27cbc41a0dfb665f47-3358a24e09e23561-01" + ], + "User-Agent": [ + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.6" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.8" + } }, "response": { "headers": { - "Connection": ["keep-alive"], - "Content-Length": ["2"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:40 GMT"], - "Etag": ["W/\"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w\""], - "X-Powered-By": ["Express"] + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "2" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:28 GMT" + ], + "Etag": [ + "W/\"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -593,7 +986,9 @@ "version": "8.0.0", "version_major": 8 }, - "parent": { "id": "5ff346d602ce27b0" }, + "parent": { + "id": "3358a24e09e23561" + }, "process": { "args": [ "/usr/local/bin/node", @@ -604,27 +999,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.6" }, - "timestamp": { "us": 1593413320106015 }, - "trace": { "id": "90bd7780b32cc51a7f4c200b1e0c170f" }, + "source": { + "ip": "172.18.0.8" + }, + "timestamp": { + "us": 1593413308782015 + }, + "trace": { + "id": "978b56807e0b7a27cbc41a0dfb665f47" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 7424 }, - "id": "f3dd00d12c594cba", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 7134 + }, + "id": "a6d8f3c5c98903e1", "name": "GET /api/orders", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 2 }, + "span_count": { + "started": 2 + }, "type": "request" }, "url": { @@ -635,60 +1055,96 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Spider" }, - "name": "Java", - "original": "Java/11.0.7", - "version": "0.7." + "device": { + "name": "Other" + }, + "name": "HeadlessChrome", + "original": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36", + "os": { + "name": "Linux" + }, + "version": "79.0.3945" } - }, - "p95": 11616, - "averageResponseTime": 7615.625, - "transactionsPerMinute": 2, - "impact": 2.6645791239678345 + } }, { - "name": "GET /api/products", + "key": "GET /api/products", + "averageResponseTime": 8585, + "transactionsPerMinute": 1.75, + "impact": 2.624924094061731, + "p95": 22112, "sample": { - "@timestamp": "2020-06-29T06:48:27.452Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.6" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:29.978463Z" }, + "@timestamp": "2020-06-29T06:48:21.475Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:26.996210Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Accept": [ - "text/plain, application/json, application/x-jackson-smile, application/cbor, application/*+json, */*" + "Connection": [ + "close" ], - "Connection": ["keep-alive"], - "Elastic-Apm-Traceparent": [ - "00-27b168a328e0fd442377de8eaa0bf582-2c86873dedb66c2c-01" + "Host": [ + "opbeans-node:3000" ], - "Host": ["opbeans-node:3000"], - "Traceparent": ["00-27b168a328e0fd442377de8eaa0bf582-2c86873dedb66c2c-01"], - "User-Agent": ["Java/11.0.7"] + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.6" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["keep-alive"], - "Content-Length": ["1023"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:27 GMT"], - "Etag": ["W/\"3ff-VyOxcDApb+a/lnjkm9FeTOGSDrs\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "1023" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:21 GMT" + ], + "Etag": [ + "W/\"3ff-VyOxcDApb+a/lnjkm9FeTOGSDrs\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -708,7 +1164,6 @@ "version": "8.0.0", "version_major": 8 }, - "parent": { "id": "2c86873dedb66c2c" }, "process": { "args": [ "/usr/local/bin/node", @@ -719,27 +1174,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.6" }, - "timestamp": { "us": 1593413307452013 }, - "trace": { "id": "27b168a328e0fd442377de8eaa0bf582" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413301475015 + }, + "trace": { + "id": "389b26b16949c7f783223de4f14b788c" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 4292 }, - "id": "141ecc2dfd55eeea", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 6775 + }, + "id": "d2d4088a0b104fb4", "name": "GET /api/products", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 2 }, + "span_count": { + "started": 2 + }, "type": "request" }, "url": { @@ -750,53 +1230,92 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Spider" }, - "name": "Java", - "original": "Java/11.0.7", - "version": "0.7." + "device": { + "name": "Other" + }, + "name": "Other", + "original": "workload/2.4.3" } - }, - "p95": 22112, - "averageResponseTime": 8585, - "transactionsPerMinute": 1.75, - "impact": 2.624924094061731 + } }, { - "name": "GET /api/products/:id", + "key": "GET /api/products/:id", + "averageResponseTime": 13516.5, + "transactionsPerMinute": 1, + "impact": 2.3368756900811305, + "p95": 37856, "sample": { - "@timestamp": "2020-06-29T06:48:24.977Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:27.004717Z" }, + "@timestamp": "2020-06-29T06:47:57.555Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:47:59.085077Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["231"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:24 GMT"], - "Etag": ["W/\"e7-kkuzj37GZDzXDh0CWqh5Gan0VO4\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "231" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:47:57 GMT" + ], + "Etag": [ + "W/\"e7-6JlJegaJ+ir0C8I8EmmOjms1dnc\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -822,87 +1341,152 @@ "/usr/local/lib/node_modules/pm2/lib/ProcessContainer.js", "ecosystem-workload.config.js" ], - "pid": 137, + "pid": 87, "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413304977014 }, - "trace": { "id": "b9b290bca14c99962fa9a1c509401630" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413277555176 + }, + "trace": { + "id": "8365e1763f19e4067b88521d4d9247a0" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 4482 }, - "id": "b8d8284ff1fc25d6", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 37709 + }, + "id": "be2722a418272f10", "name": "GET /api/products/:id", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "request" }, "url": { "domain": "opbeans-node", - "full": "http://opbeans-node:3000/api/products/3", - "original": "/api/products/3", - "path": "/api/products/3", + "full": "http://opbeans-node:3000/api/products/1", + "original": "/api/products/1", + "path": "/api/products/1", "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 37856, - "averageResponseTime": 13516.5, - "transactionsPerMinute": 1, - "impact": 2.3368756900811305 + } }, { - "name": "GET /api/types", + "key": "GET /api/types", + "averageResponseTime": 26992.5, + "transactionsPerMinute": 0.5, + "impact": 2.3330057413794503, + "p95": 45248, "sample": { - "@timestamp": "2020-06-29T06:48:26.443Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:29.977518Z" }, + "@timestamp": "2020-06-29T06:47:52.935Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:47:55.471071Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["112"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:26 GMT"], - "Etag": ["W/\"70-1z6hT7P1WHgBgS/BeUEVeHhOCQU\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "112" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:47:52 GMT" + ], + "Etag": [ + "W/\"70-1z6hT7P1WHgBgS/BeUEVeHhOCQU\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -928,31 +1512,56 @@ "/usr/local/lib/node_modules/pm2/lib/ProcessContainer.js", "ecosystem-workload.config.js" ], - "pid": 137, + "pid": 63, "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413306443014 }, - "trace": { "id": "be3f4eb50d253afc032c90eacaa85072" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413272935117 + }, + "trace": { + "id": "2946c536a33d163d0c984d00d1f3839a" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 8892 }, - "id": "ccce129bb8c6b125", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 45093 + }, + "id": "103482fda88b9400", "name": "GET /api/types", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 2 }, + "span_count": { + "started": 2 + }, "type": "request" }, "url": { @@ -963,55 +1572,101 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 45248, - "averageResponseTime": 26992.5, - "transactionsPerMinute": 0.5, - "impact": 2.3330057413794503 + } }, { - "name": "GET static file", + "key": "GET static file", + "averageResponseTime": 3492.9285714285716, + "transactionsPerMinute": 3.5, + "impact": 2.0901067389184496, + "p95": 11900, "sample": { - "@timestamp": "2020-06-29T06:48:40.953Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.992454Z" }, + "@timestamp": "2020-06-29T06:47:53.427Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:47:55.472070Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Accept-Ranges": ["bytes"], - "Cache-Control": ["public, max-age=0"], - "Connection": ["close"], - "Content-Length": ["15086"], - "Content-Type": ["image/x-icon"], - "Date": ["Mon, 29 Jun 2020 06:48:40 GMT"], - "Etag": ["W/\"3aee-1725aff14f0\""], - "Last-Modified": ["Thu, 28 May 2020 11:16:06 GMT"], - "X-Powered-By": ["Express"] + "Accept-Ranges": [ + "bytes" + ], + "Cache-Control": [ + "public, max-age=0" + ], + "Connection": [ + "close" + ], + "Content-Length": [ + "15086" + ], + "Content-Type": [ + "image/x-icon" + ], + "Date": [ + "Mon, 29 Jun 2020 06:47:53 GMT" + ], + "Etag": [ + "W/\"3aee-1725aff14f0\"" + ], + "Last-Modified": [ + "Thu, 28 May 2020 11:16:06 GMT" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -1031,30 +1686,53 @@ "/usr/local/lib/node_modules/pm2/lib/ProcessContainer.js", "ecosystem-workload.config.js" ], - "pid": 137, + "pid": 63, "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413320953016 }, - "trace": { "id": "292393440bbe04385f3c2e3715ac35fe" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413273427016 + }, + "trace": { + "id": "ec8a804fedf28fcf81d5682d69a16970" + }, "transaction": { - "duration": { "us": 1671 }, - "id": "d1d964ca1865dce3", + "duration": { + "us": 4934 + }, + "id": "ab90a62901b770e6", "name": "GET static file", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 0 }, + "span_count": { + "started": 0 + }, "type": "request" }, "url": { @@ -1066,56 +1744,86 @@ "scheme": "http" }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 11900, - "averageResponseTime": 3492.9285714285716, - "transactionsPerMinute": 3.5, - "impact": 2.0901067389184496 + } }, { - "name": "GET /api/products/top", + "key": "GET /api/products/top", + "averageResponseTime": 22958.5, + "transactionsPerMinute": 0.5, + "impact": 1.9475397398343375, + "p95": 33216, "sample": { - "@timestamp": "2020-06-29T06:48:18.211Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.8" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:21.007197Z" }, + "@timestamp": "2020-06-29T06:48:01.200Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:02.734903Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Accept": ["*/*"], - "Accept-Encoding": ["gzip, deflate"], - "Connection": ["keep-alive"], - "Host": ["opbeans-node:3000"], - "Referer": ["http://opbeans-node:3000/dashboard"], - "Traceparent": ["00-4879105b2de793ca54ce7299aff0f5ce-0d67fab9c9dec84d-01"], + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], "User-Agent": [ - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36" + "workload/2.4.3" ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.8" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["keep-alive"], - "Content-Length": ["2"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:18 GMT"], - "Etag": ["W/\"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "2" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:01 GMT" + ], + "Etag": [ + "W/\"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -1135,38 +1843,62 @@ "version": "8.0.0", "version_major": 8 }, - "parent": { "id": "0d67fab9c9dec84d" }, "process": { "args": [ "/usr/local/bin/node", "/usr/local/lib/node_modules/pm2/lib/ProcessContainer.js", "ecosystem-workload.config.js" ], - "pid": 137, + "pid": 115, "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.8" }, - "timestamp": { "us": 1593413298211013 }, - "trace": { "id": "4879105b2de793ca54ce7299aff0f5ce" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413281200133 + }, + "trace": { + "id": "195f32efeb6f91e2f71b6bc8bb74ae3a" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 12820 }, - "id": "b15b12c837ab8b89", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 33097 + }, + "id": "22e72956dfc8967a", "name": "GET /api/products/top", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "request" }, "url": { @@ -1177,56 +1909,103 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, - "name": "HeadlessChrome", - "original": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36", - "os": { "name": "Linux" }, - "version": "79.0.3945" + "device": { + "name": "Other" + }, + "name": "Other", + "original": "workload/2.4.3" } - }, - "p95": 33216, - "averageResponseTime": 22958.5, - "transactionsPerMinute": 0.5, - "impact": 1.9475397398343375 + } }, { - "name": "GET /api/stats", + "key": "GET /api/stats", + "averageResponseTime": 7105.333333333333, + "transactionsPerMinute": 1.5, + "impact": 1.7905918202662048, + "p95": 15136, "sample": { - "@timestamp": "2020-06-29T06:48:39.451Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.984824Z" }, + "@timestamp": "2020-06-29T06:48:21.150Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.8" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:26.993832Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Accept": [ + "*/*" + ], + "Accept-Encoding": [ + "gzip, deflate" + ], + "Connection": [ + "keep-alive" + ], + "Host": [ + "opbeans-node:3000" + ], + "If-None-Match": [ + "W/\"5c-6I+bqIiLxvkWuwBUnTxhBoK4lBk\"" + ], + "Referer": [ + "http://opbeans-node:3000/dashboard" + ], + "Traceparent": [ + "00-ee0ce8b38b8d5945829fc1c9432538bf-39d52cd5f528d363-01" + ], + "User-Agent": [ + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.8" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["92"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:39 GMT"], - "Etag": ["W/\"5c-6I+bqIiLxvkWuwBUnTxhBoK4lBk\""], - "X-Powered-By": ["Express"] + "Connection": [ + "keep-alive" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:21 GMT" + ], + "Etag": [ + "W/\"5c-6I+bqIiLxvkWuwBUnTxhBoK4lBk\"" + ], + "X-Powered-By": [ + "Express" + ] }, - "status_code": 200 + "status_code": 304 }, "version": "1.1" }, @@ -1244,6 +2023,9 @@ "version": "8.0.0", "version_major": 8 }, + "parent": { + "id": "39d52cd5f528d363" + }, "process": { "args": [ "/usr/local/bin/node", @@ -1254,27 +2036,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413319451016 }, - "trace": { "id": "a05787cb03a0af0863fab5e05de942f1" }, + "source": { + "ip": "172.18.0.8" + }, + "timestamp": { + "us": 1593413301150014 + }, + "trace": { + "id": "ee0ce8b38b8d5945829fc1c9432538bf" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 5050 }, - "id": "a7e004eba8f021ce", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 7273 + }, + "id": "05d5b62182c59a54", "name": "GET /api/stats", - "result": "HTTP 2xx", + "result": "HTTP 3xx", "sampled": true, - "span_count": { "started": 4 }, + "span_count": { + "started": 4 + }, "type": "request" }, "url": { @@ -1285,52 +2092,96 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, - "name": "Other", - "original": "workload/2.4.3" + "device": { + "name": "Other" + }, + "name": "HeadlessChrome", + "original": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36", + "os": { + "name": "Linux" + }, + "version": "79.0.3945" } - }, - "p95": 15136, - "averageResponseTime": 7105.333333333333, - "transactionsPerMinute": 1.5, - "impact": 1.7905918202662048 + } }, { - "name": "GET /log-error", + "key": "GET /log-error", + "averageResponseTime": 35846, + "transactionsPerMinute": 0.25, + "impact": 1.466376117925459, + "p95": 35840, "sample": { "@timestamp": "2020-06-29T06:48:07.467Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:18.533253Z" }, + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:18.533253Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["24"], - "Content-Type": ["text/html; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:07 GMT"], - "Etag": ["W/\"18-MS3VbhH7auHMzO0fUuNF6v14N/M\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "24" + ], + "Content-Type": [ + "text/html; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:07 GMT" + ], + "Etag": [ + "W/\"18-MS3VbhH7auHMzO0fUuNF6v14N/M\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 500 }, @@ -1360,27 +2211,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413287467017 }, - "trace": { "id": "d518b2c4d72cd2aaf1e39bad7ebcbdbb" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413287467017 + }, + "trace": { + "id": "d518b2c4d72cd2aaf1e39bad7ebcbdbb" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 35846 }, + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 35846 + }, "id": "c7a30c1b076907ec", "name": "GET /log-error", "result": "HTTP 5xx", "sampled": true, - "span_count": { "started": 0 }, + "span_count": { + "started": 0 + }, "type": "request" }, "url": { @@ -1391,56 +2267,104 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 35840, - "averageResponseTime": 35846, - "transactionsPerMinute": 0.25, - "impact": 1.466376117925459 + } }, { - "name": "POST /api", + "key": "POST /api", + "averageResponseTime": 20011, + "transactionsPerMinute": 0.25, + "impact": 0.7098250353192541, + "p95": 19968, "sample": { "@timestamp": "2020-06-29T06:48:25.478Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:27.005671Z" }, + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:27.005671Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { - "body": { "original": "[REDACTED]" }, + "body": { + "original": "[REDACTED]" + }, "headers": { - "Accept": ["application/json"], - "Connection": ["close"], - "Content-Length": ["129"], - "Content-Type": ["application/json"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Accept": [ + "application/json" + ], + "Connection": [ + "close" + ], + "Content-Length": [ + "129" + ], + "Content-Type": [ + "application/json" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "post", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Allow": ["GET"], - "Connection": ["close"], - "Content-Type": ["application/json;charset=UTF-8"], - "Date": ["Mon, 29 Jun 2020 06:48:25 GMT"], - "Transfer-Encoding": ["chunked"], - "X-Powered-By": ["Express"] + "Allow": [ + "GET" + ], + "Connection": [ + "close" + ], + "Content-Type": [ + "application/json;charset=UTF-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:25 GMT" + ], + "Transfer-Encoding": [ + "chunked" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 405 }, @@ -1470,27 +2394,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413305478010 }, - "trace": { "id": "4bd9027dd1e355ec742970e2d6333124" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413305478010 + }, + "trace": { + "id": "4bd9027dd1e355ec742970e2d6333124" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 20011 }, + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 20011 + }, "id": "94104435cf151478", "name": "POST /api", "result": "HTTP 4xx", "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "request" }, "url": { @@ -1501,52 +2450,92 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 19968, - "averageResponseTime": 20011, - "transactionsPerMinute": 0.25, - "impact": 0.7098250353192541 + } }, { - "name": "GET /api/types/:id", + "key": "GET /api/types/:id", + "averageResponseTime": 8181, + "transactionsPerMinute": 0.5, + "impact": 0.5354862351657939, + "p95": 10080, "sample": { - "@timestamp": "2020-06-29T06:48:12.972Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:18.543436Z" }, + "@timestamp": "2020-06-29T06:47:53.928Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:47:55.472718Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["205"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:12 GMT"], - "Etag": ["W/\"cd-pFMi1QOVY6YqWe+nwcbZVviCths\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "205" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:47:53 GMT" + ], + "Etag": [ + "W/\"cd-pFMi1QOVY6YqWe+nwcbZVviCths\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -1572,31 +2561,56 @@ "/usr/local/lib/node_modules/pm2/lib/ProcessContainer.js", "ecosystem-workload.config.js" ], - "pid": 137, + "pid": 63, "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413292972011 }, - "trace": { "id": "aea65cef5f902dda5d8e38f9fb38864d" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413273928016 + }, + "trace": { + "id": "0becaafb422bfeb69e047bf7153aa469" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 6300 }, - "id": "a5bdbe43ac05fae2", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 10062 + }, + "id": "0cee4574091bda3b", "name": "GET /api/types/:id", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 2 }, + "span_count": { + "started": 2 + }, "type": "request" }, "url": { @@ -1607,50 +2621,86 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 10080, - "averageResponseTime": 8181, - "transactionsPerMinute": 0.5, - "impact": 0.5354862351657939 + } }, { - "name": "GET /api/orders/:id", + "key": "GET /api/orders/:id", + "averageResponseTime": 4749.666666666667, + "transactionsPerMinute": 0.75, + "impact": 0.43453312891085794, + "p95": 7184, "sample": { "@timestamp": "2020-06-29T06:48:35.951Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:39.484133Z" }, + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:39.484133Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["0"], - "Date": ["Mon, 29 Jun 2020 06:48:35 GMT"], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "0" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:35 GMT" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 404 }, @@ -1680,27 +2730,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413315951017 }, - "trace": { "id": "95979caa80e6622cbbb2d308800c3016" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413315951017 + }, + "trace": { + "id": "95979caa80e6622cbbb2d308800c3016" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 3210 }, + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 3210 + }, "id": "30344988dace0b43", "name": "GET /api/orders/:id", "result": "HTTP 4xx", "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "request" }, "url": { @@ -1711,52 +2786,92 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 7184, - "averageResponseTime": 4749.666666666667, - "transactionsPerMinute": 0.75, - "impact": 0.43453312891085794 + } }, { - "name": "GET /api/products/:id/customers", + "key": "GET /api/products/:id/customers", + "averageResponseTime": 4757, + "transactionsPerMinute": 0.5, + "impact": 0.20830834986820673, + "p95": 5616, "sample": { - "@timestamp": "2020-06-29T06:48:41.956Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.994692Z" }, + "@timestamp": "2020-06-29T06:48:22.977Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:27.000765Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["2"], - "Content-Type": ["application/json; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:41 GMT"], - "Etag": ["W/\"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w\""], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "2" + ], + "Content-Type": [ + "application/json; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:22 GMT" + ], + "Etag": [ + "W/\"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w\"" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 200 }, @@ -1786,84 +2901,151 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413321956016 }, - "trace": { "id": "f735ac5fca8f83eebc748f4a2e009e61" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413302977008 + }, + "trace": { + "id": "da8f22fe652ccb6680b3029ab6efd284" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 3896 }, - "id": "b24ce95c855f83a4", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 5618 + }, + "id": "bc51c1523afaf57a", "name": "GET /api/products/:id/customers", "result": "HTTP 2xx", "sampled": true, - "span_count": { "started": 1 }, + "span_count": { + "started": 1 + }, "type": "request" }, "url": { "domain": "opbeans-node", - "full": "http://opbeans-node:3000/api/products/5/customers", - "original": "/api/products/5/customers", - "path": "/api/products/5/customers", + "full": "http://opbeans-node:3000/api/products/3/customers", + "original": "/api/products/3/customers", + "path": "/api/products/3/customers", "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 5616, - "averageResponseTime": 4757, - "transactionsPerMinute": 0.5, - "impact": 0.20830834986820673 + } }, { - "name": "GET /throw-error", + "key": "GET /throw-error", + "averageResponseTime": 2577, + "transactionsPerMinute": 0.5, + "impact": 0, + "p95": 3224, "sample": { - "@timestamp": "2020-06-29T06:48:42.954Z", - "agent": { "name": "nodejs", "version": "3.6.1" }, - "client": { "ip": "172.18.0.7" }, - "container": { "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "ecs": { "version": "1.5.0" }, - "event": { "ingested": "2020-06-29T06:48:43.996435Z" }, + "@timestamp": "2020-06-29T06:48:19.975Z", + "agent": { + "name": "nodejs", + "version": "3.6.1" + }, + "client": { + "ip": "172.18.0.7" + }, + "container": { + "id": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "ecs": { + "version": "1.5.0" + }, + "event": { + "ingested": "2020-06-29T06:48:21.012520Z" + }, "host": { "architecture": "x64", "hostname": "41712ded148f", "ip": "172.18.0.7", "name": "41712ded148f", - "os": { "platform": "linux" } + "os": { + "platform": "linux" + } }, "http": { "request": { "headers": { - "Connection": ["close"], - "Host": ["opbeans-node:3000"], - "User-Agent": ["workload/2.4.3"] + "Connection": [ + "close" + ], + "Host": [ + "opbeans-node:3000" + ], + "User-Agent": [ + "workload/2.4.3" + ] }, "method": "get", - "socket": { "encrypted": false, "remote_address": "::ffff:172.18.0.7" } + "socket": { + "encrypted": false, + "remote_address": "::ffff:172.18.0.7" + } }, "response": { "headers": { - "Connection": ["close"], - "Content-Length": ["148"], - "Content-Security-Policy": ["default-src 'none'"], - "Content-Type": ["text/html; charset=utf-8"], - "Date": ["Mon, 29 Jun 2020 06:48:42 GMT"], - "X-Content-Type-Options": ["nosniff"], - "X-Powered-By": ["Express"] + "Connection": [ + "close" + ], + "Content-Length": [ + "148" + ], + "Content-Security-Policy": [ + "default-src 'none'" + ], + "Content-Type": [ + "text/html; charset=utf-8" + ], + "Date": [ + "Mon, 29 Jun 2020 06:48:19 GMT" + ], + "X-Content-Type-Options": [ + "nosniff" + ], + "X-Powered-By": [ + "Express" + ] }, "status_code": 500 }, @@ -1893,27 +3075,52 @@ "ppid": 1, "title": "node /app/server.js" }, - "processor": { "event": "transaction", "name": "transaction" }, + "processor": { + "event": "transaction", + "name": "transaction" + }, "service": { "environment": "production", - "framework": { "name": "express", "version": "4.17.1" }, - "language": { "name": "javascript" }, + "framework": { + "name": "express", + "version": "4.17.1" + }, + "language": { + "name": "javascript" + }, "name": "opbeans-node", - "node": { "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" }, - "runtime": { "name": "node", "version": "12.18.1" }, + "node": { + "name": "41712ded148f30ee09a13421780eec4304bf5049b82a0d8dbc877893be6799e4" + }, + "runtime": { + "name": "node", + "version": "12.18.1" + }, "version": "1.0.0" }, - "source": { "ip": "172.18.0.7" }, - "timestamp": { "us": 1593413322954016 }, - "trace": { "id": "9d5aee7443a43db9820f622a10dfac6e" }, + "source": { + "ip": "172.18.0.7" + }, + "timestamp": { + "us": 1593413299975019 + }, + "trace": { + "id": "106f3a55b0b0ea327d1bbe4be66c3bcc" + }, "transaction": { - "custom": { "shoppingBasketCount": 42 }, - "duration": { "us": 1928 }, - "id": "8e6fc8c3f99e8fc9", + "custom": { + "shoppingBasketCount": 42 + }, + "duration": { + "us": 3226 + }, + "id": "247b9141552a9e73", "name": "GET /throw-error", "result": "HTTP 5xx", "sampled": true, - "span_count": { "started": 0 }, + "span_count": { + "started": 0 + }, "type": "request" }, "url": { @@ -1924,19 +3131,21 @@ "port": 3000, "scheme": "http" }, - "user": { "email": "kimchy@elastic.co", "id": "42", "name": "kimchy" }, + "user": { + "email": "kimchy@elastic.co", + "id": "42", + "name": "kimchy" + }, "user_agent": { - "device": { "name": "Other" }, + "device": { + "name": "Other" + }, "name": "Other", "original": "workload/2.4.3" } - }, - "p95": 3224, - "averageResponseTime": 2577, - "transactionsPerMinute": 0.5, - "impact": 0 + } } ], "isAggregationAccurate": true, - "bucketSize": 100 -} + "bucketSize": 1000 +} \ No newline at end of file diff --git a/x-pack/test/apm_api_integration/basic/tests/transaction_groups/top_transaction_groups.ts b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/top_transaction_groups.ts index 43b2ad5414c7a..94559a3e4aa54 100644 --- a/x-pack/test/apm_api_integration/basic/tests/transaction_groups/top_transaction_groups.ts +++ b/x-pack/test/apm_api_integration/basic/tests/transaction_groups/top_transaction_groups.ts @@ -4,9 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ import expect from '@kbn/expect'; +import { sortBy } from 'lodash'; import { FtrProviderContext } from '../../../../common/ftr_provider_context'; import expectedTransactionGroups from './expectation/top_transaction_groups.json'; +function sortTransactionGroups(items: any[]) { + return sortBy(items, 'impact'); +} + +function omitSampleFromTransactionGroups(items: any[]) { + return sortTransactionGroups(items).map(({ sample, ...item }) => ({ ...item })); +} + export default function ApiTest({ getService }: FtrProviderContext) { const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); @@ -48,15 +57,19 @@ export default function ApiTest({ getService }: FtrProviderContext) { }); it('returns the correct buckets (when ignoring samples)', async () => { - function omitSample(items: any[]) { - return items.map(({ sample, ...item }) => ({ ...item })); - } - - expect(omitSample(response.body.items)).to.eql(omitSample(expectedTransactionGroups.items)); + expect(omitSampleFromTransactionGroups(response.body.items)).to.eql( + omitSampleFromTransactionGroups(expectedTransactionGroups.items) + ); }); it('returns the correct buckets and samples', async () => { - expect(response.body.items).to.eql(expectedTransactionGroups.items); + // sample should provide enough information to deeplink to a transaction detail page + response.body.items.forEach((item: any) => { + expect(item.sample.trace.id).to.be.an('string'); + expect(item.sample.transaction.id).to.be.an('string'); + expect(item.sample.service.name).to.be('opbeans-node'); + expect(item.sample.transaction.name).to.be(item.key); + }); }); }); }); diff --git a/x-pack/test/functional/apps/dashboard_mode/dashboard_empty_screen.js b/x-pack/test/functional/apps/dashboard_mode/dashboard_empty_screen.js index c8a8f9653c11b..62e07a08d1762 100644 --- a/x-pack/test/functional/apps/dashboard_mode/dashboard_empty_screen.js +++ b/x-pack/test/functional/apps/dashboard_mode/dashboard_empty_screen.js @@ -98,5 +98,15 @@ export default function ({ getPageObjects, getService }) { const titles = await PageObjects.dashboard.getPanelTitles(); expect(titles.indexOf(newTitle)).to.not.be(-1); }); + + it('loses originatingApp connection after save as when redirectToOrigin is false', async () => { + const newTitle = 'wowee, my title just got cooler again'; + await PageObjects.dashboard.waitForRenderComplete(); + await dashboardPanelActions.openContextMenu(); + await dashboardPanelActions.clickEdit(); + await PageObjects.lens.save(newTitle, true, false); + await PageObjects.lens.notLinkedToOriginatingApp(); + await PageObjects.common.navigateToApp('dashboard'); + }); }); } diff --git a/x-pack/test/functional/apps/graph/graph.ts b/x-pack/test/functional/apps/graph/graph.ts index 803e5e8f80d70..c2500dca78444 100644 --- a/x-pack/test/functional/apps/graph/graph.ts +++ b/x-pack/test/functional/apps/graph/graph.ts @@ -13,8 +13,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const browser = getService('browser'); - // FLAKY: https://github.com/elastic/kibana/issues/53749 - describe.skip('graph', function () { + describe('graph', function () { before(async () => { await browser.setWindowSize(1600, 1000); log.debug('load graph/secrepo data'); @@ -132,14 +131,17 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await buildGraph(); const { edges } = await PageObjects.graph.getGraphObjects(); - const blogAdminBlogEdge = edges.find( + await PageObjects.graph.isolateEdge('test', '/test/wp-admin/'); + + await PageObjects.graph.stopLayout(); + await PageObjects.common.sleep(1000); + const testTestWpAdminBlogEdge = edges.find( ({ sourceNode, targetNode }) => - sourceNode.label === '/blog/wp-admin/' && targetNode.label === 'blog' + targetNode.label === '/test/wp-admin/' && sourceNode.label === 'test' )!; - - await PageObjects.graph.isolateEdge(blogAdminBlogEdge); - - await PageObjects.graph.clickEdge(blogAdminBlogEdge); + await testTestWpAdminBlogEdge.element.click(); + await PageObjects.common.sleep(1000); + await PageObjects.graph.startLayout(); const vennTerm1 = await PageObjects.graph.getVennTerm1(); log.debug('vennTerm1 = ' + vennTerm1); @@ -156,11 +158,11 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { const smallVennTerm2 = await PageObjects.graph.getSmallVennTerm2(); log.debug('smallVennTerm2 = ' + smallVennTerm2); - expect(vennTerm1).to.be('/blog/wp-admin/'); - expect(vennTerm2).to.be('blog'); - expect(smallVennTerm1).to.be('5'); - expect(smallVennTerm12).to.be(' (5) '); - expect(smallVennTerm2).to.be('8'); + expect(vennTerm1).to.be('/test/wp-admin/'); + expect(vennTerm2).to.be('test'); + expect(smallVennTerm1).to.be('4'); + expect(smallVennTerm12).to.be(' (4) '); + expect(smallVennTerm2).to.be('4'); }); it('should delete graph', async function () { diff --git a/x-pack/test/functional/apps/infra/feature_controls/infrastructure_security.ts b/x-pack/test/functional/apps/infra/feature_controls/infrastructure_security.ts index 971826112a3e2..3c471516e9c66 100644 --- a/x-pack/test/functional/apps/infra/feature_controls/infrastructure_security.ts +++ b/x-pack/test/functional/apps/infra/feature_controls/infrastructure_security.ts @@ -423,19 +423,19 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { expect(navLinks).to.not.contain(['Metrics']); }); - it(`metrics app is inaccessible and Application Not Found message is rendered`, async () => { - await PageObjects.common.navigateToApp('infraOps'); - await testSubjects.existOrFail('~appNotFoundPageContent'); - await PageObjects.common.navigateToUrlWithBrowserHistory( - 'infraOps', - '/inventory', - undefined, - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } + it(`metrics app is inaccessible and returns a 404`, async () => { + await PageObjects.common.navigateToActualUrl('infraOps', '', { + ensureCurrentUrl: false, + shouldLoginIfPrompted: false, + }); + const messageText = await PageObjects.common.getBodyText(); + expect(messageText).to.eql( + JSON.stringify({ + statusCode: 404, + error: 'Not Found', + message: 'Not Found', + }) ); - await testSubjects.existOrFail('~appNotFoundPageContent'); }); }); }); diff --git a/x-pack/test/functional/apps/infra/feature_controls/infrastructure_spaces.ts b/x-pack/test/functional/apps/infra/feature_controls/infrastructure_spaces.ts index 211a9ce718b56..1bf8ded69016b 100644 --- a/x-pack/test/functional/apps/infra/feature_controls/infrastructure_spaces.ts +++ b/x-pack/test/functional/apps/infra/feature_controls/infrastructure_spaces.ts @@ -79,21 +79,19 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`metrics app is inaccessible and Application Not Found message is rendered`, async () => { - await PageObjects.common.navigateToApp('infraOps', { + await PageObjects.common.navigateToActualUrl('infraOps', '', { + ensureCurrentUrl: false, + shouldLoginIfPrompted: false, basePath: '/s/custom_space', }); - await testSubjects.existOrFail('~appNotFoundPageContent'); - await PageObjects.common.navigateToUrlWithBrowserHistory( - 'infraOps', - '/inventory', - undefined, - { - basePath: '/s/custom_space', - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } + const messageText = await PageObjects.common.getBodyText(); + expect(messageText).to.eql( + JSON.stringify({ + statusCode: 404, + error: 'Not Found', + message: 'Not Found', + }) ); - await testSubjects.existOrFail('~appNotFoundPageContent'); }); }); diff --git a/x-pack/test/functional/apps/infra/feature_controls/logs_security.ts b/x-pack/test/functional/apps/infra/feature_controls/logs_security.ts index c7d94f86ea420..64154ff6cf3f7 100644 --- a/x-pack/test/functional/apps/infra/feature_controls/logs_security.ts +++ b/x-pack/test/functional/apps/infra/feature_controls/logs_security.ts @@ -187,19 +187,19 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { expect(navLinks).to.not.contain('Logs'); }); - it(`logs app is inaccessible and Application Not Found message is rendered`, async () => { - await PageObjects.common.navigateToApp('infraLogs'); - await testSubjects.existOrFail('~appNotFoundPageContent'); - await PageObjects.common.navigateToUrlWithBrowserHistory( - 'infraLogs', - '/stream', - undefined, - { - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } + it(`logs app is inaccessible and returns a 404`, async () => { + await PageObjects.common.navigateToActualUrl('infraLogs', '', { + ensureCurrentUrl: false, + shouldLoginIfPrompted: false, + }); + const messageText = await PageObjects.common.getBodyText(); + expect(messageText).to.eql( + JSON.stringify({ + statusCode: 404, + error: 'Not Found', + message: 'Not Found', + }) ); - await testSubjects.existOrFail('~appNotFoundPageContent'); }); }); }); diff --git a/x-pack/test/functional/apps/infra/feature_controls/logs_spaces.ts b/x-pack/test/functional/apps/infra/feature_controls/logs_spaces.ts index 4d54539a4d09e..ea08307ccedd3 100644 --- a/x-pack/test/functional/apps/infra/feature_controls/logs_spaces.ts +++ b/x-pack/test/functional/apps/infra/feature_controls/logs_spaces.ts @@ -80,21 +80,19 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`logs app is inaccessible and Application Not Found message is rendered`, async () => { - await PageObjects.common.navigateToApp('infraLogs', { + await PageObjects.common.navigateToActualUrl('infraLogs', '', { + ensureCurrentUrl: false, + shouldLoginIfPrompted: false, basePath: '/s/custom_space', }); - await testSubjects.existOrFail('~appNotFoundPageContent'); - await PageObjects.common.navigateToUrlWithBrowserHistory( - 'infraLogs', - '/stream', - undefined, - { - basePath: '/s/custom_space', - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - } + const messageText = await PageObjects.common.getBodyText(); + expect(messageText).to.eql( + JSON.stringify({ + statusCode: 404, + error: 'Not Found', + message: 'Not Found', + }) ); - await testSubjects.existOrFail('~appNotFoundPageContent'); }); }); }); diff --git a/x-pack/test/functional/apps/maps/index.js b/x-pack/test/functional/apps/maps/index.js index d0735aecda78b..4bbe38367d0a2 100644 --- a/x-pack/test/functional/apps/maps/index.js +++ b/x-pack/test/functional/apps/maps/index.js @@ -35,6 +35,7 @@ export default function ({ loadTestFile, getService }) { loadTestFile(require.resolve('./saved_object_management')); loadTestFile(require.resolve('./sample_data')); loadTestFile(require.resolve('./auto_fit_to_bounds')); + loadTestFile(require.resolve('./layer_visibility')); loadTestFile(require.resolve('./feature_controls/maps_security')); loadTestFile(require.resolve('./feature_controls/maps_spaces')); loadTestFile(require.resolve('./full_screen_mode')); diff --git a/x-pack/test/functional/apps/maps/layer_visibility.js b/x-pack/test/functional/apps/maps/layer_visibility.js new file mode 100644 index 0000000000000..22cff6de416c1 --- /dev/null +++ b/x-pack/test/functional/apps/maps/layer_visibility.js @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; + +export default function ({ getPageObjects, getService }) { + const PageObjects = getPageObjects(['maps']); + const inspector = getService('inspector'); + + describe('layer visibility', () => { + before(async () => { + await PageObjects.maps.loadSavedMap('document example hidden'); + }); + + afterEach(async () => { + await inspector.close(); + }); + + it('should not make any requests when layer is hidden', async () => { + const noRequests = await PageObjects.maps.doesInspectorHaveRequests(); + expect(noRequests).to.equal(true); + }); + + it('should fetch layer data when layer is made visible', async () => { + await PageObjects.maps.toggleLayerVisibility('logstash'); + const hits = await PageObjects.maps.getHits(); + expect(hits).to.equal('6'); + }); + }); +} diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts index 2c6edeba2129f..4566e9aed61b4 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts @@ -115,7 +115,13 @@ export default function ({ getService }: FtrProviderContext) { await ml.dataFrameAnalyticsCreation.setJobDescription(testData.jobDescription); }); - it('inputs the destination index', async () => { + it('should default the set destination index to job id switch to true', async () => { + await ml.dataFrameAnalyticsCreation.assertDestIndexSameAsIdSwitchExists(); + await ml.dataFrameAnalyticsCreation.assertDestIndexSameAsIdCheckState(true); + }); + + it('should input the destination index', async () => { + await ml.dataFrameAnalyticsCreation.setDestIndexSameAsIdCheckState(false); await ml.dataFrameAnalyticsCreation.assertDestIndexInputExists(); await ml.dataFrameAnalyticsCreation.setDestIndex(testData.destinationIndex); }); diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts index 4ae93296f9be0..0320354b99ff0 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts @@ -133,7 +133,13 @@ export default function ({ getService }: FtrProviderContext) { await ml.dataFrameAnalyticsCreation.setJobDescription(testData.jobDescription); }); - it('inputs the destination index', async () => { + it('should default the set destination index to job id switch to true', async () => { + await ml.dataFrameAnalyticsCreation.assertDestIndexSameAsIdSwitchExists(); + await ml.dataFrameAnalyticsCreation.assertDestIndexSameAsIdCheckState(true); + }); + + it('should input the destination index', async () => { + await ml.dataFrameAnalyticsCreation.setDestIndexSameAsIdCheckState(false); await ml.dataFrameAnalyticsCreation.assertDestIndexInputExists(); await ml.dataFrameAnalyticsCreation.setDestIndex(testData.destinationIndex); }); diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/regression_creation.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/regression_creation.ts index 03117d4cc419d..1aa505e26e1e9 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/regression_creation.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/regression_creation.ts @@ -115,7 +115,13 @@ export default function ({ getService }: FtrProviderContext) { await ml.dataFrameAnalyticsCreation.setJobDescription(testData.jobDescription); }); - it('inputs the destination index', async () => { + it('should default the set destination index to job id switch to true', async () => { + await ml.dataFrameAnalyticsCreation.assertDestIndexSameAsIdSwitchExists(); + await ml.dataFrameAnalyticsCreation.assertDestIndexSameAsIdCheckState(true); + }); + + it('should input the destination index', async () => { + await ml.dataFrameAnalyticsCreation.setDestIndexSameAsIdCheckState(false); await ml.dataFrameAnalyticsCreation.assertDestIndexInputExists(); await ml.dataFrameAnalyticsCreation.setDestIndex(testData.destinationIndex); }); diff --git a/x-pack/test/functional/apps/monitoring/time_filter.js b/x-pack/test/functional/apps/monitoring/time_filter.js index d7ffdb4a7900d..11557d995218e 100644 --- a/x-pack/test/functional/apps/monitoring/time_filter.js +++ b/x-pack/test/functional/apps/monitoring/time_filter.js @@ -7,6 +7,8 @@ import expect from '@kbn/expect'; import { getLifecycleMethods } from './_get_lifecycle_methods'; +const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + export default function ({ getService, getPageObjects }) { const PageObjects = getPageObjects(['header', 'timePicker']); const testSubjects = getService('testSubjects'); @@ -35,6 +37,11 @@ export default function ({ getService, getPageObjects }) { }); it('should send another request when changing the time picker', async () => { + /** + * TODO: The value should either be removed or lowered after: + * https://github.com/elastic/kibana/issues/72997 is resolved + */ + await delay(3000); await PageObjects.timePicker.setAbsoluteRange( 'Aug 15, 2016 @ 21:00:00.000', 'Aug 16, 2016 @ 00:00:00.000' diff --git a/x-pack/test/functional/apps/security/doc_level_security_roles.js b/x-pack/test/functional/apps/security/doc_level_security_roles.js index d8a3e40ccc010..72f463be48fd5 100644 --- a/x-pack/test/functional/apps/security/doc_level_security_roles.js +++ b/x-pack/test/functional/apps/security/doc_level_security_roles.js @@ -15,8 +15,7 @@ export default function ({ getService, getPageObjects }) { const screenshot = getService('screenshots'); const PageObjects = getPageObjects(['security', 'common', 'header', 'discover', 'settings']); - // Skipped as failing on ES Promotion: https://github.com/elastic/kibana/issues/70818 - describe.skip('dls', function () { + describe('dls', function () { before('initialize tests', async () => { await esArchiver.load('empty_kibana'); await esArchiver.loadIfNeeded('security/dlstest'); diff --git a/x-pack/test/functional/apps/security/field_level_security.js b/x-pack/test/functional/apps/security/field_level_security.js index 20b13ad935f93..7b22d72885c9d 100644 --- a/x-pack/test/functional/apps/security/field_level_security.js +++ b/x-pack/test/functional/apps/security/field_level_security.js @@ -14,8 +14,7 @@ export default function ({ getService, getPageObjects }) { const log = getService('log'); const PageObjects = getPageObjects(['security', 'settings', 'common', 'discover', 'header']); - // Skipped as it was failing on ES Promotion: https://github.com/elastic/kibana/issues/70880 - describe.skip('field_level_security', () => { + describe('field_level_security', () => { before('initialize tests', async () => { await esArchiver.loadIfNeeded('security/flstest/data'); //( data) await esArchiver.load('security/flstest/kibana'); //(savedobject) diff --git a/x-pack/test/functional/apps/upgrade_assistant/upgrade_assistant.ts b/x-pack/test/functional/apps/upgrade_assistant/upgrade_assistant.ts index 85ad98727cea5..57b8fb23613be 100644 --- a/x-pack/test/functional/apps/upgrade_assistant/upgrade_assistant.ts +++ b/x-pack/test/functional/apps/upgrade_assistant/upgrade_assistant.ts @@ -11,14 +11,22 @@ export default function upgradeAssistantFunctionalTests({ getPageObjects, }: FtrProviderContext) { const esArchiver = getService('esArchiver'); - const PageObjects = getPageObjects(['upgradeAssistant']); + const PageObjects = getPageObjects(['upgradeAssistant', 'common']); + const security = getService('security'); + const log = getService('log'); describe('Upgrade Checkup', function () { this.tags('includeFirefox'); - before(async () => await esArchiver.load('empty_kibana')); + + before(async () => { + await esArchiver.load('empty_kibana'); + await security.testUser.setRoles(['global_upgrade_assistant_role']); + }); + after(async () => { await PageObjects.upgradeAssistant.expectTelemetryHasFinish(); await esArchiver.unload('empty_kibana'); + await security.testUser.restoreDefaults(); }); it('allows user to navigate to upgrade checkup', async () => { @@ -28,9 +36,17 @@ export default function upgradeAssistantFunctionalTests({ it('allows user to toggle deprecation logging', async () => { await PageObjects.upgradeAssistant.navigateToPage(); + log.debug('expect initial state to be ON'); await PageObjects.upgradeAssistant.expectDeprecationLoggingLabel('On'); + log.debug('Now toggle to off'); await PageObjects.upgradeAssistant.toggleDeprecationLogging(); + await PageObjects.common.sleep(2000); + log.debug('expect state to be OFF after toggle'); await PageObjects.upgradeAssistant.expectDeprecationLoggingLabel('Off'); + await PageObjects.upgradeAssistant.toggleDeprecationLogging(); + await PageObjects.common.sleep(2000); + log.debug('expect state to be ON after toggle'); + await PageObjects.upgradeAssistant.expectDeprecationLoggingLabel('On'); }); it('allows user to open cluster tab', async () => { diff --git a/x-pack/test/functional/apps/uptime/settings.ts b/x-pack/test/functional/apps/uptime/settings.ts index 1286a9940c02c..744b9120028d7 100644 --- a/x-pack/test/functional/apps/uptime/settings.ts +++ b/x-pack/test/functional/apps/uptime/settings.ts @@ -16,7 +16,6 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { const es = getService('es'); - // Flaky https://github.com/elastic/kibana/issues/60866 describe('uptime settings page', () => { beforeEach('navigate to clean app root', async () => { // make 10 checks diff --git a/x-pack/test/functional/config.js b/x-pack/test/functional/config.js index 5c13e430ae2ca..fdd694e73394e 100644 --- a/x-pack/test/functional/config.js +++ b/x-pack/test/functional/config.js @@ -284,6 +284,20 @@ export default async function ({ readConfigFile }) { ], }, + global_upgrade_assistant_role: { + elasticsearch: { + cluster: ['manage'], + }, + kibana: [ + { + feature: { + discover: ['read'], + }, + spaces: ['*'], + }, + ], + }, + global_ccr_role: { elasticsearch: { cluster: ['manage', 'manage_ccr'], diff --git a/x-pack/test/functional/es_archives/alerts/data.json b/x-pack/test/functional/es_archives/alerts/data.json index 3703473606ea2..cc246b0fe44da 100644 --- a/x-pack/test/functional/es_archives/alerts/data.json +++ b/x-pack/test/functional/es_archives/alerts/data.json @@ -38,4 +38,46 @@ "updated_at": "2020-06-17T15:35:39.839Z" } } +} + +{ + "type": "doc", + "value": { + "id": "alert:74f3e6d7-b7bb-477d-ac28-fdf248d5f2a4", + "index": ".kibana_1", + "source": { + "alert": { + "actions": [ + ], + "alertTypeId": "example.always-firing", + "apiKey": "XHcE1hfSJJCvu2oJrKErgbIbR7iu3XAX+c1kki8jESzWZNyBlD4+6yHhCDEx7rNLlP/Hvbut/V8N1BaQkaSpVpiNsW/UxshiCouqJ+cmQ9LbaYnca9eTTVUuPhbHwwsDjfYkakDPqW3gB8sonwZl6rpzZVacfp4=", + "apiKeyOwner": "elastic", + "consumer": "metrics", + "createdAt": "2020-06-17T15:35:38.497Z", + "createdBy": "elastic", + "enabled": true, + "muteAll": false, + "mutedInstanceIds": [ + ], + "name": "always-firing-alert", + "params": { + }, + "schedule": { + "interval": "1m" + }, + "scheduledTaskId": "329798f0-b0b0-11ea-9510-fdf248d5f2a4", + "tags": [ + ], + "throttle": null, + "updatedBy": "elastic" + }, + "migrationVersion": { + "alert": "7.8.0" + }, + "references": [ + ], + "type": "alert", + "updated_at": "2020-06-17T15:35:39.839Z" + } + } } \ No newline at end of file diff --git a/x-pack/test/functional/es_archives/endpoint/artifacts/api_feature/data.json b/x-pack/test/functional/es_archives/endpoint/artifacts/api_feature/data.json index 47390f0428742..3af1070597671 100644 --- a/x-pack/test/functional/es_archives/endpoint/artifacts/api_feature/data.json +++ b/x-pack/test/functional/es_archives/endpoint/artifacts/api_feature/data.json @@ -1,28 +1,3 @@ -{ - "type": "doc", - "value": { - "id": "endpoint:user-artifact:endpoint-exceptionlist-linux-v1-d2a9c760005b08d43394e59a8701ae75c80881934ccf15a006944452b80f7f9f", - "index": ".kibana", - "source": { - "references": [ - ], - "endpoint:user-artifact": { - "body": "eJylkM8KwjAMxl9Fci59gN29iicvMqR02QjUbiSpKGPvbiw6ETwpuX1/fh9kBszKhALNcQa9TQgNCJ2nhOA+vJ4wdWaGqJSHPY8RRXxPCb3QkJEtP07IQUe2GOWYSoedqU8qXq16ikGqeAmpPNRtCqIU3WbnDx4WN38d/WvhQqmCXzDlIlojP9CsjLC0bqWtHwhaGN/1jHVkae3u+6N6Sg==", - "created": 1593016187465, - "compressionAlgorithm": "zlib", - "encryptionAlgorithm": "none", - "identifier": "endpoint-exceptionlist-linux-v1", - "encodedSha256": "5caaeabcb7864d47157fc7c28d5a7398b4f6bbaaa565d789c02ee809253b7613", - "encodedSize": 160, - "decodedSha256": "d2a9c760005b08d43394e59a8701ae75c80881934ccf15a006944452b80f7f9f", - "decodedSize": 358 - }, - "type": "endpoint:user-artifact", - "updated_at": "2020-06-24T16:29:47.584Z" - } - } -} - { "type": "doc", "value": { @@ -83,8 +58,9 @@ ], "endpoint:user-artifact-manifest": { "created": 1593183699663, + "schemaVersion": "v1", + "semanticVersion": "1.0.1", "ids": [ - "endpoint-exceptionlist-linux-v1-d2a9c760005b08d43394e59a8701ae75c80881934ccf15a006944452b80f7f9f", "endpoint-exceptionlist-macos-v1-d801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658", "endpoint-exceptionlist-windows-v1-8d2bcc37e82fad5d06e2c9e4bd96793ea8905ace1d528a57d0d0579ecc8c647e" ] diff --git a/x-pack/test/functional/es_archives/maps/kibana/data.json b/x-pack/test/functional/es_archives/maps/kibana/data.json index d2206009d9e65..7690c92589312 100644 --- a/x-pack/test/functional/es_archives/maps/kibana/data.json +++ b/x-pack/test/functional/es_archives/maps/kibana/data.json @@ -446,6 +446,37 @@ } } +{ + "type": "doc", + "value": { + "id": "map:2de4de10-cc82-11ea-9b0a-eb2886fc84af", + "index": ".kibana", + "source": { + "map": { + "title" : "document example hidden", + "description" : "", + "mapStateJSON" : "{\"zoom\":4.1,\"center\":{\"lon\":-100.61091,\"lat\":33.23887},\"timeFilters\":{\"from\":\"2015-09-20T00:00:00.000Z\",\"to\":\"2015-09-20T01:00:00.000Z\"},\"refreshConfig\":{\"isPaused\":true,\"interval\":1000},\"query\":{\"query\":\"\",\"language\":\"kuery\"},\"filters\":[],\"settings\":{\"autoFitToDataBounds\":false,\"initialLocation\":\"LAST_SAVED_LOCATION\",\"fixedLocation\":{\"lat\":0,\"lon\":0,\"zoom\":2},\"browserLocation\":{\"zoom\":2},\"maxZoom\":24,\"minZoom\":0,\"showSpatialFilters\":true,\"spatialFiltersAlpa\":0.3,\"spatialFiltersFillColor\":\"#DA8B45\",\"spatialFiltersLineColor\":\"#DA8B45\"}}", + "layerListJSON" : "[{\"id\":\"0hmz5\",\"sourceDescriptor\":{\"type\":\"EMS_TMS\",\"id\":\"road_map\"},\"visible\":true,\"temporary\":false,\"style\":{\"type\":\"TILE\",\"properties\":{}},\"type\":\"VECTOR_TILE\",\"minZoom\":0,\"maxZoom\":24},{\"id\":\"z52lq\",\"label\":\"logstash\",\"minZoom\":0,\"maxZoom\":24,\"sourceDescriptor\":{\"id\":\"e1a5e1a6-676c-4a89-8ea9-0d91d64b73c6\",\"type\":\"ES_SEARCH\",\"geoField\":\"geo.coordinates\",\"limit\":2048,\"filterByMapBounds\":true,\"showTooltip\":true,\"tooltipProperties\":[],\"applyGlobalQuery\":true,\"scalingType\":\"LIMIT\",\"indexPatternRefName\":\"layer_1_source_index_pattern\"},\"visible\":false,\"temporary\":false,\"style\":{\"type\":\"VECTOR\",\"properties\":{\"fillColor\":{\"type\":\"STATIC\",\"options\":{\"color\":\"#e6194b\"}},\"lineColor\":{\"type\":\"STATIC\",\"options\":{\"color\":\"#FFFFFF\"}},\"lineWidth\":{\"type\":\"STATIC\",\"options\":{\"size\":1}},\"iconSize\":{\"type\":\"STATIC\",\"options\":{\"size\":10}},\"symbolizeAs\":{\"options\":{\"value\":\"circle\"}},\"icon\":{\"type\":\"STATIC\",\"options\":{\"value\":\"marker\"}}},\"previousStyle\":null},\"type\":\"VECTOR\"}]", + "uiStateJSON" : "{\"isLayerTOCOpen\":true,\"openTOCDetails\":[]}" + }, + "type" : "map", + "references" : [ + { + "name" : "layer_1_source_index_pattern", + "type" : "index-pattern", + "id" : "c698b940-e149-11e8-a35a-370a8516603a" + } + ], + "migrationVersion" : { + "map" : "7.9.0" + }, + "updated_at" : "2020-07-23T01:16:47.600Z" + } + } +} + + + { "type": "doc", "value": { diff --git a/x-pack/test/functional/page_objects/gis_page.js b/x-pack/test/functional/page_objects/gis_page.js index 8a0b4aaefa888..b8f4faf3ebfd8 100644 --- a/x-pack/test/functional/page_objects/gis_page.js +++ b/x-pack/test/functional/page_objects/gis_page.js @@ -17,6 +17,7 @@ export function GisPageProvider({ getService, getPageObjects }) { const find = getService('find'); const queryBar = getService('queryBar'); const comboBox = getService('comboBox'); + const renderable = getService('renderable'); function escapeLayerName(layerName) { return layerName.split(' ').join('_'); @@ -135,6 +136,7 @@ export function GisPageProvider({ getService, getPageObjects }) { // Navigate directly because we don't need to go through the map listing // page. The listing page is skipped if there are no saved objects await PageObjects.common.navigateToUrlWithBrowserHistory(APP_ID, '/map'); + await renderable.waitForRender(); } async saveMap(name) { diff --git a/x-pack/test/functional/page_objects/graph_page.ts b/x-pack/test/functional/page_objects/graph_page.ts index 0d3e2c10579f5..fe049327fe38b 100644 --- a/x-pack/test/functional/page_objects/graph_page.ts +++ b/x-pack/test/functional/page_objects/graph_page.ts @@ -83,10 +83,7 @@ export function GraphPageProvider({ getService, getPageObjects }: FtrProviderCon return [this.getPositionAsString(x1, y1), this.getPositionAsString(x2, y2)]; } - async isolateEdge(edge: Edge) { - const from = edge.sourceNode.label; - const to = edge.targetNode.label; - + async isolateEdge(from: string, to: string) { // select all nodes await testSubjects.click('graphSelectAll'); @@ -109,13 +106,6 @@ export function GraphPageProvider({ getService, getPageObjects }: FtrProviderCon await testSubjects.click('graphRemoveSelection'); } - async clickEdge(edge: Edge) { - await this.stopLayout(); - await PageObjects.common.sleep(1000); - await edge.element.click(); - await this.startLayout(); - } - async stopLayout() { if (await testSubjects.exists('graphPauseLayout')) { await testSubjects.click('graphPauseLayout'); diff --git a/x-pack/test/functional/page_objects/lens_page.ts b/x-pack/test/functional/page_objects/lens_page.ts index d101c9754d562..79548db0e2630 100644 --- a/x-pack/test/functional/page_objects/lens_page.ts +++ b/x-pack/test/functional/page_objects/lens_page.ts @@ -195,5 +195,15 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont async createLayer() { await testSubjects.click('lnsLayerAddButton'); }, + + async linkedToOriginatingApp() { + await PageObjects.header.waitUntilLoadingHasFinished(); + await testSubjects.existOrFail('lnsApp_saveAndReturnButton'); + }, + + async notLinkedToOriginatingApp() { + await PageObjects.header.waitUntilLoadingHasFinished(); + await testSubjects.missingOrFail('lnsApp_saveAndReturnButton'); + }, }); } diff --git a/x-pack/test/functional/page_objects/status_page.js b/x-pack/test/functional/page_objects/status_page.js index 68fc931a9140f..eba5e7dd18496 100644 --- a/x-pack/test/functional/page_objects/status_page.js +++ b/x-pack/test/functional/page_objects/status_page.js @@ -29,7 +29,7 @@ export function StatusPagePageProvider({ getService, getPageObjects }) { async expectStatusPage() { return await retry.try(async () => { log.debug(`expectStatusPage()`); - await find.byCssSelector('[data-test-subj="kibanaChrome"] nav:not(.ng-hide) ', 20000); + await find.byCssSelector('[data-test-subj="statusPageRoot"]', 20000); const url = await browser.getCurrentUrl(); expect(url).to.contain(`/status`); }); diff --git a/x-pack/test/functional/services/ml/api.ts b/x-pack/test/functional/services/ml/api.ts index a48159cd7515f..9dfec3a17dec0 100644 --- a/x-pack/test/functional/services/ml/api.ts +++ b/x-pack/test/functional/services/ml/api.ts @@ -5,14 +5,12 @@ */ import expect from '@kbn/expect'; import { ProvidedType } from '@kbn/test/types/ftr'; +import { Calendar, CalendarEvent } from '../../../../plugins/ml/server/models/calendar/index'; import { DataFrameAnalyticsConfig } from '../../../../plugins/ml/public/application/data_frame_analytics/common'; - import { FtrProviderContext } from '../../ftr_provider_context'; - import { DATAFEED_STATE, JOB_STATE } from '../../../../plugins/ml/common/constants/states'; import { DATA_FRAME_TASK_STATE } from '../../../../plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/common'; import { Datafeed, Job } from '../../../../plugins/ml/common/types/anomaly_detection_jobs'; - export type MlApi = ProvidedType; export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { @@ -325,19 +323,102 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { }); }, - async getCalendar(calendarId: string) { - return await esSupertest.get(`/_ml/calendars/${calendarId}`).expect(200); + async getCalendar(calendarId: string, expectedCode = 200) { + return await esSupertest.get(`/_ml/calendars/${calendarId}`).expect(expectedCode); }, - async createCalendar(calendarId: string, body = { description: '', job_ids: [] }) { + async createCalendar( + calendarId: string, + requestBody: Partial = { description: '', job_ids: [] } + ) { log.debug(`Creating calendar with id '${calendarId}'...`); - await esSupertest.put(`/_ml/calendars/${calendarId}`).send(body).expect(200); + await esSupertest.put(`/_ml/calendars/${calendarId}`).send(requestBody).expect(200); + await this.waitForCalendarToExist(calendarId); + }, + + async deleteCalendar(calendarId: string) { + log.debug(`Deleting calendar with id '${calendarId}'...`); + await esSupertest.delete(`/_ml/calendars/${calendarId}`); + + await this.waitForCalendarNotToExist(calendarId); + }, + + async waitForCalendarToExist(calendarId: string, errorMsg?: string) { + await retry.waitForWithTimeout(`'${calendarId}' to exist`, 5 * 1000, async () => { + if (await this.getCalendar(calendarId, 200)) { + return true; + } else { + throw new Error(errorMsg || `expected calendar '${calendarId}' to exist`); + } + }); + }, - await retry.waitForWithTimeout(`'${calendarId}' to be created`, 30 * 1000, async () => { - if (await this.getCalendar(calendarId)) { + async waitForCalendarNotToExist(calendarId: string, errorMsg?: string) { + await retry.waitForWithTimeout(`'${calendarId}' to not exist`, 5 * 1000, async () => { + if (await this.getCalendar(calendarId, 404)) { return true; } else { - throw new Error(`expected calendar '${calendarId}' to be created`); + throw new Error(errorMsg || `expected calendar '${calendarId}' to not exist`); + } + }); + }, + + async createCalendarEvents(calendarId: string, events: CalendarEvent[]) { + log.debug(`Creating events for calendar with id '${calendarId}'...`); + await esSupertest.post(`/_ml/calendars/${calendarId}/events`).send({ events }).expect(200); + await this.waitForEventsToExistInCalendar(calendarId, events); + }, + + async getCalendarEvents(calendarId: string, expectedCode = 200) { + return await esSupertest.get(`/_ml/calendars/${calendarId}/events`).expect(expectedCode); + }, + + assertAllEventsExistInCalendar: ( + eventsToCheck: CalendarEvent[], + calendar: Calendar + ): boolean => { + const updatedCalendarEvents = calendar.events as CalendarEvent[]; + let allEventsAreUpdated = true; + for (const eventToCheck of eventsToCheck) { + // if at least one of the events that we need to check is not in the updated events + // no need to continue + if ( + updatedCalendarEvents.findIndex( + (updatedEvent) => + updatedEvent.description === eventToCheck.description && + updatedEvent.start_time === eventToCheck.start_time && + updatedEvent.end_time === eventToCheck.end_time + ) < 0 + ) { + allEventsAreUpdated = false; + break; + } + } + expect(allEventsAreUpdated).to.eql( + true, + `Expected calendar ${calendar.calendar_id} to contain events ${JSON.stringify( + eventsToCheck + )}` + ); + return true; + }, + + async waitForEventsToExistInCalendar( + calendarId: string, + eventsToCheck: CalendarEvent[], + errorMsg?: string + ) { + await retry.waitForWithTimeout(`'${calendarId}' events to exist`, 5 * 1000, async () => { + // validate if calendar events have been updated with the requested events + const { body } = await this.getCalendarEvents(calendarId, 200); + + if (this.assertAllEventsExistInCalendar(eventsToCheck, body)) { + return true; + } else { + throw new Error( + errorMsg || + `expected events for calendar '${calendarId}' to have been updated correctly` + ); } }); }, @@ -515,5 +596,43 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { } ); }, + + async getFilter(filterId: string, expectedCode = 200) { + return await esSupertest.get(`/_ml/filters/${filterId}`).expect(expectedCode); + }, + + async createFilter(filterId: string, requestBody: object) { + log.debug(`Creating filter with id '${filterId}'...`); + await esSupertest.put(`/_ml/filters/${filterId}`).send(requestBody).expect(200); + + await this.waitForFilterToExist(filterId, `expected filter '${filterId}' to be created`); + }, + + async deleteFilter(filterId: string) { + log.debug(`Deleting filter with id '${filterId}'...`); + await esSupertest.delete(`/_ml/filters/${filterId}`); + + await this.waitForFilterToNotExist(filterId, `expected filter '${filterId}' to be deleted`); + }, + + async waitForFilterToExist(filterId: string, errorMsg?: string) { + await retry.waitForWithTimeout(`'${filterId}' to exist`, 5 * 1000, async () => { + if (await this.getFilter(filterId, 200)) { + return true; + } else { + throw new Error(errorMsg || `expected filter '${filterId}' to exist`); + } + }); + }, + + async waitForFilterToNotExist(filterId: string, errorMsg?: string) { + await retry.waitForWithTimeout(`'${filterId}' to not exist`, 5 * 1000, async () => { + if (await this.getFilter(filterId, 404)) { + return true; + } else { + throw new Error(errorMsg || `expected filter '${filterId}' to not exist`); + } + }); + }, }; } diff --git a/x-pack/test/functional/services/ml/data_frame_analytics_creation.ts b/x-pack/test/functional/services/ml/data_frame_analytics_creation.ts index e36855a4e769e..5f3d21b80a830 100644 --- a/x-pack/test/functional/services/ml/data_frame_analytics_creation.ts +++ b/x-pack/test/functional/services/ml/data_frame_analytics_creation.ts @@ -199,7 +199,9 @@ export function MachineLearningDataFrameAnalyticsCreationProvider( // }, async assertDestIndexInputExists() { - await testSubjects.existOrFail('mlAnalyticsCreateJobFlyoutDestinationIndexInput'); + await retry.tryForTime(4000, async () => { + await testSubjects.existOrFail('mlAnalyticsCreateJobFlyoutDestinationIndexInput'); + }); }, async assertDestIndexValue(expectedValue: string) { @@ -417,6 +419,35 @@ export function MachineLearningDataFrameAnalyticsCreationProvider( ); }, + async getDestIndexSameAsIdSwitchCheckState(): Promise { + const state = await testSubjects.getAttribute( + 'mlAnalyticsCreateJobWizardDestIndexSameAsIdSwitch', + 'aria-checked' + ); + return state === 'true'; + }, + + async assertDestIndexSameAsIdCheckState(expectedCheckState: boolean) { + const actualCheckState = await this.getDestIndexSameAsIdSwitchCheckState(); + expect(actualCheckState).to.eql( + expectedCheckState, + `Destination index same as job id check state should be '${expectedCheckState}' (got '${actualCheckState}')` + ); + }, + + async assertDestIndexSameAsIdSwitchExists() { + await testSubjects.existOrFail(`mlAnalyticsCreateJobWizardDestIndexSameAsIdSwitch`, { + allowHidden: true, + }); + }, + + async setDestIndexSameAsIdCheckState(checkState: boolean) { + if ((await this.getDestIndexSameAsIdSwitchCheckState()) !== checkState) { + await testSubjects.click('mlAnalyticsCreateJobWizardDestIndexSameAsIdSwitch'); + } + await this.assertDestIndexSameAsIdCheckState(checkState); + }, + async setCreateIndexPatternSwitchState(checkState: boolean) { if ((await this.getCreateIndexPatternSwitchCheckState()) !== checkState) { await testSubjects.click('mlAnalyticsCreateJobWizardCreateIndexPatternSwitch'); diff --git a/x-pack/test/functional/services/ml/data_visualizer_file_based.ts b/x-pack/test/functional/services/ml/data_visualizer_file_based.ts index eea0a83879ea7..8c5e40dd5dbdd 100644 --- a/x-pack/test/functional/services/ml/data_visualizer_file_based.ts +++ b/x-pack/test/functional/services/ml/data_visualizer_file_based.ts @@ -101,7 +101,7 @@ export function MachineLearningDataVisualizerFileBasedProvider( }, async startImportAndWaitForProcessing() { - await testSubjects.click('mlFileDataVisImportButton'); + await testSubjects.clickWhenNotDisabled('mlFileDataVisImportButton'); await retry.tryForTime(60 * 1000, async () => { await testSubjects.existOrFail('mlFileImportSuccessCallout'); }); diff --git a/x-pack/test/functional/services/uptime/navigation.ts b/x-pack/test/functional/services/uptime/navigation.ts index f8e0c0cff41f4..ab511abf130a5 100644 --- a/x-pack/test/functional/services/uptime/navigation.ts +++ b/x-pack/test/functional/services/uptime/navigation.ts @@ -41,7 +41,7 @@ export function UptimeNavigationProvider({ getService, getPageObjects }: FtrProv goToSettings: async () => { await goToUptimeRoot(); await testSubjects.click('settings-page-link', 5000); - await testSubjects.existOrFail('uptimeSettingsPage', { timeout: 2000 }); + await testSubjects.existOrFail('uptimeSettingsPage', { timeout: 10000 }); }, checkIfOnMonitorPage: async (monitorId: string) => { diff --git a/x-pack/test/functional_enterprise_search/apps/enterprise_search/with_host_configured/app_search/engines.ts b/x-pack/test/functional_enterprise_search/apps/enterprise_search/with_host_configured/app_search/engines.ts index e4ebd61c0692a..1742ed443984b 100644 --- a/x-pack/test/functional_enterprise_search/apps/enterprise_search/with_host_configured/app_search/engines.ts +++ b/x-pack/test/functional_enterprise_search/apps/enterprise_search/with_host_configured/app_search/engines.ts @@ -5,7 +5,7 @@ */ import expect from '@kbn/expect'; -import { EsArchiver } from 'src/es_archiver'; +import { EsArchiver } from '@kbn/es-archiver'; import { AppSearchService, IEngine } from '../../../../services/app_search_service'; import { Browser } from '../../../../../../../test/functional/services/common'; import { FtrProviderContext } from '../../../../ftr_provider_context'; diff --git a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/alerts.ts b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/alerts.ts index 2225316bba80f..fa714e8374ec7 100644 --- a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/alerts.ts +++ b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/alerts.ts @@ -28,7 +28,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { name: generateUniqueKey(), tags: ['foo', 'bar'], alertTypeId: 'test.noop', - consumer: 'test', + consumer: 'alerts', schedule: { interval: '1m' }, throttle: '1m', actions: [], @@ -86,7 +86,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await testSubjects.click('variableMenuButton-1'); expect(await messageTextArea.getAttribute('value')).to.eql( - 'test message {{alertId}} some additional text {{alertName}}' + 'test message {{alertId}} some additional text {{alertInstanceId}}' ); await testSubjects.click('saveAlertButton'); @@ -372,7 +372,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await testSubjects.click('deleteAll'); await testSubjects.existOrFail('deleteIdsConfirmation'); await testSubjects.click('deleteIdsConfirmation > confirmModalConfirmButton'); - await testSubjects.missingOrFail('deleteIdsConfirmation'); + await testSubjects.missingOrFail('deleteIdsConfirmation', { timeout: 5000 }); await pageObjects.common.closeToast(); diff --git a/x-pack/test/functional_with_es_ssl/fixtures/plugins/alerts/kibana.json b/x-pack/test/functional_with_es_ssl/fixtures/plugins/alerts/kibana.json index 74f740f52a8b2..4ad7aa3126e88 100644 --- a/x-pack/test/functional_with_es_ssl/fixtures/plugins/alerts/kibana.json +++ b/x-pack/test/functional_with_es_ssl/fixtures/plugins/alerts/kibana.json @@ -3,7 +3,7 @@ "version": "1.0.0", "kibanaVersion": "kibana", "configPath": ["xpack"], - "requiredPlugins": ["alerts", "triggers_actions_ui"], + "requiredPlugins": ["alerts", "triggers_actions_ui", "features"], "server": true, "ui": true } diff --git a/x-pack/test/functional_with_es_ssl/fixtures/plugins/alerts/public/plugin.ts b/x-pack/test/functional_with_es_ssl/fixtures/plugins/alerts/public/plugin.ts index 2bc299ede930b..503c328017a9a 100644 --- a/x-pack/test/functional_with_es_ssl/fixtures/plugins/alerts/public/plugin.ts +++ b/x-pack/test/functional_with_es_ssl/fixtures/plugins/alerts/public/plugin.ts @@ -21,7 +21,7 @@ export interface AlertingExamplePublicSetupDeps { export class AlertingFixturePlugin implements Plugin { public setup(core: CoreSetup, { alerts, triggers_actions_ui }: AlertingExamplePublicSetupDeps) { alerts.registerNavigation( - 'consumer-noop', + 'alerting_fixture', 'test.noop', (alert: SanitizedAlert, alertType: AlertType) => `/alert/${alert.id}` ); @@ -49,8 +49,8 @@ export class AlertingFixturePlugin implements Plugin { - public setup(core: CoreSetup, { alerts }: AlertingExampleDeps) { + public setup(core: CoreSetup, { alerts, features }: AlertingExampleDeps) { createNoopAlertType(alerts); createAlwaysFiringAlertType(alerts); + features.registerFeature({ + id: 'alerting_fixture', + name: 'alerting_fixture', + app: [], + alerting: ['test.always-firing', 'test.noop'], + privileges: { + all: { + alerting: { + all: ['test.always-firing', 'test.noop'], + }, + savedObject: { + all: [], + read: [], + }, + ui: [], + }, + read: { + alerting: { + all: ['test.always-firing', 'test.noop'], + }, + savedObject: { + all: [], + read: [], + }, + ui: [], + }, + }, + }); } public start() {} @@ -32,7 +62,7 @@ function createNoopAlertType(alerts: AlertingSetup) { actionGroups: [{ id: 'default', name: 'Default' }], defaultActionGroupId: 'default', async executor() {}, - producer: 'alerting', + producer: 'alerts', }; alerts.registerType(noopAlertType); } @@ -46,7 +76,7 @@ function createAlwaysFiringAlertType(alerts: AlertingSetup) { { id: 'default', name: 'Default' }, { id: 'other', name: 'Other' }, ], - producer: 'alerting', + producer: 'alerts', async executor(alertExecutorOptions: any) { const { services, state, params } = alertExecutorOptions; diff --git a/x-pack/test/functional_with_es_ssl/services/alerting/alerts.ts b/x-pack/test/functional_with_es_ssl/services/alerting/alerts.ts index 25f4c6a932d5e..23a4529139c53 100644 --- a/x-pack/test/functional_with_es_ssl/services/alerting/alerts.ts +++ b/x-pack/test/functional_with_es_ssl/services/alerting/alerts.ts @@ -43,7 +43,7 @@ export class Alerts { name, tags, alertTypeId, - consumer: consumer ?? 'bar', + consumer: consumer ?? 'alerts', schedule: schedule ?? { interval: '1m' }, throttle: throttle ?? '1m', actions: actions ?? [], @@ -68,7 +68,7 @@ export class Alerts { name, tags: ['foo'], alertTypeId: 'test.noop', - consumer: 'consumer-noop', + consumer: 'alerting_fixture', schedule: { interval: '1m' }, throttle: '1m', actions: [], @@ -101,7 +101,7 @@ export class Alerts { name, tags: ['foo'], alertTypeId: 'test.always-firing', - consumer: 'bar', + consumer: 'alerts', schedule: { interval: '1m' }, throttle: '1m', actions, diff --git a/x-pack/test/api_integration/apis/ingest_manager/agent_config.ts b/x-pack/test/ingest_manager_api_integration/apis/agent_config/agent_config.ts similarity index 97% rename from x-pack/test/api_integration/apis/ingest_manager/agent_config.ts rename to x-pack/test/ingest_manager_api_integration/apis/agent_config/agent_config.ts index 8bf3efbdaf501..89258600c85e1 100644 --- a/x-pack/test/api_integration/apis/ingest_manager/agent_config.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/agent_config/agent_config.ts @@ -5,7 +5,7 @@ */ import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../ftr_provider_context'; +import { FtrProviderContext } from '../../../api_integration/ftr_provider_context'; export default function ({ getService }: FtrProviderContext) { const supertest = getService('supertest'); diff --git a/x-pack/test/api_integration/apis/ingest_manager/index.js b/x-pack/test/ingest_manager_api_integration/apis/agent_config/index.js similarity index 100% rename from x-pack/test/api_integration/apis/ingest_manager/index.js rename to x-pack/test/ingest_manager_api_integration/apis/agent_config/index.js diff --git a/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts b/x-pack/test/ingest_manager_api_integration/apis/epm/install_overrides.ts similarity index 100% rename from x-pack/test/ingest_manager_api_integration/apis/epm/install.ts rename to x-pack/test/ingest_manager_api_integration/apis/epm/install_overrides.ts diff --git a/x-pack/test/ingest_manager_api_integration/apis/epm/install_remove_assets.ts b/x-pack/test/ingest_manager_api_integration/apis/epm/install_remove_assets.ts new file mode 100644 index 0000000000000..9ca8ebf136078 --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/epm/install_remove_assets.ts @@ -0,0 +1,197 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../api_integration/ftr_provider_context'; +import { skipIfNoDockerRegistry } from '../../helpers'; + +export default function (providerContext: FtrProviderContext) { + const { getService } = providerContext; + const kibanaServer = getService('kibanaServer'); + const supertest = getService('supertest'); + const es = getService('es'); + const pkgName = 'all_assets'; + const pkgVersion = '0.1.0'; + const pkgKey = `${pkgName}-${pkgVersion}`; + const logsTemplateName = `logs-${pkgName}.test_logs`; + const metricsTemplateName = `metrics-${pkgName}.test_metrics`; + + const uninstallPackage = async (pkg: string) => { + await supertest.delete(`/api/ingest_manager/epm/packages/${pkg}`).set('kbn-xsrf', 'xxxx'); + }; + const installPackage = async (pkg: string) => { + await supertest.post(`/api/ingest_manager/epm/packages/${pkg}`).set('kbn-xsrf', 'xxxx'); + }; + + describe('installs and uninstalls all assets', async () => { + describe('installs all assets when installing a package for the first time', async () => { + skipIfNoDockerRegistry(providerContext); + before(async () => { + await installPackage(pkgKey); + }); + it('should have installed the ILM policy', async function () { + const resPolicy = await es.transport.request({ + method: 'GET', + path: `/_ilm/policy/all_assets`, + }); + expect(resPolicy.statusCode).equal(200); + }); + it('should have installed the index templates', async function () { + const resLogsTemplate = await es.transport.request({ + method: 'GET', + path: `/_index_template/${logsTemplateName}`, + }); + expect(resLogsTemplate.statusCode).equal(200); + + const resMetricsTemplate = await es.transport.request({ + method: 'GET', + path: `/_index_template/${metricsTemplateName}`, + }); + expect(resMetricsTemplate.statusCode).equal(200); + }); + it('should have installed the pipelines', async function () { + const res = await es.transport.request({ + method: 'GET', + path: `/_ingest/pipeline/${logsTemplateName}-${pkgVersion}`, + }); + expect(res.statusCode).equal(200); + }); + it('should have installed the template components', async function () { + const res = await es.transport.request({ + method: 'GET', + path: `/_component_template/${logsTemplateName}-mappings`, + }); + expect(res.statusCode).equal(200); + const resSettings = await es.transport.request({ + method: 'GET', + path: `/_component_template/${logsTemplateName}-settings`, + }); + expect(resSettings.statusCode).equal(200); + }); + it('should have installed the kibana assets', async function () { + const resIndexPatternLogs = await kibanaServer.savedObjects.get({ + type: 'index-pattern', + id: 'logs-*', + }); + expect(resIndexPatternLogs.id).equal('logs-*'); + const resIndexPatternMetrics = await kibanaServer.savedObjects.get({ + type: 'index-pattern', + id: 'metrics-*', + }); + expect(resIndexPatternMetrics.id).equal('metrics-*'); + const resIndexPatternEvents = await kibanaServer.savedObjects.get({ + type: 'index-pattern', + id: 'events-*', + }); + expect(resIndexPatternEvents.id).equal('events-*'); + const resDashboard = await kibanaServer.savedObjects.get({ + type: 'dashboard', + id: 'sample_dashboard', + }); + expect(resDashboard.id).equal('sample_dashboard'); + const resDashboard2 = await kibanaServer.savedObjects.get({ + type: 'dashboard', + id: 'sample_dashboard2', + }); + expect(resDashboard2.id).equal('sample_dashboard2'); + const resVis = await kibanaServer.savedObjects.get({ + type: 'visualization', + id: 'sample_visualization', + }); + expect(resVis.id).equal('sample_visualization'); + const resSearch = await kibanaServer.savedObjects.get({ + type: 'search', + id: 'sample_search', + }); + expect(resSearch.id).equal('sample_search'); + }); + }); + + describe('uninstalls all assets when uninstalling a package', async () => { + skipIfNoDockerRegistry(providerContext); + before(async () => { + await uninstallPackage(pkgKey); + }); + it('should have uninstalled the index templates', async function () { + const resLogsTemplate = await es.transport.request( + { + method: 'GET', + path: `/_index_template/${logsTemplateName}`, + }, + { + ignore: [404], + } + ); + expect(resLogsTemplate.statusCode).equal(404); + + const resMetricsTemplate = await es.transport.request( + { + method: 'GET', + path: `/_index_template/${metricsTemplateName}`, + }, + { + ignore: [404], + } + ); + expect(resMetricsTemplate.statusCode).equal(404); + }); + it('should have uninstalled the pipelines', async function () { + const res = await es.transport.request( + { + method: 'GET', + path: `/_ingest/pipeline/${logsTemplateName}-${pkgVersion}`, + }, + { + ignore: [404], + } + ); + expect(res.statusCode).equal(404); + }); + it('should have uninstalled the kibana assets', async function () { + let resDashboard; + try { + resDashboard = await kibanaServer.savedObjects.get({ + type: 'dashboard', + id: 'sample_dashboard', + }); + } catch (err) { + resDashboard = err; + } + expect(resDashboard.response.data.statusCode).equal(404); + let resDashboard2; + try { + resDashboard2 = await kibanaServer.savedObjects.get({ + type: 'dashboard', + id: 'sample_dashboard2', + }); + } catch (err) { + resDashboard2 = err; + } + expect(resDashboard2.response.data.statusCode).equal(404); + let resVis; + try { + resVis = await kibanaServer.savedObjects.get({ + type: 'visualization', + id: 'sample_visualization', + }); + } catch (err) { + resVis = err; + } + expect(resVis.response.data.statusCode).equal(404); + let resSearch; + try { + resVis = await kibanaServer.savedObjects.get({ + type: 'search', + id: 'sample_search', + }); + } catch (err) { + resSearch = err; + } + expect(resSearch.response.data.statusCode).equal(404); + }); + }); + }); +} diff --git a/x-pack/test/ingest_manager_api_integration/apis/epm/list.ts b/x-pack/test/ingest_manager_api_integration/apis/epm/list.ts index 74aaf48d15674..98b26c1c04ebb 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/epm/list.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/epm/list.ts @@ -29,7 +29,7 @@ export default function ({ getService }: FtrProviderContext) { return response.body; }; const listResponse = await fetchPackageList(); - expect(listResponse.response.length).to.be(5); + expect(listResponse.response.length).to.be(13); } else { warnAndSkipTest(this, log); } diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_logs/elasticsearch/ilm_policy/all_assets.json b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_logs/elasticsearch/ilm_policy/all_assets.json new file mode 100644 index 0000000000000..7cf62e890f865 --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_logs/elasticsearch/ilm_policy/all_assets.json @@ -0,0 +1,15 @@ +{ + "policy": { + "phases": { + "hot": { + "min_age": "0ms", + "actions": { + "rollover": { + "max_size": "50gb", + "max_age": "30d" + } + } + } + } + } +} \ No newline at end of file diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_logs/elasticsearch/ingest_pipeline/default.yml b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_logs/elasticsearch/ingest_pipeline/default.yml new file mode 100644 index 0000000000000..580db049d0d5d --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_logs/elasticsearch/ingest_pipeline/default.yml @@ -0,0 +1,7 @@ +--- +description: Pipeline for parsing test logs + plugins. +processors: +- set: + field: error.message + value: '{{ _ingest.on_failure_message }}' \ No newline at end of file diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_logs/fields/fields.yml b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_logs/fields/fields.yml new file mode 100644 index 0000000000000..12a9a03c1337b --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_logs/fields/fields.yml @@ -0,0 +1,16 @@ +- name: dataset.type + type: constant_keyword + description: > + Dataset type. +- name: dataset.name + type: constant_keyword + description: > + Dataset name. +- name: dataset.namespace + type: constant_keyword + description: > + Dataset namespace. +- name: '@timestamp' + type: date + description: > + Event timestamp. diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_logs/manifest.yml b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_logs/manifest.yml new file mode 100644 index 0000000000000..8cd522e2845bb --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_logs/manifest.yml @@ -0,0 +1,9 @@ +title: Test Dataset + +type: logs + +elasticsearch: + index_template.mappings: + dynamic: false + index_template.settings: + index.lifecycle.name: reference \ No newline at end of file diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_metrics/fields/fields.yml b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_metrics/fields/fields.yml new file mode 100644 index 0000000000000..12a9a03c1337b --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_metrics/fields/fields.yml @@ -0,0 +1,16 @@ +- name: dataset.type + type: constant_keyword + description: > + Dataset type. +- name: dataset.name + type: constant_keyword + description: > + Dataset name. +- name: dataset.namespace + type: constant_keyword + description: > + Dataset namespace. +- name: '@timestamp' + type: date + description: > + Event timestamp. diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_metrics/manifest.yml b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_metrics/manifest.yml new file mode 100644 index 0000000000000..6bc20442bd432 --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/dataset/test_metrics/manifest.yml @@ -0,0 +1,3 @@ +title: Test Dataset + +type: metrics \ No newline at end of file diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/docs/README.md b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/docs/README.md new file mode 100644 index 0000000000000..2617f1fcabe11 --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/docs/README.md @@ -0,0 +1,3 @@ +# Test package + +For testing that a package installs its elasticsearch assets when installed for the first time (not updating) and removing the package diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/img/logo_overrides_64_color.svg b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/img/logo_overrides_64_color.svg new file mode 100644 index 0000000000000..b03007a76ffcc --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/img/logo_overrides_64_color.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/kibana/dashboard/sample_dashboard.json b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/kibana/dashboard/sample_dashboard.json new file mode 100644 index 0000000000000..ef08d69324210 --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/kibana/dashboard/sample_dashboard.json @@ -0,0 +1,16 @@ +{ + "attributes": { + "description": "Sample dashboard", + "hits": 0, + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{\"filter\":[],\"highlightAll\":true,\"query\":{\"language\":\"kuery\",\"query\":\"\"},\"version\":true}" + }, + "optionsJSON": "{\"darkTheme\":false}", + "panelsJSON": "[{\"embeddableConfig\":{},\"gridData\":{\"h\":12,\"i\":\"1\",\"w\":24,\"x\":0,\"y\":0},\"panelIndex\":\"1\",\"panelRefName\":\"panel_0\",\"version\":\"7.3.0\"},{\"embeddableConfig\":{\"columns\":[\"kafka.log.class\",\"kafka.log.trace.class\",\"kafka.log.trace.full\"],\"sort\":[\"@timestamp\",\"desc\"]},\"gridData\":{\"h\":12,\"i\":\"2\",\"w\":24,\"x\":24,\"y\":0},\"panelIndex\":\"2\",\"panelRefName\":\"panel_1\",\"version\":\"7.3.0\"},{\"embeddableConfig\":{\"columns\":[\"log.level\",\"kafka.log.component\",\"message\"],\"sort\":[\"@timestamp\",\"desc\"]},\"gridData\":{\"h\":20,\"i\":\"3\",\"w\":48,\"x\":0,\"y\":20},\"panelIndex\":\"3\",\"panelRefName\":\"panel_2\",\"version\":\"7.3.0\"},{\"embeddableConfig\":{},\"gridData\":{\"h\":8,\"i\":\"4\",\"w\":48,\"x\":0,\"y\":12},\"panelIndex\":\"4\",\"panelRefName\":\"panel_3\",\"version\":\"7.3.0\"}]", + "timeRestore": false, + "title": "[Logs Sample] Overview ECS", + "version": 1 + }, + "id": "sample_dashboard", + "type": "dashboard" +} \ No newline at end of file diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/kibana/dashboard/sample_dashboard2.json b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/kibana/dashboard/sample_dashboard2.json new file mode 100644 index 0000000000000..7ea63c5d444ba --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/kibana/dashboard/sample_dashboard2.json @@ -0,0 +1,16 @@ +{ + "attributes": { + "description": "Sample dashboard 2", + "hits": 0, + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{\"filter\":[],\"highlightAll\":true,\"query\":{\"language\":\"kuery\",\"query\":\"\"},\"version\":true}" + }, + "optionsJSON": "{\"darkTheme\":false}", + "panelsJSON": "[{\"embeddableConfig\":{},\"gridData\":{\"h\":12,\"i\":\"1\",\"w\":24,\"x\":0,\"y\":0},\"panelIndex\":\"1\",\"panelRefName\":\"panel_0\",\"version\":\"7.3.0\"},{\"embeddableConfig\":{\"columns\":[\"kafka.log.class\",\"kafka.log.trace.class\",\"kafka.log.trace.full\"],\"sort\":[\"@timestamp\",\"desc\"]},\"gridData\":{\"h\":12,\"i\":\"2\",\"w\":24,\"x\":24,\"y\":0},\"panelIndex\":\"2\",\"panelRefName\":\"panel_1\",\"version\":\"7.3.0\"},{\"embeddableConfig\":{\"columns\":[\"log.level\",\"kafka.log.component\",\"message\"],\"sort\":[\"@timestamp\",\"desc\"]},\"gridData\":{\"h\":20,\"i\":\"3\",\"w\":48,\"x\":0,\"y\":20},\"panelIndex\":\"3\",\"panelRefName\":\"panel_2\",\"version\":\"7.3.0\"},{\"embeddableConfig\":{},\"gridData\":{\"h\":8,\"i\":\"4\",\"w\":48,\"x\":0,\"y\":12},\"panelIndex\":\"4\",\"panelRefName\":\"panel_3\",\"version\":\"7.3.0\"}]", + "timeRestore": false, + "title": "[Logs Sample2] Overview ECS", + "version": 1 + }, + "id": "sample_dashboard2", + "type": "dashboard" +} \ No newline at end of file diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/kibana/search/sample_search.json b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/kibana/search/sample_search.json new file mode 100644 index 0000000000000..28185affabef8 --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/kibana/search/sample_search.json @@ -0,0 +1,24 @@ +{ + "attributes": { + "columns": [ + "log.level", + "kafka.log.component", + "message" + ], + "description": "", + "hits": 0, + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{\"filter\":[{\"$state\":{\"store\":\"appState\"},\"meta\":{\"alias\":null,\"disabled\":false,\"indexRefName\":\"kibanaSavedObjectMeta.searchSourceJSON.filter[0].meta.index\",\"key\":\"dataset.name\",\"negate\":false,\"params\":{\"query\":\"kafka.log\",\"type\":\"phrase\"},\"type\":\"phrase\",\"value\":\"log\"},\"query\":{\"match\":{\"dataset.name\":{\"query\":\"kafka.log\",\"type\":\"phrase\"}}}}],\"highlightAll\":true,\"indexRefName\":\"kibanaSavedObjectMeta.searchSourceJSON.index\",\"query\":{\"language\":\"kuery\",\"query\":\"\"},\"version\":true}" + }, + "sort": [ + [ + "@timestamp", + "desc" + ] + ], + "title": "All logs [Logs Kafka] ECS", + "version": 1 + }, + "id": "sample_search", + "type": "search" +} \ No newline at end of file diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/kibana/visualization/sample_visualization.json b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/kibana/visualization/sample_visualization.json new file mode 100644 index 0000000000000..e814b83bbf324 --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/kibana/visualization/sample_visualization.json @@ -0,0 +1,11 @@ +{ + "attributes": { + "description": "sample visualization", + "title": "sample vis title", + "uiStateJSON": "{}", + "version": 1, + "visState": "{\"aggs\":[{\"enabled\":true,\"id\":\"1\",\"params\":{},\"schema\":\"metric\",\"type\":\"count\"},{\"enabled\":true,\"id\":\"2\",\"params\":{\"extended_bounds\":{},\"field\":\"@timestamp\",\"interval\":\"auto\",\"min_doc_count\":1},\"schema\":\"segment\",\"type\":\"date_histogram\"},{\"enabled\":true,\"id\":\"3\",\"params\":{\"customLabel\":\"Log Level\",\"field\":\"log.level\",\"order\":\"desc\",\"orderBy\":\"1\",\"size\":5},\"schema\":\"group\",\"type\":\"terms\"}],\"params\":{\"addLegend\":true,\"addTimeMarker\":false,\"addTooltip\":true,\"categoryAxes\":[{\"id\":\"CategoryAxis-1\",\"labels\":{\"show\":true,\"truncate\":100},\"position\":\"bottom\",\"scale\":{\"type\":\"linear\"},\"show\":true,\"style\":{},\"title\":{\"text\":\"@timestamp per day\"},\"type\":\"category\"}],\"grid\":{\"categoryLines\":false,\"style\":{\"color\":\"#eee\"}},\"legendPosition\":\"right\",\"seriesParams\":[{\"data\":{\"id\":\"1\",\"label\":\"Count\"},\"drawLinesBetweenPoints\":true,\"mode\":\"stacked\",\"show\":\"true\",\"showCircles\":true,\"type\":\"histogram\",\"valueAxis\":\"ValueAxis-1\"}],\"times\":[],\"type\":\"histogram\",\"valueAxes\":[{\"id\":\"ValueAxis-1\",\"labels\":{\"filter\":false,\"rotate\":0,\"show\":true,\"truncate\":100},\"name\":\"LeftAxis-1\",\"position\":\"left\",\"scale\":{\"mode\":\"normal\",\"type\":\"linear\"},\"show\":true,\"style\":{},\"title\":{\"text\":\"Count\"},\"type\":\"value\"}]},\"title\":\"Log levels over time [Logs Kafka] ECS\",\"type\":\"histogram\"}" + }, + "id": "sample_visualization", + "type": "visualization" +} \ No newline at end of file diff --git a/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/manifest.yml b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/manifest.yml new file mode 100644 index 0000000000000..3c11b5103fbeb --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/fixtures/test_packages/all_assets/0.1.0/manifest.yml @@ -0,0 +1,20 @@ +format_version: 1.0.0 +name: all_assets +title: All Assets Installed/Uninstalled Test +description: This is a test package for testing that all assets were installed when installing a package for the first time and removing the assets during package uninstall +version: 0.1.0 +categories: [] +release: beta +type: integration +license: basic + +requirement: + elasticsearch: + versions: '>7.7.0' + kibana: + versions: '>7.7.0' + +icons: + - src: '/img/logo_overrides_64_color.svg' + size: '16x16' + type: 'image/svg+xml' diff --git a/x-pack/test/api_integration/apis/fleet/agents/acks.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/acks.ts similarity index 98% rename from x-pack/test/api_integration/apis/fleet/agents/acks.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/agents/acks.ts index a040ef20081a8..c9fa80c88762b 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/acks.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/acks.ts @@ -6,8 +6,7 @@ import expect from '@kbn/expect'; import uuid from 'uuid'; - -import { FtrProviderContext } from '../../../ftr_provider_context'; +import { FtrProviderContext } from '../../../../api_integration/ftr_provider_context'; import { getSupertestWithoutAuth } from './services'; export default function (providerContext: FtrProviderContext) { diff --git a/x-pack/test/api_integration/apis/fleet/agents/actions.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/actions.ts similarity index 96% rename from x-pack/test/api_integration/apis/fleet/agents/actions.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/agents/actions.ts index c0b2aedf5c244..8dc4e5c232b80 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/actions.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/actions.ts @@ -5,8 +5,7 @@ */ import expect from '@kbn/expect'; - -import { FtrProviderContext } from '../../../ftr_provider_context'; +import { FtrProviderContext } from '../../../../api_integration/ftr_provider_context'; export default function (providerContext: FtrProviderContext) { const { getService } = providerContext; diff --git a/x-pack/test/api_integration/apis/fleet/agents/checkin.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/checkin.ts similarity index 94% rename from x-pack/test/api_integration/apis/fleet/agents/checkin.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/agents/checkin.ts index 70147f602e9c7..79f6cfae175e1 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/checkin.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/checkin.ts @@ -7,8 +7,9 @@ import expect from '@kbn/expect'; import uuid from 'uuid'; -import { FtrProviderContext } from '../../../ftr_provider_context'; +import { FtrProviderContext } from '../../../../api_integration/ftr_provider_context'; import { getSupertestWithoutAuth, setupIngest } from './services'; +import { skipIfNoDockerRegistry } from '../../../helpers'; export default function (providerContext: FtrProviderContext) { const { getService } = providerContext; @@ -19,6 +20,7 @@ export default function (providerContext: FtrProviderContext) { let apiKey: { id: string; api_key: string }; describe('fleet_agents_checkin', () => { + skipIfNoDockerRegistry(providerContext); before(async () => { await esArchiver.loadIfNeeded('fleet/agents'); diff --git a/x-pack/test/api_integration/apis/fleet/agent_flow.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/complete_flow.ts similarity index 96% rename from x-pack/test/api_integration/apis/fleet/agent_flow.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/agents/complete_flow.ts index da472ca912d40..8d7472f0ecd8b 100644 --- a/x-pack/test/api_integration/apis/fleet/agent_flow.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/complete_flow.ts @@ -6,8 +6,9 @@ import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../ftr_provider_context'; -import { setupIngest, getSupertestWithoutAuth } from './agents/services'; +import { FtrProviderContext } from '../../../../api_integration/ftr_provider_context'; +import { setupIngest, getSupertestWithoutAuth } from './services'; +import { skipIfNoDockerRegistry } from '../../../helpers'; export default function (providerContext: FtrProviderContext) { const { getService } = providerContext; @@ -19,6 +20,7 @@ export default function (providerContext: FtrProviderContext) { const esClient = getService('es'); describe('fleet_agent_flow', () => { + skipIfNoDockerRegistry(providerContext); before(async () => { await esArchiver.load('empty_kibana'); }); diff --git a/x-pack/test/api_integration/apis/fleet/delete_agent.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/delete.ts similarity index 97% rename from x-pack/test/api_integration/apis/fleet/delete_agent.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/agents/delete.ts index eefdc35338cb4..dc05b7a4dd792 100644 --- a/x-pack/test/api_integration/apis/fleet/delete_agent.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/delete.ts @@ -5,7 +5,7 @@ */ import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../ftr_provider_context'; +import { FtrProviderContext } from '../../../../api_integration/ftr_provider_context'; export default function ({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); diff --git a/x-pack/test/api_integration/apis/fleet/agents/enroll.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/enroll.ts similarity index 96% rename from x-pack/test/api_integration/apis/fleet/agents/enroll.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/agents/enroll.ts index 58440a34457d0..ef9f2b2e61500 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/enroll.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/enroll.ts @@ -7,8 +7,9 @@ import expect from '@kbn/expect'; import uuid from 'uuid'; -import { FtrProviderContext } from '../../../ftr_provider_context'; +import { FtrProviderContext } from '../../../../api_integration/ftr_provider_context'; import { getSupertestWithoutAuth, setupIngest, getEsClientForAPIKey } from './services'; +import { skipIfNoDockerRegistry } from '../../../helpers'; export default function (providerContext: FtrProviderContext) { const { getService } = providerContext; @@ -21,8 +22,8 @@ export default function (providerContext: FtrProviderContext) { let apiKey: { id: string; api_key: string }; let kibanaVersion: string; - // Flaky: https://github.com/elastic/kibana/issues/60865 - describe.skip('fleet_agents_enroll', () => { + describe('fleet_agents_enroll', () => { + skipIfNoDockerRegistry(providerContext); before(async () => { await esArchiver.loadIfNeeded('fleet/agents'); diff --git a/x-pack/test/api_integration/apis/fleet/agents/events.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/events.ts similarity index 93% rename from x-pack/test/api_integration/apis/fleet/agents/events.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/agents/events.ts index 44fc4389cab3c..93147091dc430 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/events.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/events.ts @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../ftr_provider_context'; +import { FtrProviderContext } from '../../../../api_integration/ftr_provider_context'; export default function ({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); diff --git a/x-pack/test/api_integration/apis/fleet/list_agent.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/list.ts similarity index 97% rename from x-pack/test/api_integration/apis/fleet/list_agent.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/agents/list.ts index 59ecb8f2579b1..23563c6f43bbe 100644 --- a/x-pack/test/api_integration/apis/fleet/list_agent.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/list.ts @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../ftr_provider_context'; +import { FtrProviderContext } from '../../../../api_integration/ftr_provider_context'; export default function ({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); diff --git a/x-pack/test/api_integration/apis/fleet/agents/services.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/services.ts similarity index 94% rename from x-pack/test/api_integration/apis/fleet/agents/services.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/agents/services.ts index 86c5fb5032c7f..70d59ecc0b0da 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/services.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/services.ts @@ -8,7 +8,7 @@ import supertestAsPromised from 'supertest-as-promised'; import { Client } from '@elastic/elasticsearch'; import { format as formatUrl } from 'url'; -import { FtrProviderContext } from '../../../ftr_provider_context'; +import { FtrProviderContext } from '../../../../api_integration/ftr_provider_context'; export function getSupertestWithoutAuth({ getService }: FtrProviderContext) { const config = getService('config'); diff --git a/x-pack/test/api_integration/apis/fleet/unenroll_agent.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/unenroll.ts similarity index 93% rename from x-pack/test/api_integration/apis/fleet/unenroll_agent.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/agents/unenroll.ts index bbbce3314e4cc..d1ff8731183ba 100644 --- a/x-pack/test/api_integration/apis/fleet/unenroll_agent.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/unenroll.ts @@ -7,8 +7,9 @@ import expect from '@kbn/expect'; import uuid from 'uuid'; -import { FtrProviderContext } from '../../ftr_provider_context'; -import { setupIngest } from './agents/services'; +import { FtrProviderContext } from '../../../../api_integration/ftr_provider_context'; +import { setupIngest } from './services'; +import { skipIfNoDockerRegistry } from '../../../helpers'; export default function (providerContext: FtrProviderContext) { const { getService } = providerContext; @@ -17,6 +18,7 @@ export default function (providerContext: FtrProviderContext) { const esClient = getService('es'); describe('fleet_unenroll_agent', () => { + skipIfNoDockerRegistry(providerContext); let accessAPIKeyId: string; let outputAPIKeyId: string; before(async () => { diff --git a/x-pack/test/api_integration/apis/fleet/enrollment_api_keys/crud.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/enrollment_api_keys/crud.ts similarity index 95% rename from x-pack/test/api_integration/apis/fleet/enrollment_api_keys/crud.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/enrollment_api_keys/crud.ts index e9685d663aac6..bc9182627326b 100644 --- a/x-pack/test/api_integration/apis/fleet/enrollment_api_keys/crud.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/enrollment_api_keys/crud.ts @@ -6,8 +6,9 @@ import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../ftr_provider_context'; +import { FtrProviderContext } from '../../../../api_integration/ftr_provider_context'; import { setupIngest, getEsClientForAPIKey } from '../agents/services'; +import { skipIfNoDockerRegistry } from '../../../helpers'; const ENROLLMENT_KEY_ID = 'ed22ca17-e178-4cfe-8b02-54ea29fbd6d0'; @@ -21,11 +22,14 @@ export default function (providerContext: FtrProviderContext) { before(async () => { await esArchiver.loadIfNeeded('fleet/agents'); }); - setupIngest({ getService } as FtrProviderContext); + after(async () => { await esArchiver.unload('fleet/agents'); }); + skipIfNoDockerRegistry(providerContext); + setupIngest(providerContext); + describe('GET /fleet/enrollment-api-keys', async () => { it('should list existing api keys', async () => { const { body: apiResponse } = await supertest diff --git a/x-pack/test/api_integration/apis/fleet/index.js b/x-pack/test/ingest_manager_api_integration/apis/fleet/index.js similarity index 77% rename from x-pack/test/api_integration/apis/fleet/index.js rename to x-pack/test/ingest_manager_api_integration/apis/fleet/index.js index df81b826132a9..3a72fe6d9f12b 100644 --- a/x-pack/test/api_integration/apis/fleet/index.js +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/index.js @@ -7,16 +7,16 @@ export default function loadTests({ loadTestFile }) { describe('Fleet Endpoints', () => { loadTestFile(require.resolve('./setup')); - loadTestFile(require.resolve('./delete_agent')); - loadTestFile(require.resolve('./list_agent')); - loadTestFile(require.resolve('./unenroll_agent')); + loadTestFile(require.resolve('./agents/delete')); + loadTestFile(require.resolve('./agents/list')); loadTestFile(require.resolve('./agents/enroll')); + loadTestFile(require.resolve('./agents/unenroll')); loadTestFile(require.resolve('./agents/checkin')); loadTestFile(require.resolve('./agents/events')); loadTestFile(require.resolve('./agents/acks')); + loadTestFile(require.resolve('./agents/complete_flow')); loadTestFile(require.resolve('./enrollment_api_keys/crud')); loadTestFile(require.resolve('./install')); loadTestFile(require.resolve('./agents/actions')); - loadTestFile(require.resolve('./agent_flow')); }); } diff --git a/x-pack/test/api_integration/apis/fleet/install.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/install.ts similarity index 92% rename from x-pack/test/api_integration/apis/fleet/install.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/install.ts index 59b040e30fb48..98758ae3ac65e 100644 --- a/x-pack/test/api_integration/apis/fleet/install.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/install.ts @@ -5,7 +5,7 @@ */ import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../ftr_provider_context'; +import { FtrProviderContext } from '../../../api_integration/ftr_provider_context'; import { setupIngest } from './agents/services'; export default function (providerContext: FtrProviderContext) { diff --git a/x-pack/test/api_integration/apis/fleet/setup.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/setup.ts similarity index 92% rename from x-pack/test/api_integration/apis/fleet/setup.ts rename to x-pack/test/ingest_manager_api_integration/apis/fleet/setup.ts index 4fcf39886e202..64c014dc6fb3d 100644 --- a/x-pack/test/api_integration/apis/fleet/setup.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/setup.ts @@ -5,13 +5,16 @@ */ import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../ftr_provider_context'; +import { FtrProviderContext } from '../../../api_integration/ftr_provider_context'; +import { skipIfNoDockerRegistry } from '../../helpers'; -export default function ({ getService }: FtrProviderContext) { +export default function (providerContext: FtrProviderContext) { + const { getService } = providerContext; const supertest = getService('supertest'); const es = getService('es'); describe('fleet_setup', () => { + skipIfNoDockerRegistry(providerContext); beforeEach(async () => { try { await es.security.deleteUser({ diff --git a/x-pack/test/ingest_manager_api_integration/apis/index.js b/x-pack/test/ingest_manager_api_integration/apis/index.js index 81848917f9b05..d21b80bd6eed7 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/index.js +++ b/x-pack/test/ingest_manager_api_integration/apis/index.js @@ -8,15 +8,22 @@ export default function ({ loadTestFile }) { describe('Ingest Manager Endpoints', function () { this.tags('ciGroup7'); + // Fleet + loadTestFile(require.resolve('./fleet/index')); + // EPM loadTestFile(require.resolve('./epm/list')); loadTestFile(require.resolve('./epm/file')); //loadTestFile(require.resolve('./epm/template')); loadTestFile(require.resolve('./epm/ilm')); - loadTestFile(require.resolve('./epm/install')); + loadTestFile(require.resolve('./epm/install_overrides')); + loadTestFile(require.resolve('./epm/install_remove_assets')); // Package configs loadTestFile(require.resolve('./package_config/create')); loadTestFile(require.resolve('./package_config/update')); + loadTestFile(require.resolve('./package_config/get')); + // Agent config + loadTestFile(require.resolve('./agent_config/index')); }); } diff --git a/x-pack/test/ingest_manager_api_integration/apis/package_config/create.ts b/x-pack/test/ingest_manager_api_integration/apis/package_config/create.ts index 27581550ac2bc..cae4ff79bdef6 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/package_config/create.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/package_config/create.ts @@ -18,9 +18,7 @@ export default function ({ getService }: FtrProviderContext) { // because `this` has to point to the Mocha context // see https://mochajs.org/#arrow-functions - // Temporarily skipped to promote snapshot - // Re-enabled in https://github.com/elastic/kibana/pull/71727 - describe.skip('Package Config - create', async function () { + describe('Package Config - create', async function () { let agentConfigId: string; before(async function () { diff --git a/x-pack/test/ingest_manager_api_integration/apis/package_config/get.ts b/x-pack/test/ingest_manager_api_integration/apis/package_config/get.ts new file mode 100644 index 0000000000000..94b7543d982ad --- /dev/null +++ b/x-pack/test/ingest_manager_api_integration/apis/package_config/get.ts @@ -0,0 +1,89 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../api_integration/ftr_provider_context'; +import { skipIfNoDockerRegistry } from '../../helpers'; + +export default function (providerContext: FtrProviderContext) { + const { getService } = providerContext; + const supertest = getService('supertest'); + const dockerServers = getService('dockerServers'); + + const server = dockerServers.get('registry'); + // use function () {} and not () => {} here + // because `this` has to point to the Mocha context + // see https://mochajs.org/#arrow-functions + + describe('Package Config - get by id', async function () { + skipIfNoDockerRegistry(providerContext); + let agentConfigId: string; + let packageConfigId: string; + + before(async function () { + if (!server.enabled) { + return; + } + const { body: agentConfigResponse } = await supertest + .post(`/api/ingest_manager/agent_configs`) + .set('kbn-xsrf', 'xxxx') + .send({ + name: 'Test config', + namespace: 'default', + }); + agentConfigId = agentConfigResponse.item.id; + + const { body: packageConfigResponse } = await supertest + .post(`/api/ingest_manager/package_configs`) + .set('kbn-xsrf', 'xxxx') + .send({ + name: 'filetest-1', + description: '', + namespace: 'default', + config_id: agentConfigId, + enabled: true, + output_id: '', + inputs: [], + package: { + name: 'filetest', + title: 'For File Tests', + version: '0.1.0', + }, + }); + packageConfigId = packageConfigResponse.item.id; + }); + + after(async function () { + if (!server.enabled) { + return; + } + + await supertest + .post(`/api/ingest_manager/agent_configs/delete`) + .set('kbn-xsrf', 'xxxx') + .send({ agentConfigId }) + .expect(200); + + await supertest + .post(`/api/ingest_manager/package_configs/delete`) + .set('kbn-xsrf', 'xxxx') + .send({ packageConfigIds: [packageConfigId] }) + .expect(200); + }); + + it('should succeed with a valid id', async function () { + const { body: apiResponse } = await supertest + .get(`/api/ingest_manager/package_configs/${packageConfigId}`) + .expect(200); + + expect(apiResponse.success).to.be(true); + }); + + it('should return a 404 with an invalid id', async function () { + await supertest.get(`/api/ingest_manager/package_configs/IS_NOT_PRESENT`).expect(404); + }); + }); +} diff --git a/x-pack/test/ingest_manager_api_integration/apis/package_config/update.ts b/x-pack/test/ingest_manager_api_integration/apis/package_config/update.ts index 0251fef5f767c..7b0ad4f524bad 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/package_config/update.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/package_config/update.ts @@ -6,10 +6,10 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../api_integration/ftr_provider_context'; -import { warnAndSkipTest } from '../../helpers'; +import { skipIfNoDockerRegistry } from '../../helpers'; -export default function ({ getService }: FtrProviderContext) { - const log = getService('log'); +export default function (providerContext: FtrProviderContext) { + const { getService } = providerContext; const supertest = getService('supertest'); const dockerServers = getService('dockerServers'); @@ -19,11 +19,15 @@ export default function ({ getService }: FtrProviderContext) { // see https://mochajs.org/#arrow-functions describe('Package Config - update', async function () { + skipIfNoDockerRegistry(providerContext); let agentConfigId: string; let packageConfigId: string; let packageConfigId2: string; before(async function () { + if (!server.enabled) { + return; + } const { body: agentConfigResponse } = await supertest .post(`/api/ingest_manager/agent_configs`) .set('kbn-xsrf', 'xxxx') @@ -73,55 +77,47 @@ export default function ({ getService }: FtrProviderContext) { }); it('should work with valid values', async function () { - if (server.enabled) { - const { body: apiResponse } = await supertest - .put(`/api/ingest_manager/package_configs/${packageConfigId}`) - .set('kbn-xsrf', 'xxxx') - .send({ - name: 'filetest-1', - description: '', - namespace: 'updated_namespace', - config_id: agentConfigId, - enabled: true, - output_id: '', - inputs: [], - package: { - name: 'filetest', - title: 'For File Tests', - version: '0.1.0', - }, - }) - .expect(200); + const { body: apiResponse } = await supertest + .put(`/api/ingest_manager/package_configs/${packageConfigId}`) + .set('kbn-xsrf', 'xxxx') + .send({ + name: 'filetest-1', + description: '', + namespace: 'updated_namespace', + config_id: agentConfigId, + enabled: true, + output_id: '', + inputs: [], + package: { + name: 'filetest', + title: 'For File Tests', + version: '0.1.0', + }, + }) + .expect(200); - expect(apiResponse.success).to.be(true); - } else { - warnAndSkipTest(this, log); - } + expect(apiResponse.success).to.be(true); }); it('should return a 500 if there is another package config with the same name', async function () { - if (server.enabled) { - await supertest - .put(`/api/ingest_manager/package_configs/${packageConfigId2}`) - .set('kbn-xsrf', 'xxxx') - .send({ - name: 'filetest-1', - description: '', - namespace: 'updated_namespace', - config_id: agentConfigId, - enabled: true, - output_id: '', - inputs: [], - package: { - name: 'filetest', - title: 'For File Tests', - version: '0.1.0', - }, - }) - .expect(500); - } else { - warnAndSkipTest(this, log); - } + await supertest + .put(`/api/ingest_manager/package_configs/${packageConfigId2}`) + .set('kbn-xsrf', 'xxxx') + .send({ + name: 'filetest-1', + description: '', + namespace: 'updated_namespace', + config_id: agentConfigId, + enabled: true, + output_id: '', + inputs: [], + package: { + name: 'filetest', + title: 'For File Tests', + version: '0.1.0', + }, + }) + .expect(500); }); }); } diff --git a/x-pack/test/ingest_manager_api_integration/config.ts b/x-pack/test/ingest_manager_api_integration/config.ts index e3cdf0eff4b3a..ddb49a09a7afa 100644 --- a/x-pack/test/ingest_manager_api_integration/config.ts +++ b/x-pack/test/ingest_manager_api_integration/config.ts @@ -9,6 +9,11 @@ import path from 'path'; import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; import { defineDockerServersConfig } from '@kbn/test'; +// Docker image to use for Ingest Manager API integration tests. +// This hash comes from the commit hash here: https://github.com/elastic/package-storage/commit/48f3935a72b0c5aacc6fec8ef36d559b089a238b +export const dockerImage = + 'docker.elastic.co/package-registry/distribution:48f3935a72b0c5aacc6fec8ef36d559b089a238b'; + export default async function ({ readConfigFile }: FtrConfigProviderContext) { const xPackAPITestsConfig = await readConfigFile(require.resolve('../api_integration/config.ts')); @@ -29,10 +34,6 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { )}:/packages/test-packages`, ]; - // Docker image to use for Ingest Manager API integration tests. - const dockerImage = - 'docker.elastic.co/package-registry/distribution:184b85f19e8fd14363e36150173d338ff9659f01'; - return { testFiles: [require.resolve('./apis')], servers: xPackAPITestsConfig.get('servers'), @@ -46,9 +47,9 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { waitForLogLine: 'package manifests loaded', }, }), + esArchiver: xPackAPITestsConfig.get('esArchiver'), services: { - supertest: xPackAPITestsConfig.get('services.supertest'), - es: xPackAPITestsConfig.get('services.es'), + ...xPackAPITestsConfig.get('services'), }, junit: { reportName: 'X-Pack EPM API Integration Tests', diff --git a/x-pack/test/ingest_manager_api_integration/helpers.ts b/x-pack/test/ingest_manager_api_integration/helpers.ts index 121630249621b..a5ffc4e7adc24 100644 --- a/x-pack/test/ingest_manager_api_integration/helpers.ts +++ b/x-pack/test/ingest_manager_api_integration/helpers.ts @@ -6,6 +6,7 @@ import { Context } from 'mocha'; import { ToolingLog } from '@kbn/dev-utils'; +import { FtrProviderContext } from '../api_integration/ftr_provider_context'; export function warnAndSkipTest(mochaContext: Context, log: ToolingLog) { log.warning( @@ -13,3 +14,17 @@ export function warnAndSkipTest(mochaContext: Context, log: ToolingLog) { ); mochaContext.skip(); } + +export function skipIfNoDockerRegistry(providerContext: FtrProviderContext) { + const { getService } = providerContext; + const dockerServers = getService('dockerServers'); + + const server = dockerServers.get('registry'); + const log = getService('log'); + + beforeEach(function beforeSetupWithDockerRegistry() { + if (!server.enabled) { + warnAndSkipTest(this, log); + } + }); +} diff --git a/x-pack/test/security_solution_cypress/config.ts b/x-pack/test/security_solution_cypress/config.ts index 1ad3a36cc57ae..83290a60a17a6 100644 --- a/x-pack/test/security_solution_cypress/config.ts +++ b/x-pack/test/security_solution_cypress/config.ts @@ -46,8 +46,6 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { '--csp.strict=false', // define custom kibana server args here `--elasticsearch.ssl.certificateAuthorities=${CA_CERT_PATH}`, - '--xpack.ingestManager.enabled=true', - '--xpack.ingestManager.fleet.enabled=true', ], }, }; diff --git a/x-pack/test/security_solution_cypress/es_archives/export_rule/data.json.gz b/x-pack/test/security_solution_cypress/es_archives/export_rule/data.json.gz index 373251d9e4f93..aad07a0bf6d53 100644 Binary files a/x-pack/test/security_solution_cypress/es_archives/export_rule/data.json.gz and b/x-pack/test/security_solution_cypress/es_archives/export_rule/data.json.gz differ diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/endpoint_list.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/endpoint_list.ts index 6971d9f523e7e..85d0e56231643 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/endpoint_list.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/endpoint_list.ts @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; -import { deleteMetadataStream } from '../../../api_integration/apis/endpoint/data_stream_helper'; +import { deleteMetadataStream } from '../../../security_solution_endpoint_api_int/apis/data_stream_helper'; export default ({ getPageObjects, getService }: FtrProviderContext) => { const pageObjects = getPageObjects(['common', 'endpoint', 'header', 'endpointPageUtils']); @@ -36,8 +36,8 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { [ 'Hostname', 'Host Status', - 'Policy', - 'Policy Status', + 'Integration', + 'Configuration Status', 'Operating System', 'IP Address', 'Version', @@ -119,7 +119,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { }); // The integration does not work properly yet. Skipping this test for now. - it.skip('navigates to ingest fleet when the Reassign Policy link is clicked', async () => { + it.skip('navigates to ingest fleet when the Reassign Configuration link is clicked', async () => { await (await testSubjects.find('hostnameCellLink')).click(); await (await testSubjects.find('hostDetailsLinkToIngest')).click(); await testSubjects.existOrFail('fleetAgentListTable'); @@ -145,8 +145,8 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { 'OS', 'Last Seen', 'Alerts', - 'Policy', - 'Policy Status', + 'Integration', + 'Configuration Status', 'IP Address', 'Hostname', 'Sensor Version', diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/index.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/index.ts index bd933c9a136f2..7962ec60ff57e 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/index.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/index.ts @@ -3,17 +3,32 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import { DEFAULT_REGISTRY_URL } from '../../../../plugins/ingest_manager/common'; import { FtrProviderContext } from '../../ftr_provider_context'; +import { + isRegistryEnabled, + getRegistryUrl, +} from '../../../security_solution_endpoint_api_int/registry'; + +export default function (providerContext: FtrProviderContext) { + const { loadTestFile, getService } = providerContext; -export default function ({ loadTestFile, getService }: FtrProviderContext) { describe('endpoint', function () { this.tags('ciGroup7'); const ingestManager = getService('ingestManager'); + const log = getService('log'); + + if (!isRegistryEnabled()) { + log.warning('These tests are being run with an external package registry'); + } + + const registryUrl = getRegistryUrl() ?? DEFAULT_REGISTRY_URL; + log.info(`Package registry URL for tests: ${registryUrl}`); + before(async () => { await ingestManager.setup(); }); loadTestFile(require.resolve('./endpoint_list')); - loadTestFile(require.resolve('./policy_list')); loadTestFile(require.resolve('./policy_details')); }); } diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts index cf76f297d83be..d4947222a6cc0 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts @@ -27,7 +27,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await pageObjects.policy.navigateToPolicyDetails('invalid-id'); await testSubjects.existOrFail('policyDetailsIdNotFoundMessage'); expect(await testSubjects.getVisibleText('policyDetailsIdNotFoundMessage')).to.equal( - 'Saved object [ingest-package-configs/invalid-id] not found' + 'Package config invalid-id not found' ); }); }); @@ -73,7 +73,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await testSubjects.existOrFail('policyDetailsSuccessMessage'); expect(await testSubjects.getVisibleText('policyDetailsSuccessMessage')).to.equal( - `Policy ${policyInfo.packageConfig.name} has been updated.` + `Integration ${policyInfo.packageConfig.name} has been updated.` ); }); it('should persist update on the screen', async () => { @@ -81,7 +81,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await pageObjects.policy.confirmAndSave(); await testSubjects.existOrFail('policyDetailsSuccessMessage'); - await pageObjects.policy.navigateToPolicyList(); + await pageObjects.endpoint.navigateToHostList(); await pageObjects.policy.navigateToPolicyDetails(policyInfo.packageConfig.id); expect(await (await testSubjects.find('policyWindowsEvent_process')).isSelected()).to.equal( @@ -118,18 +118,6 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }, artifact_manifest: { artifacts: { - 'endpoint-exceptionlist-linux-v1': { - compression_algorithm: 'zlib', - decoded_sha256: - 'd801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658', - decoded_size: 14, - encoded_sha256: - 'f8e6afa1d5662f5b37f83337af774b5785b5b7f1daee08b7b00c2d6813874cda', - encoded_size: 22, - encryption_algorithm: 'none', - relative_url: - '/api/endpoint/artifacts/download/endpoint-exceptionlist-linux-v1/d801aa1fb7ddcc330a5e3173372ea6af4a3d08ec58074478e85aa5603e926658', - }, 'endpoint-exceptionlist-macos-v1': { compression_algorithm: 'zlib', decoded_sha256: diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts index 57321ab4cd911..0c5e15ed4104c 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts @@ -78,7 +78,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { 'Protect East Coastrev. 1', 'elastic', 'elastic', - `${policyInfo.packageConfig.package?.title} v${policyInfo.packageConfig.package?.version}`, + `v${policyInfo.packageConfig.package?.version}`, '', ]); [policyRow[2], policyRow[4]].forEach((relativeDate) => { @@ -131,6 +131,11 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { expect(endpointConfig).not.to.be(undefined); }); + it('should have empty value for package configuration name', async () => { + await pageObjects.ingestManagerCreatePackageConfig.selectAgentConfig(); + expect(await pageObjects.ingestManagerCreatePackageConfig.getPackageConfigName()).to.be(''); + }); + it('should redirect user back to Policy List after a successful save', async () => { const newPolicyName = `endpoint policy ${Date.now()}`; await pageObjects.ingestManagerCreatePackageConfig.selectAgentConfig(); diff --git a/x-pack/test/security_solution_endpoint/config.ts b/x-pack/test/security_solution_endpoint/config.ts index 2d94163fa1018..5aa5e42ffd4ee 100644 --- a/x-pack/test/security_solution_endpoint/config.ts +++ b/x-pack/test/security_solution_endpoint/config.ts @@ -8,6 +8,10 @@ import { resolve } from 'path'; import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; import { pageObjects } from './page_objects'; import { services } from './services'; +import { + getRegistryUrlAsArray, + createEndpointDockerConfig, +} from '../security_solution_endpoint_api_int/registry'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const xpackFunctionalConfig = await readConfigFile(require.resolve('../functional/config.js')); @@ -16,6 +20,7 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { ...xpackFunctionalConfig.getAll(), pageObjects, testFiles: [resolve(__dirname, './apps/endpoint')], + dockerServers: createEndpointDockerConfig(), junit: { reportName: 'X-Pack Endpoint Functional Tests', }, @@ -31,6 +36,8 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { serverArgs: [ ...xpackFunctionalConfig.get('kbnTestServer.serverArgs'), '--xpack.ingestManager.enabled=true', + // if you return an empty string here the kibana server will not start properly but an empty array works + ...getRegistryUrlAsArray(), ], }, }; diff --git a/x-pack/test/security_solution_endpoint/page_objects/ingest_manager_create_package_config_page.ts b/x-pack/test/security_solution_endpoint/page_objects/ingest_manager_create_package_config_page.ts index dd3fc637a3d6c..dfdb528b7362c 100644 --- a/x-pack/test/security_solution_endpoint/page_objects/ingest_manager_create_package_config_page.ts +++ b/x-pack/test/security_solution_endpoint/page_objects/ingest_manager_create_package_config_page.ts @@ -62,6 +62,13 @@ export function IngestManagerCreatePackageConfig({ } }, + /** + * Returns the package config name currently populated on the input field + */ + async getPackageConfigName() { + return testSubjects.getAttribute('packageConfigNameInput', 'value'); + }, + /** * Set the name of the package config on the input field * @param name diff --git a/x-pack/test/api_integration/apis/endpoint/artifacts/index.ts b/x-pack/test/security_solution_endpoint_api_int/apis/artifacts/index.ts similarity index 80% rename from x-pack/test/api_integration/apis/endpoint/artifacts/index.ts rename to x-pack/test/security_solution_endpoint_api_int/apis/artifacts/index.ts index ba68b9b7ba6ee..d5106f5549924 100644 --- a/x-pack/test/api_integration/apis/endpoint/artifacts/index.ts +++ b/x-pack/test/security_solution_endpoint_api_int/apis/artifacts/index.ts @@ -8,8 +8,8 @@ import expect from '@kbn/expect'; import { createHash } from 'crypto'; import { inflateSync } from 'zlib'; -import { FtrProviderContext } from '../../../ftr_provider_context'; -import { getSupertestWithoutAuth, setupIngest } from '../../fleet/agents/services'; +import { FtrProviderContext } from '../../../api_integration/ftr_provider_context'; +import { getSupertestWithoutAuth } from '../../../ingest_manager_api_integration/apis/fleet/agents/services'; export default function (providerContext: FtrProviderContext) { const { getService } = providerContext; @@ -19,7 +19,6 @@ export default function (providerContext: FtrProviderContext) { let agentAccessAPIKey: string; describe('artifact download', () => { - setupIngest(providerContext); before(async () => { await esArchiver.load('endpoint/artifacts/api_feature', { useCreate: true }); @@ -84,24 +83,24 @@ export default function (providerContext: FtrProviderContext) { it('should download an artifact with list items', async () => { await supertestWithoutAuth .get( - '/api/endpoint/artifacts/download/endpoint-exceptionlist-linux-v1/d2a9c760005b08d43394e59a8701ae75c80881934ccf15a006944452b80f7f9f' + '/api/endpoint/artifacts/download/endpoint-exceptionlist-windows-v1/8d2bcc37e82fad5d06e2c9e4bd96793ea8905ace1d528a57d0d0579ecc8c647e' ) .set('kbn-xsrf', 'xxx') .set('authorization', `ApiKey ${agentAccessAPIKey}`) .send() .expect(200) .expect((response) => { - expect(response.body.byteLength).to.equal(160); + expect(response.body.byteLength).to.equal(191); const encodedHash = createHash('sha256').update(response.body).digest('hex'); expect(encodedHash).to.equal( - '5caaeabcb7864d47157fc7c28d5a7398b4f6bbaaa565d789c02ee809253b7613' + '73015ee5131dabd1b48aa4776d3e766d836f8dd8c9fa8999c9b931f60027f07f' ); const decodedBody = inflateSync(response.body); const decodedHash = createHash('sha256').update(decodedBody).digest('hex'); expect(decodedHash).to.equal( - 'd2a9c760005b08d43394e59a8701ae75c80881934ccf15a006944452b80f7f9f' + '8d2bcc37e82fad5d06e2c9e4bd96793ea8905ace1d528a57d0d0579ecc8c647e' ); - expect(decodedBody.byteLength).to.equal(358); + expect(decodedBody.byteLength).to.equal(704); const artifactJson = JSON.parse(decodedBody.toString()); expect(artifactJson).to.eql({ entries: [ @@ -114,6 +113,35 @@ export default function (providerContext: FtrProviderContext) { type: 'exact_cased', value: 'Elastic, N.V.', }, + { + entries: [ + { + field: 'signer', + operator: 'included', + type: 'exact_cased', + value: '😈', + }, + { + field: 'trusted', + operator: 'included', + type: 'exact_cased', + value: 'true', + }, + ], + field: 'file.signature', + type: 'nested', + }, + ], + }, + { + type: 'simple', + entries: [ + { + field: 'actingProcess.file.signer', + operator: 'included', + type: 'exact_cased', + value: 'Another signer', + }, { entries: [ { @@ -281,7 +309,7 @@ export default function (providerContext: FtrProviderContext) { it('should download an artifact from cache', async () => { await supertestWithoutAuth .get( - '/api/endpoint/artifacts/download/endpoint-exceptionlist-linux-v1/d2a9c760005b08d43394e59a8701ae75c80881934ccf15a006944452b80f7f9f' + '/api/endpoint/artifacts/download/endpoint-exceptionlist-windows-v1/8d2bcc37e82fad5d06e2c9e4bd96793ea8905ace1d528a57d0d0579ecc8c647e' ) .set('kbn-xsrf', 'xxx') .set('authorization', `ApiKey ${agentAccessAPIKey}`) @@ -293,22 +321,24 @@ export default function (providerContext: FtrProviderContext) { .then(async () => { await supertestWithoutAuth .get( - '/api/endpoint/artifacts/download/endpoint-exceptionlist-linux-v1/d2a9c760005b08d43394e59a8701ae75c80881934ccf15a006944452b80f7f9f' + '/api/endpoint/artifacts/download/endpoint-exceptionlist-windows-v1/8d2bcc37e82fad5d06e2c9e4bd96793ea8905ace1d528a57d0d0579ecc8c647e' ) .set('kbn-xsrf', 'xxx') .set('authorization', `ApiKey ${agentAccessAPIKey}`) .send() .expect(200) .expect((response) => { + expect(response.body.byteLength).to.equal(191); const encodedHash = createHash('sha256').update(response.body).digest('hex'); expect(encodedHash).to.equal( - '5caaeabcb7864d47157fc7c28d5a7398b4f6bbaaa565d789c02ee809253b7613' + '73015ee5131dabd1b48aa4776d3e766d836f8dd8c9fa8999c9b931f60027f07f' ); const decodedBody = inflateSync(response.body); const decodedHash = createHash('sha256').update(decodedBody).digest('hex'); expect(decodedHash).to.equal( - 'd2a9c760005b08d43394e59a8701ae75c80881934ccf15a006944452b80f7f9f' + '8d2bcc37e82fad5d06e2c9e4bd96793ea8905ace1d528a57d0d0579ecc8c647e' ); + expect(decodedBody.byteLength).to.equal(704); const artifactJson = JSON.parse(decodedBody.toString()); expect(artifactJson).to.eql({ entries: [ @@ -321,6 +351,35 @@ export default function (providerContext: FtrProviderContext) { type: 'exact_cased', value: 'Elastic, N.V.', }, + { + entries: [ + { + field: 'signer', + operator: 'included', + type: 'exact_cased', + value: '😈', + }, + { + field: 'trusted', + operator: 'included', + type: 'exact_cased', + value: 'true', + }, + ], + field: 'file.signature', + type: 'nested', + }, + ], + }, + { + type: 'simple', + entries: [ + { + field: 'actingProcess.file.signer', + operator: 'included', + type: 'exact_cased', + value: 'Another signer', + }, { entries: [ { diff --git a/x-pack/test/api_integration/apis/endpoint/data_stream_helper.ts b/x-pack/test/security_solution_endpoint_api_int/apis/data_stream_helper.ts similarity index 94% rename from x-pack/test/api_integration/apis/endpoint/data_stream_helper.ts rename to x-pack/test/security_solution_endpoint_api_int/apis/data_stream_helper.ts index b239ab41e41f1..b16da16b3137f 100644 --- a/x-pack/test/api_integration/apis/endpoint/data_stream_helper.ts +++ b/x-pack/test/security_solution_endpoint_api_int/apis/data_stream_helper.ts @@ -10,7 +10,7 @@ import { eventsIndexPattern, alertsIndexPattern, policyIndexPattern, -} from '../../../../plugins/security_solution/common/endpoint/constants'; +} from '../../../plugins/security_solution/common/endpoint/constants'; export async function deleteDataStream(getService: (serviceName: 'es') => Client, index: string) { const client = getService('es'); diff --git a/x-pack/test/security_solution_endpoint_api_int/apis/fixtures/package_registry_config.yml b/x-pack/test/security_solution_endpoint_api_int/apis/fixtures/package_registry_config.yml new file mode 100644 index 0000000000000..4d93386b4d4e1 --- /dev/null +++ b/x-pack/test/security_solution_endpoint_api_int/apis/fixtures/package_registry_config.yml @@ -0,0 +1,2 @@ +package_paths: + - /packages/production diff --git a/x-pack/test/security_solution_endpoint_api_int/apis/index.ts b/x-pack/test/security_solution_endpoint_api_int/apis/index.ts new file mode 100644 index 0000000000000..56adc2382e234 --- /dev/null +++ b/x-pack/test/security_solution_endpoint_api_int/apis/index.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { FtrProviderContext } from '../ftr_provider_context'; +import { isRegistryEnabled, getRegistryUrl } from '../registry'; +import { DEFAULT_REGISTRY_URL } from '../../../plugins/ingest_manager/common'; + +export default function endpointAPIIntegrationTests(providerContext: FtrProviderContext) { + const { loadTestFile, getService } = providerContext; + + describe('Endpoint plugin', function () { + const ingestManager = getService('ingestManager'); + + this.tags('ciGroup7'); + const log = getService('log'); + + if (!isRegistryEnabled()) { + log.warning('These tests are being run with an external package registry'); + } + + const registryUrl = getRegistryUrl() ?? DEFAULT_REGISTRY_URL; + log.info(`Package registry URL for tests: ${registryUrl}`); + + before(async () => { + await ingestManager.setup(); + }); + loadTestFile(require.resolve('./resolver/entity_id')); + loadTestFile(require.resolve('./resolver/tree')); + loadTestFile(require.resolve('./metadata')); + loadTestFile(require.resolve('./policy')); + loadTestFile(require.resolve('./artifacts')); + }); +} diff --git a/x-pack/test/api_integration/apis/endpoint/metadata.ts b/x-pack/test/security_solution_endpoint_api_int/apis/metadata.ts similarity index 99% rename from x-pack/test/api_integration/apis/endpoint/metadata.ts rename to x-pack/test/security_solution_endpoint_api_int/apis/metadata.ts index 41531269ddeb9..719327e5f9b79 100644 --- a/x-pack/test/api_integration/apis/endpoint/metadata.ts +++ b/x-pack/test/security_solution_endpoint_api_int/apis/metadata.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import expect from '@kbn/expect/expect.js'; -import { FtrProviderContext } from '../../ftr_provider_context'; +import { FtrProviderContext } from '../ftr_provider_context'; import { deleteMetadataStream } from './data_stream_helper'; /** diff --git a/x-pack/test/api_integration/apis/endpoint/policy.ts b/x-pack/test/security_solution_endpoint_api_int/apis/policy.ts similarity index 96% rename from x-pack/test/api_integration/apis/endpoint/policy.ts rename to x-pack/test/security_solution_endpoint_api_int/apis/policy.ts index e33423d172567..66bcc0e759916 100644 --- a/x-pack/test/api_integration/apis/endpoint/policy.ts +++ b/x-pack/test/security_solution_endpoint_api_int/apis/policy.ts @@ -5,7 +5,7 @@ */ import expect from '@kbn/expect/expect.js'; -import { FtrProviderContext } from '../../ftr_provider_context'; +import { FtrProviderContext } from '../ftr_provider_context'; import { deletePolicyStream } from './data_stream_helper'; export default function ({ getService }: FtrProviderContext) { diff --git a/x-pack/test/security_solution_endpoint_api_int/apis/resolver/entity_id.ts b/x-pack/test/security_solution_endpoint_api_int/apis/resolver/entity_id.ts new file mode 100644 index 0000000000000..4f2a801377204 --- /dev/null +++ b/x-pack/test/security_solution_endpoint_api_int/apis/resolver/entity_id.ts @@ -0,0 +1,156 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import expect from '@kbn/expect'; +import { SearchResponse } from 'elasticsearch'; +import { eventsIndexPattern } from '../../../../plugins/security_solution/common/endpoint/constants'; +import { + ResolverTree, + ResolverEntityIndex, +} from '../../../../plugins/security_solution/common/endpoint/types'; +import { FtrProviderContext } from '../../ftr_provider_context'; +import { + EndpointDocGenerator, + Event, +} from '../../../../plugins/security_solution/common/endpoint/generate_data'; +import { InsertedEvents } from '../../services/resolver'; + +export default function resolverAPIIntegrationTests({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const resolver = getService('resolverGenerator'); + const es = getService('es'); + const generator = new EndpointDocGenerator('resolver'); + + describe('Resolver handling of entity ids', () => { + describe('entity api', () => { + let origin: Event; + let genData: InsertedEvents; + before(async () => { + origin = generator.generateEvent({ parentEntityID: 'a' }); + origin.process.entity_id = ''; + genData = await resolver.insertEvents([origin]); + }); + + after(async () => { + await resolver.deleteData(genData); + }); + + it('excludes events that have an empty entity_id field', async () => { + // first lets get the _id of the document using the parent.process.entity_id + // then we'll use the API to search for that specific document + const res = await es.search>({ + index: genData.indices[0], + body: { + query: { + bool: { + filter: [ + { + term: { 'process.parent.entity_id': origin.process.parent!.entity_id }, + }, + ], + }, + }, + }, + }); + const { body }: { body: ResolverEntityIndex } = await supertest.get( + // using the same indices value here twice to force the query parameter to be an array + // for some reason using supertest's query() function doesn't construct a parsable array + `/api/endpoint/resolver/entity?_id=${res.body.hits.hits[0]._id}&indices=${eventsIndexPattern}&indices=${eventsIndexPattern}` + ); + expect(body).to.be.empty(); + }); + }); + + describe('children', () => { + let origin: Event; + let childNoEntityID: Event; + let childWithEntityID: Event; + let events: Event[]; + let genData: InsertedEvents; + + before(async () => { + // construct a tree with an origin and two direct children. One child will not have an entity_id. That child + // should not be returned by the backend. + origin = generator.generateEvent({ entityID: 'a' }); + childNoEntityID = generator.generateEvent({ + parentEntityID: origin.process.entity_id, + ancestry: [origin.process.entity_id], + }); + // force it to be empty + childNoEntityID.process.entity_id = ''; + + childWithEntityID = generator.generateEvent({ + entityID: 'b', + parentEntityID: origin.process.entity_id, + ancestry: [origin.process.entity_id], + }); + events = [origin, childNoEntityID, childWithEntityID]; + genData = await resolver.insertEvents(events); + }); + + after(async () => { + await resolver.deleteData(genData); + }); + + it('does not find children without a process entity_id', async () => { + const { body }: { body: ResolverTree } = await supertest + .get(`/api/endpoint/resolver/${origin.process.entity_id}`) + .expect(200); + expect(body.children.childNodes.length).to.be(1); + expect(body.children.childNodes[0].entityID).to.be(childWithEntityID.process.entity_id); + }); + }); + + describe('ancestors', () => { + let origin: Event; + let ancestor1: Event; + let ancestor2: Event; + let ancestorNoEntityID: Event; + let events: Event[]; + let genData: InsertedEvents; + + before(async () => { + // construct a tree with an origin that has two ancestors. The origin will have an empty string as one of the + // entity_ids in the ancestry array. This is to make sure that the backend will not query for that event. + ancestor2 = generator.generateEvent({ + entityID: '2', + }); + ancestor1 = generator.generateEvent({ + entityID: '1', + parentEntityID: ancestor2.process.entity_id, + ancestry: [ancestor2.process.entity_id], + }); + + // we'll insert an event that doesn't have an entity id so if the backend does search for it, it should be + // returned and our test should fail + ancestorNoEntityID = generator.generateEvent({ + ancestry: [ancestor2.process.entity_id], + }); + ancestorNoEntityID.process.entity_id = ''; + + origin = generator.generateEvent({ + entityID: 'a', + parentEntityID: ancestor1.process.entity_id, + ancestry: ['', ancestor2.process.entity_id], + }); + + events = [origin, ancestor1, ancestor2, ancestorNoEntityID]; + genData = await resolver.insertEvents(events); + }); + + after(async () => { + await resolver.deleteData(genData); + }); + + it('does not query for ancestors that have an empty string for the entity_id', async () => { + const { body }: { body: ResolverTree } = await supertest + .get(`/api/endpoint/resolver/${origin.process.entity_id}`) + .expect(200); + expect(body.ancestry.ancestors.length).to.be(1); + expect(body.ancestry.ancestors[0].entityID).to.be(ancestor2.process.entity_id); + }); + }); + }); +} diff --git a/x-pack/test/api_integration/apis/endpoint/resolver.ts b/x-pack/test/security_solution_endpoint_api_int/apis/resolver/tree.ts similarity index 99% rename from x-pack/test/api_integration/apis/endpoint/resolver.ts rename to x-pack/test/security_solution_endpoint_api_int/apis/resolver/tree.ts index fa980aed30502..3527e7e575c99 100644 --- a/x-pack/test/api_integration/apis/endpoint/resolver.ts +++ b/x-pack/test/security_solution_endpoint_api_int/apis/resolver/tree.ts @@ -256,7 +256,7 @@ export default function resolverAPIIntegrationTests({ getService }: FtrProviderC ancestryArraySize: 2, }; - describe('Resolver', () => { + describe('Resolver tree', () => { before(async () => { await esArchiver.load('endpoint/resolver/api_feature'); resolverTrees = await resolver.createTrees(treeOptions); @@ -264,7 +264,7 @@ export default function resolverAPIIntegrationTests({ getService }: FtrProviderC tree = resolverTrees.trees[0]; }); after(async () => { - await resolver.deleteTrees(resolverTrees); + await resolver.deleteData(resolverTrees); // this unload is for an endgame-* index so it does not use data streams await esArchiver.unload('endpoint/resolver/api_feature'); }); diff --git a/x-pack/test/security_solution_endpoint_api_int/config.ts b/x-pack/test/security_solution_endpoint_api_int/config.ts new file mode 100644 index 0000000000000..726059a8d73fe --- /dev/null +++ b/x-pack/test/security_solution_endpoint_api_int/config.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { createEndpointDockerConfig, getRegistryUrlAsArray } from './registry'; +import { services } from './services'; + +export default async function ({ readConfigFile }: FtrConfigProviderContext) { + const xPackAPITestsConfig = await readConfigFile(require.resolve('../api_integration/config.ts')); + + return { + ...xPackAPITestsConfig.getAll(), + testFiles: [require.resolve('./apis')], + dockerServers: createEndpointDockerConfig(), + services, + junit: { + reportName: 'X-Pack Endpoint API Integration Tests', + }, + kbnTestServer: { + ...xPackAPITestsConfig.get('kbnTestServer'), + serverArgs: [ + ...xPackAPITestsConfig.get('kbnTestServer.serverArgs'), + // if you return an empty string here the kibana server will not start properly but an empty array works + ...getRegistryUrlAsArray(), + ], + }, + }; +} diff --git a/x-pack/plugins/canvas/public/components/arg_add/index.js b/x-pack/test/security_solution_endpoint_api_int/ftr_provider_context.d.ts similarity index 56% rename from x-pack/plugins/canvas/public/components/arg_add/index.js rename to x-pack/test/security_solution_endpoint_api_int/ftr_provider_context.d.ts index 9a89a48edcef6..e3add3748f56d 100644 --- a/x-pack/plugins/canvas/public/components/arg_add/index.js +++ b/x-pack/test/security_solution_endpoint_api_int/ftr_provider_context.d.ts @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; +import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; -import { ArgAdd as Component } from './arg_add'; +import { services } from './services'; -export const ArgAdd = pure(Component); +export type FtrProviderContext = GenericFtrProviderContext; diff --git a/x-pack/test/security_solution_endpoint_api_int/registry.ts b/x-pack/test/security_solution_endpoint_api_int/registry.ts new file mode 100644 index 0000000000000..cc474cbf29aaf --- /dev/null +++ b/x-pack/test/security_solution_endpoint_api_int/registry.ts @@ -0,0 +1,77 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import path from 'path'; + +import { defineDockerServersConfig } from '@kbn/test'; +import { dockerImage as ingestDockerImage } from '../ingest_manager_api_integration/config'; + +/** + * This is used by CI to set the docker registry port + * you can also define this environment variable locally when running tests which + * will spin up a local docker package registry locally for you + * if this is defined it takes precedence over the `packageRegistryOverride` variable + */ +const dockerRegistryPort: string | undefined = process.env.INGEST_MANAGEMENT_PACKAGE_REGISTRY_PORT; + +/** + * If you don't want to use the docker image version pinned below and instead want to run your own + * registry or use an external registry you can define this environment variable when running + * the tests to use that registry url instead. + * + * This is particularly useful when a developer needs to test a new package against the kibana + * integration or functional tests. Instead of having to publish a whole new docker image we + * can set this environment variable which will point to the location of where your package registry + * is serving the updated package. + * + * This variable will not and should not be used by CI. CI should always use the pinned docker image below. + */ +const packageRegistryOverride: string | undefined = process.env.PACKAGE_REGISTRY_URL_OVERRIDE; + +const defaultRegistryConfigPath = path.join( + __dirname, + './apis/fixtures/package_registry_config.yml' +); + +export function createEndpointDockerConfig( + packageRegistryConfig: string = defaultRegistryConfigPath, + dockerImage: string = ingestDockerImage, + dockerArgs: string[] = [] +) { + const args: string[] = [ + '-v', + `${packageRegistryConfig}:/package-registry/config.yml`, + ...dockerArgs, + ]; + return defineDockerServersConfig({ + registry: { + enabled: !!dockerRegistryPort, + image: dockerImage, + portInContainer: 8080, + port: dockerRegistryPort, + args, + waitForLogLine: 'package manifests loaded', + }, + }); +} + +export function getRegistryUrl(): string | undefined { + let registryUrl: string | undefined; + if (dockerRegistryPort !== undefined) { + registryUrl = `--xpack.ingestManager.registryUrl=http://localhost:${dockerRegistryPort}`; + } else if (packageRegistryOverride !== undefined) { + registryUrl = `--xpack.ingestManager.registryUrl=${packageRegistryOverride}`; + } + return registryUrl; +} + +export function getRegistryUrlAsArray(): string[] { + const registryUrl: string | undefined = getRegistryUrl(); + return registryUrl !== undefined ? [registryUrl] : []; +} + +export function isRegistryEnabled() { + return getRegistryUrl() !== undefined; +} diff --git a/x-pack/test/security_solution_endpoint_api_int/services/index.ts b/x-pack/test/security_solution_endpoint_api_int/services/index.ts new file mode 100644 index 0000000000000..47d45557022d3 --- /dev/null +++ b/x-pack/test/security_solution_endpoint_api_int/services/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { services as xPackAPIServices } from '../../api_integration/services'; +import { ResolverGeneratorProvider } from './resolver'; + +export const services = { + ...xPackAPIServices, + resolverGenerator: ResolverGeneratorProvider, +}; diff --git a/x-pack/test/api_integration/services/resolver.ts b/x-pack/test/security_solution_endpoint_api_int/services/resolver.ts similarity index 53% rename from x-pack/test/api_integration/services/resolver.ts rename to x-pack/test/security_solution_endpoint_api_int/services/resolver.ts index 7f568a2b00314..335689b804d5b 100644 --- a/x-pack/test/api_integration/services/resolver.ts +++ b/x-pack/test/security_solution_endpoint_api_int/services/resolver.ts @@ -7,9 +7,12 @@ import { TreeOptions, Tree, EndpointDocGenerator, + Event, } from '../../../plugins/security_solution/common/endpoint/generate_data'; import { FtrProviderContext } from '../ftr_provider_context'; +const processIndex = 'logs-endpoint.events.process-default'; + /** * Options for build a resolver tree */ @@ -26,17 +29,41 @@ export interface Options extends TreeOptions { */ export interface GeneratedTrees { trees: Tree[]; - eventsIndex: string; - alertsIndex: string; + indices: string[]; +} + +/** + * Structure containing the events inserted into ES and the index they live in + */ +export interface InsertedEvents { + events: Event[]; + indices: string[]; +} + +interface BulkCreateHeader { + create: { + _index: string; + }; } export function ResolverGeneratorProvider({ getService }: FtrProviderContext) { const client = getService('es'); return { + async insertEvents( + events: Event[], + eventsIndex: string = processIndex + ): Promise { + const body = events.reduce((array: Array, doc) => { + array.push({ create: { _index: eventsIndex } }, doc); + return array; + }, []); + await client.bulk({ body, refresh: true }); + return { events, indices: [eventsIndex] }; + }, async createTrees( options: Options, - eventsIndex: string = 'logs-endpoint.events.process-default', + eventsIndex: string = processIndex, alertsIndex: string = 'logs-endpoint.alerts-default' ): Promise { const seed = options.seed || 'resolver-seed'; @@ -45,7 +72,7 @@ export function ResolverGeneratorProvider({ getService }: FtrProviderContext) { const numTrees = options.numTrees ?? 1; for (let j = 0; j < numTrees; j++) { const tree = generator.generateTree(options); - const body = tree.allEvents.reduce((array: Array>, doc) => { + const body = tree.allEvents.reduce((array: Array, doc) => { let index = eventsIndex; if (doc.event.kind === 'alert') { index = alertsIndex; @@ -60,23 +87,21 @@ export function ResolverGeneratorProvider({ getService }: FtrProviderContext) { await client.bulk({ body, refresh: true }); allTrees.push(tree); } - return { trees: allTrees, eventsIndex, alertsIndex }; + return { trees: allTrees, indices: [eventsIndex, alertsIndex] }; }, - async deleteTrees(trees: GeneratedTrees) { - /** - * The ingest manager handles creating the template for the endpoint's indices. It is using a V2 template - * with data streams. Data streams aren't included in the javascript elasticsearch client in kibana yet so we - * need to do raw requests here. Delete a data stream is slightly different than that of a regular index which - * is why we're using _data_stream here. - */ - await client.transport.request({ - method: 'DELETE', - path: `_data_stream/${trees.eventsIndex}`, - }); - await client.transport.request({ - method: 'DELETE', - path: `_data_stream/${trees.alertsIndex}`, - }); + async deleteData(genData: { indices: string[] }) { + for (const index of genData.indices) { + /** + * The ingest manager handles creating the template for the endpoint's indices. It is using a V2 template + * with data streams. Data streams aren't included in the javascript elasticsearch client in kibana yet so we + * need to do raw requests here. Delete a data stream is slightly different than that of a regular index which + * is why we're using _data_stream here. + */ + await client.transport.request({ + method: 'DELETE', + path: `_data_stream/${index}`, + }); + } }, }; } diff --git a/x-pack/test/spaces_api_integration/common/suites/copy_to_space.ts b/x-pack/test/spaces_api_integration/common/suites/copy_to_space.ts index ebec70793e8fd..2dd4484ffcde8 100644 --- a/x-pack/test/spaces_api_integration/common/suites/copy_to_space.ts +++ b/x-pack/test/spaces_api_integration/common/suites/copy_to_space.ts @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; import { SuperTest } from 'supertest'; -import { EsArchiver } from 'src/es_archiver'; +import { EsArchiver } from '@kbn/es-archiver'; import { DEFAULT_SPACE_ID } from '../../../../plugins/spaces/common/constants'; import { CopyResponse } from '../../../../plugins/spaces/server/lib/copy_to_spaces'; import { getUrlPrefix } from '../lib/space_test_utils'; diff --git a/x-pack/test/spaces_api_integration/common/suites/resolve_copy_to_space_conflicts.ts b/x-pack/test/spaces_api_integration/common/suites/resolve_copy_to_space_conflicts.ts index 3529d8f3ae9c9..6d80688b7a703 100644 --- a/x-pack/test/spaces_api_integration/common/suites/resolve_copy_to_space_conflicts.ts +++ b/x-pack/test/spaces_api_integration/common/suites/resolve_copy_to_space_conflicts.ts @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; import { SuperTest } from 'supertest'; -import { EsArchiver } from 'src/es_archiver'; +import { EsArchiver } from '@kbn/es-archiver'; import { SavedObject } from 'src/core/server'; import { DEFAULT_SPACE_ID } from '../../../../plugins/spaces/common/constants'; import { CopyResponse } from '../../../../plugins/spaces/server/lib/copy_to_spaces'; diff --git a/x-pack/test/ui_capabilities/common/features.ts b/x-pack/test/ui_capabilities/common/features.ts index 3c015bc21e937..e3febc945c299 100644 --- a/x-pack/test/ui_capabilities/common/features.ts +++ b/x-pack/test/ui_capabilities/common/features.ts @@ -5,7 +5,7 @@ */ interface Feature { - navLinkId: string; + app: string[]; } export interface Features { diff --git a/x-pack/test/ui_capabilities/common/fixtures/plugins/foo_plugin/server/index.ts b/x-pack/test/ui_capabilities/common/fixtures/plugins/foo_plugin/server/index.ts index bff794801119a..5c80b4283a69b 100644 --- a/x-pack/test/ui_capabilities/common/fixtures/plugins/foo_plugin/server/index.ts +++ b/x-pack/test/ui_capabilities/common/fixtures/plugins/foo_plugin/server/index.ts @@ -19,11 +19,11 @@ class FooPlugin implements Plugin { name: 'Foo', icon: 'upArrow', navLinkId: 'foo_plugin', - app: ['kibana'], + app: ['foo_plugin', 'kibana'], catalogue: ['foo'], privileges: { all: { - app: ['kibana'], + app: ['foo_plugin', 'kibana'], catalogue: ['foo'], savedObject: { all: ['foo'], @@ -32,7 +32,7 @@ class FooPlugin implements Plugin { ui: ['create', 'edit', 'delete', 'show'], }, read: { - app: ['kibana'], + app: ['foo_plugin', 'kibana'], catalogue: ['foo'], savedObject: { all: [], diff --git a/x-pack/test/ui_capabilities/common/nav_links_builder.ts b/x-pack/test/ui_capabilities/common/nav_links_builder.ts index b20a499ba7e20..04ab08e08a2ba 100644 --- a/x-pack/test/ui_capabilities/common/nav_links_builder.ts +++ b/x-pack/test/ui_capabilities/common/nav_links_builder.ts @@ -13,11 +13,14 @@ export class NavLinksBuilder { ...features, // management isn't a first-class "feature", but it makes our life easier here to pretend like it is management: { - navLinkId: 'kibana:stack_management', + app: ['kibana:stack_management'], }, // TODO: Temp until navLinkIds fix is merged in appSearch: { - navLinkId: 'appSearch', + app: ['appSearch', 'workplaceSearch'], + }, + kibana: { + app: ['kibana'], }, }; } @@ -38,9 +41,9 @@ export class NavLinksBuilder { private build(callback: buildCallback): Record { const navLinks = {} as Record; for (const [featureId, feature] of Object.entries(this.features)) { - if (feature.navLinkId) { - navLinks[feature.navLinkId] = callback(featureId); - } + feature.app.forEach((app) => { + navLinks[app] = callback(featureId); + }); } return navLinks; diff --git a/x-pack/test/ui_capabilities/common/services/features.ts b/x-pack/test/ui_capabilities/common/services/features.ts index 0f796c1d0a0cc..5f6ec0ad050c7 100644 --- a/x-pack/test/ui_capabilities/common/services/features.ts +++ b/x-pack/test/ui_capabilities/common/services/features.ts @@ -40,7 +40,7 @@ export class FeaturesService { (acc: Features, feature: any) => ({ ...acc, [feature.id]: { - navLinkId: feature.navLinkId, + app: feature.app, }, }), {} diff --git a/x-pack/test/ui_capabilities/common/services/ui_capabilities.ts b/x-pack/test/ui_capabilities/common/services/ui_capabilities.ts index bb1f3b6eefe4a..7f831973aea5c 100644 --- a/x-pack/test/ui_capabilities/common/services/ui_capabilities.ts +++ b/x-pack/test/ui_capabilities/common/services/ui_capabilities.ts @@ -52,7 +52,7 @@ export class UICapabilitiesService { }): Promise { const features = await this.featureService.get(); const applications = Object.values(features) - .map((feature) => feature.navLinkId) + .flatMap((feature) => feature.app) .filter((link) => !!link); const spaceUrlPrefix = spaceId ? `/s/${spaceId}` : ''; diff --git a/x-pack/test/ui_capabilities/security_only/tests/nav_links.ts b/x-pack/test/ui_capabilities/security_only/tests/nav_links.ts index 18838e536cf96..d7a0dfa1cf80a 100644 --- a/x-pack/test/ui_capabilities/security_only/tests/nav_links.ts +++ b/x-pack/test/ui_capabilities/security_only/tests/nav_links.ts @@ -57,7 +57,7 @@ export default function navLinksTests({ getService }: FtrProviderContext) { expect(uiCapabilities.success).to.be(true); expect(uiCapabilities.value).to.have.property('navLinks'); expect(uiCapabilities.value!.navLinks).to.eql( - navLinksBuilder.only('management', 'foo') + navLinksBuilder.only('management', 'foo', 'kibana') ); break; case 'legacy_all': diff --git a/yarn.lock b/yarn.lock index 4cc802e328ab8..c31f58c3320e2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2767,26 +2767,24 @@ "@types/yargs" "^15.0.0" chalk "^3.0.0" -"@jimp/bmp@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/bmp/-/bmp-0.9.6.tgz#379e261615d7c1f3b52af4d5a0f324666de53d7d" - integrity sha512-T2Fh/k/eN6cDyOx0KQ4y56FMLo8+mKNhBh7GXMQXLK2NNZ0ckpFo3VHDBZ3HnaFeVTZXF/atLiR9CfnXH+rLxA== +"@jimp/bmp@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/bmp/-/bmp-0.14.0.tgz#6df246026554f276f7b354047c6fff9f5b2b5182" + integrity sha512-5RkX6tSS7K3K3xNEb2ygPuvyL9whjanhoaB/WmmXlJS6ub4DjTqrapu8j4qnIWmO4YYtFeTbDTXV6v9P1yMA5A== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" + "@jimp/utils" "^0.14.0" bmp-js "^0.1.0" - core-js "^3.4.1" -"@jimp/core@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/core/-/core-0.9.6.tgz#a553f801bd436526d36e8982b99e58e8afc3d17a" - integrity sha512-sQO04S+HZNid68a9ehb4BC2lmW6iZ5JgU9tC+thC2Lhix+N/XKDJcBJ6HevbLgeTzuIAw24C5EKuUeO3C+rE5w== +"@jimp/core@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/core/-/core-0.14.0.tgz#870c9ca25b40be353ebda1d2abb48723d9010055" + integrity sha512-S62FcKdtLtj3yWsGfJRdFXSutjvHg7aQNiFogMbwq19RP4XJWqS2nOphu7ScB8KrSlyy5nPF2hkWNhLRLyD82w== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" + "@jimp/utils" "^0.14.0" any-base "^1.1.0" buffer "^5.2.0" - core-js "^3.4.1" exif-parser "^0.1.12" file-type "^9.0.0" load-bmfont "^1.3.1" @@ -2795,256 +2793,269 @@ pixelmatch "^4.0.2" tinycolor2 "^1.4.1" -"@jimp/custom@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/custom/-/custom-0.9.6.tgz#3d8a19d6ed717f0f1aa3f1b8f42fa374f43bc715" - integrity sha512-ZYKgrBZVoQwvIGlQSO7MFmn7Jn8a9X5g1g+KOTDO9Q0s4vnxdPTtr/qUjG9QYX6zW/6AK4LaIsDinDrrKDnOag== +"@jimp/custom@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/custom/-/custom-0.14.0.tgz#1dbbf0094df7403f4e03bc984ed92e7458842f74" + integrity sha512-kQJMeH87+kWJdVw8F9GQhtsageqqxrvzg7yyOw3Tx/s7v5RToe8RnKyMM+kVtBJtNAG+Xyv/z01uYQ2jiZ3GwA== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/core" "^0.9.6" - core-js "^3.4.1" + "@jimp/core" "^0.14.0" -"@jimp/gif@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/gif/-/gif-0.9.6.tgz#0a7b1e521daca635b02259f941bdb3600569d8e6" - integrity sha512-Z2muC2On8KHEVrWKCCM0L2eua9kw4bQETzT7gmVsizc8MXAKdS8AyVV9T3ZrImiI0o5UkAN/u0cPi1U2pSiD8Q== +"@jimp/gif@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/gif/-/gif-0.14.0.tgz#db159f57c3cfd1566bbe8b124958791998614960" + integrity sha512-DHjoOSfCaCz72+oGGEh8qH0zE6pUBaBxPxxmpYJjkNyDZP7RkbBkZJScIYeQ7BmJxmGN4/dZn+MxamoQlr+UYg== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" + gifwrap "^0.9.2" omggif "^1.0.9" -"@jimp/jpeg@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/jpeg/-/jpeg-0.9.6.tgz#fb90bdc0111966987c5ba59cdca7040be86ead41" - integrity sha512-igSe0pIX3le/CKdvqW4vLXMxoFjTLjEaW6ZHt/h63OegaEa61TzJ2OM7j7DxrEHcMCMlkhUc9Bapk57MAefCTQ== +"@jimp/jpeg@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/jpeg/-/jpeg-0.14.0.tgz#8a687a6a653bbbae38c522edef8f84bb418d9461" + integrity sha512-561neGbr+87S/YVQYnZSTyjWTHBm9F6F1obYHiyU3wVmF+1CLbxY3FQzt4YolwyQHIBv36Bo0PY2KkkU8BEeeQ== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" - jpeg-js "^0.3.4" + "@jimp/utils" "^0.14.0" + jpeg-js "^0.4.0" -"@jimp/plugin-blit@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-blit/-/plugin-blit-0.9.6.tgz#7937e02e3514b95dbe4c70d444054847f6e9ce3c" - integrity sha512-zp7X6uDU1lCu44RaSY88aAvsSKbgqUrfDyWRX1wsamJvvZpRnp1WekWlGyydRtnlUBAGIpiHCHmyh/TJ2I4RWA== +"@jimp/plugin-blit@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-blit/-/plugin-blit-0.14.0.tgz#5eb374be1201313b2113899fb842232d8fcfd345" + integrity sha512-YoYOrnVHeX3InfgbJawAU601iTZMwEBZkyqcP1V/S33Qnz9uzH1Uj1NtC6fNgWzvX6I4XbCWwtr4RrGFb5CFrw== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-blur@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-blur/-/plugin-blur-0.9.6.tgz#3d74b18c27e9eae11b956ffe26290ece6d250813" - integrity sha512-xEi63hvzewUp7kzw+PI3f9CIrgZbphLI4TDDHWNYuS70RvhTuplbR6RMHD/zFhosrANCkJGr5OZJlrJnsCg6ug== +"@jimp/plugin-blur@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-blur/-/plugin-blur-0.14.0.tgz#fe07e4932d5a2f5d8c9831e245561553224bfc60" + integrity sha512-9WhZcofLrT0hgI7t0chf7iBQZib//0gJh9WcQMUt5+Q1Bk04dWs8vTgLNj61GBqZXgHSPzE4OpCrrLDBG8zlhQ== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-color@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-color/-/plugin-color-0.9.6.tgz#d0fca0ed4c2c48fd6f929ef4a03cebf9c1342e14" - integrity sha512-o1HSoqBVUUAsWbqSXnpiHU0atKWy/Q1GUbZ3F5GWt/0OSDyl9RWM82V9axT2vePZHInKjIaimhnx1gGj8bfxkQ== +"@jimp/plugin-circle@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-circle/-/plugin-circle-0.14.0.tgz#82c0e904a34e90fa672fb9c286bc892e92088ddf" + integrity sha512-o5L+wf6QA44tvTum5HeLyLSc5eVfIUd5ZDVi5iRfO4o6GT/zux9AxuTSkKwnjhsG8bn1dDmywAOQGAx7BjrQVA== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" + +"@jimp/plugin-color@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-color/-/plugin-color-0.14.0.tgz#772bd2d80a88bc66ea1331d010207870f169a74b" + integrity sha512-JJz512SAILYV0M5LzBb9sbOm/XEj2fGElMiHAxb7aLI6jx+n0agxtHpfpV/AePTLm1vzzDxx6AJxXbKv355hBQ== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.14.0" tinycolor2 "^1.4.1" -"@jimp/plugin-contain@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-contain/-/plugin-contain-0.9.6.tgz#7d7bbd5e9c2fa4391a3d63620e13a28f51e1e7e8" - integrity sha512-Xz467EN1I104yranET4ff1ViVKMtwKLg1uRe8j3b5VOrjtiXpDbjirNZjP3HTlv8IEUreWNz4BK7ZtfHSptufA== +"@jimp/plugin-contain@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-contain/-/plugin-contain-0.14.0.tgz#c68115420d182e696f81bbe76fb5e704909b2b6a" + integrity sha512-RX2q233lGyaxiMY6kAgnm9ScmEkNSof0hdlaJAVDS1OgXphGAYAeSIAwzESZN4x3ORaWvkFefeVH9O9/698Evg== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-cover@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-cover/-/plugin-cover-0.9.6.tgz#2853de7f8302f655ae8e95f51ab25a0ed77e3756" - integrity sha512-Ocr27AvtvH4ZT/9EWZgT3+HQV9fG5njwh2CYMHbdpx09O62Asj6pZ4QI0kKzOcux1oLgv59l7a93pEfMOfkfwQ== +"@jimp/plugin-cover@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-cover/-/plugin-cover-0.14.0.tgz#4755322589c5885e44e14e31b86b542e907297ce" + integrity sha512-0P/5XhzWES4uMdvbi3beUgfvhn4YuQ/ny8ijs5kkYIw6K8mHcl820HahuGpwWMx56DJLHRl1hFhJwo9CeTRJtQ== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-crop@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-crop/-/plugin-crop-0.9.6.tgz#82e539af2a2417783abbd143124a57672ff4cc31" - integrity sha512-d9rNdmz3+eYLbSKcTyyp+b8Nmhf6HySnimDXlTej4UP6LDtkq2VAyVaJ12fz9x6dfd8qcXOBXMozSfNCcgpXYA== +"@jimp/plugin-crop@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-crop/-/plugin-crop-0.14.0.tgz#4cbd856ca84ffc37230fad2534906f2f75aa3057" + integrity sha512-Ojtih+XIe6/XSGtpWtbAXBozhCdsDMmy+THUJAGu2x7ZgKrMS0JotN+vN2YC3nwDpYkM+yOJImQeptSfZb2Sug== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-displace@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-displace/-/plugin-displace-0.9.6.tgz#67564d081dc6b19007248ca222d025fd6f90c03b" - integrity sha512-SWpbrxiHmUYBVWtDDMjaG3eRDBASrTPaad7l07t73/+kmU6owAKWQW6KtVs05MYSJgXz7Ggdr0fhEn9AYLH1Rg== +"@jimp/plugin-displace@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-displace/-/plugin-displace-0.14.0.tgz#b0e6a57d00cb1f893f541413fe9d737d23c3b70c" + integrity sha512-c75uQUzMgrHa8vegkgUvgRL/PRvD7paFbFJvzW0Ugs8Wl+CDMGIPYQ3j7IVaQkIS+cAxv+NJ3TIRBQyBrfVEOg== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-dither@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-dither/-/plugin-dither-0.9.6.tgz#dc48669cf51f3933761aa9137e99ebfa000b8cce" - integrity sha512-abm1GjfYK7ru/PoxH9fAUmhl+meHhGEClbVvjjMMe5g2S0BSTvMJl3SrkQD/FMkRLniaS/Qci6aQhIi+8rZmSw== +"@jimp/plugin-dither@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-dither/-/plugin-dither-0.14.0.tgz#9185ec4c38e02edc9e5831f5d709f6ba891e1b93" + integrity sha512-g8SJqFLyYexXQQsoh4dc1VP87TwyOgeTElBcxSXX2LaaMZezypmxQfLTzOFzZoK8m39NuaoH21Ou1Ftsq7LzVQ== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-flip@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-flip/-/plugin-flip-0.9.6.tgz#f81f9b886da8cd56e23dd04d5aa359f2b94f939e" - integrity sha512-KFZTzAzQQ5bct3ii7gysOhWrTKVdUOghkkoSzLi+14nO3uS/dxiu8fPeH1m683ligbdnuM/b22OuLwEwrboTHA== +"@jimp/plugin-fisheye@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-fisheye/-/plugin-fisheye-0.14.0.tgz#9f26346cf2fbc660cc2008cd7fd30a83b5029e78" + integrity sha512-BFfUZ64EikCaABhCA6mR3bsltWhPpS321jpeIQfJyrILdpFsZ/OccNwCgpW1XlbldDHIoNtXTDGn3E+vCE7vDg== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-gaussian@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-gaussian/-/plugin-gaussian-0.9.6.tgz#6c93897ee0ff979466184d7d0ec0fbc95c679be4" - integrity sha512-WXKLtJKWchXfWHT5HIOq1HkPKpbH7xBLWPgVRxw00NV/6I8v4xT63A7/Nag78m00JgjwwiE7eK2tLGDbbrPYig== +"@jimp/plugin-flip@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-flip/-/plugin-flip-0.14.0.tgz#7966d6aa3b5fe1aa4d2d561ff12b8ef5ccb9b071" + integrity sha512-WtL1hj6ryqHhApih+9qZQYA6Ye8a4HAmdTzLbYdTMrrrSUgIzFdiZsD0WeDHpgS/+QMsWwF+NFmTZmxNWqKfXw== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-invert@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-invert/-/plugin-invert-0.9.6.tgz#4b3fa7b81ea976b09b82b3db59ee00ac3093d2fd" - integrity sha512-Pab/cupZrYxeRp07N4L5a4C/3ksTN9k6Knm/o2G5C789OF0rYsGGLcnBR/6h69nPizRZHBYdXCEyXYgujlIFiw== +"@jimp/plugin-gaussian@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-gaussian/-/plugin-gaussian-0.14.0.tgz#452bc1971a4467ad9b984aa67f4c200bf941bb65" + integrity sha512-uaLwQ0XAQoydDlF9tlfc7iD9drYPriFe+jgYnWm8fbw5cN+eOIcnneEX9XCOOzwgLPkNCxGox6Kxjn8zY6GxtQ== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-mask@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-mask/-/plugin-mask-0.9.6.tgz#d70be0030ab3294b191f5b487fb655d776820b19" - integrity sha512-ikypRoDJkbxXlo6gW+EZOcTiLDIt0DrPwOFMt1bvL8UV2QPgX+GJ685IYwhIfEhBf/GSNFgB/NYsVvuSufTGeg== +"@jimp/plugin-invert@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-invert/-/plugin-invert-0.14.0.tgz#cd31a555860e9f821394936d15af161c09c42921" + integrity sha512-UaQW9X9vx8orQXYSjT5VcITkJPwDaHwrBbxxPoDG+F/Zgv4oV9fP+udDD6qmkgI9taU+44Fy+zm/J/gGcMWrdg== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-normalize@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-normalize/-/plugin-normalize-0.9.6.tgz#c9128412a53485d91236a1da241f3166e572be4a" - integrity sha512-V3GeuAJ1NeL7qsLoDjnypJq24RWDCwbXpKhtxB+Yg9zzgOCkmb041p7ysxbcpkuJsRpKLNABZeNCCqd83bRawA== +"@jimp/plugin-mask@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-mask/-/plugin-mask-0.14.0.tgz#52619643ac6222f85e6b27dee33c771ca3a6a4c9" + integrity sha512-tdiGM69OBaKtSPfYSQeflzFhEpoRZ+BvKfDEoivyTjauynbjpRiwB1CaiS8En1INTDwzLXTT0Be9SpI3LkJoEA== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-print@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-print/-/plugin-print-0.9.6.tgz#fea31ffeafee18ae7b5cfd6fa131bb205abfee51" - integrity sha512-gKkqZZPQtMSufHOL0mtJm5d/KI2O6+0kUpOBVSYdGedtPXA61kmVnsOd3wwajIMlXA3E0bDxLXLdAguWqjjGgw== +"@jimp/plugin-normalize@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-normalize/-/plugin-normalize-0.14.0.tgz#bf39e356b6d473f582ce95633ad49c9cdb82492b" + integrity sha512-AfY8sqlsbbdVwFGcyIPy5JH/7fnBzlmuweb+Qtx2vn29okq6+HelLjw2b+VT2btgGUmWWHGEHd86oRGSoWGyEQ== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.14.0" + +"@jimp/plugin-print@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-print/-/plugin-print-0.14.0.tgz#1c43c2a92a7adc05b464863882cb89ce486d63e6" + integrity sha512-MwP3sH+VS5AhhSTXk7pui+tEJFsxnTKFY3TraFJb8WFbA2Vo2qsRCZseEGwpTLhENB7p/JSsLvWoSSbpmxhFAQ== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" load-bmfont "^1.4.0" -"@jimp/plugin-resize@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-resize/-/plugin-resize-0.9.6.tgz#7fb939c8a42e2a3639d661cc7ab24057598693bd" - integrity sha512-r5wJcVII7ZWMuY2l6WSbHPG6gKMFemtCHmJRXGUu+/ZhPGBz3IFluycBpHkWW3OB+jfvuyv1EGQWHU50N1l8Og== +"@jimp/plugin-resize@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-resize/-/plugin-resize-0.14.0.tgz#ef7fc6c2e45f8bcab62456baf8fd3bc415b02b64" + integrity sha512-qFeMOyXE/Bk6QXN0GQo89+CB2dQcXqoxUcDb2Ah8wdYlKqpi53skABkgVy5pW3EpiprDnzNDboMltdvDslNgLQ== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-rotate@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-rotate/-/plugin-rotate-0.9.6.tgz#06d725155e5cdb615133f57a52f5a860a9d03f3e" - integrity sha512-B2nm/eO2nbvn1DgmnzMd79yt3V6kffhRNrKoo2VKcKFiVze1vGP3MD3fVyw5U1PeqwAFu7oTICFnCf9wKDWSqg== +"@jimp/plugin-rotate@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-rotate/-/plugin-rotate-0.14.0.tgz#3632bc159bf1c3b9ec9f459d9c05d02a11781ee7" + integrity sha512-aGaicts44bvpTcq5Dtf93/8TZFu5pMo/61lWWnYmwJJU1RqtQlxbCLEQpMyRhKDNSfPbuP8nyGmaqXlM/82J0Q== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugin-scale@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugin-scale/-/plugin-scale-0.9.6.tgz#3fa939c1a4f44383e12afeb7c434eb41f20e4a1c" - integrity sha512-DLsLB5S3mh9+TZY5ycwfLgOJvUcoS7bP0Mi3I8vE1J91qmA+TXoWFFgrIVgnEPw5jSKzNTt8WhykQ0x2lKXncw== +"@jimp/plugin-scale@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-scale/-/plugin-scale-0.14.0.tgz#d30f0cd1365b8e68f43fa423300ae7f124e9bf10" + integrity sha512-ZcJk0hxY5ZKZDDwflqQNHEGRblgaR+piePZm7dPwPUOSeYEH31P0AwZ1ziceR74zd8N80M0TMft+e3Td6KGBHw== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" -"@jimp/plugins@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/plugins/-/plugins-0.9.6.tgz#a1cfdf9f3e1adf5b124686486343888a16c8fd27" - integrity sha512-eQI29e+K+3L/fb5GbPgsBdoftvaYetSOO2RL5z+Gjk6R4EF4QFRo63YcFl+f72Kc1b0JTOoDxClvn/s5GMV0tg== +"@jimp/plugin-shadow@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-shadow/-/plugin-shadow-0.14.0.tgz#471fdb9f109ff2d9e20d533d45e1e18e0b48c749" + integrity sha512-p2igcEr/iGrLiTu0YePNHyby0WYAXM14c5cECZIVnq/UTOOIQ7xIcWZJ1lRbAEPxVVXPN1UibhZAbr3HAb5BjQ== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.14.0" + +"@jimp/plugin-threshold@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugin-threshold/-/plugin-threshold-0.14.0.tgz#ebd72721c7d1d518c5bb6e494e55d97ac3351d3b" + integrity sha512-N4BlDgm/FoOMV/DQM2rSpzsgqAzkP0DXkWZoqaQrlRxQBo4zizQLzhEL00T/YCCMKnddzgEhnByaocgaaa0fKw== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.14.0" + +"@jimp/plugins@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/plugins/-/plugins-0.14.0.tgz#41dba85f15ab8dadb4162100eb54e5f27b93ee2c" + integrity sha512-vDO3XT/YQlFlFLq5TqNjQkISqjBHT8VMhpWhAfJVwuXIpilxz5Glu4IDLK6jp4IjPR6Yg2WO8TmRY/HI8vLrOw== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/plugin-blit" "^0.9.6" - "@jimp/plugin-blur" "^0.9.6" - "@jimp/plugin-color" "^0.9.6" - "@jimp/plugin-contain" "^0.9.6" - "@jimp/plugin-cover" "^0.9.6" - "@jimp/plugin-crop" "^0.9.6" - "@jimp/plugin-displace" "^0.9.6" - "@jimp/plugin-dither" "^0.9.6" - "@jimp/plugin-flip" "^0.9.6" - "@jimp/plugin-gaussian" "^0.9.6" - "@jimp/plugin-invert" "^0.9.6" - "@jimp/plugin-mask" "^0.9.6" - "@jimp/plugin-normalize" "^0.9.6" - "@jimp/plugin-print" "^0.9.6" - "@jimp/plugin-resize" "^0.9.6" - "@jimp/plugin-rotate" "^0.9.6" - "@jimp/plugin-scale" "^0.9.6" - core-js "^3.4.1" + "@jimp/plugin-blit" "^0.14.0" + "@jimp/plugin-blur" "^0.14.0" + "@jimp/plugin-circle" "^0.14.0" + "@jimp/plugin-color" "^0.14.0" + "@jimp/plugin-contain" "^0.14.0" + "@jimp/plugin-cover" "^0.14.0" + "@jimp/plugin-crop" "^0.14.0" + "@jimp/plugin-displace" "^0.14.0" + "@jimp/plugin-dither" "^0.14.0" + "@jimp/plugin-fisheye" "^0.14.0" + "@jimp/plugin-flip" "^0.14.0" + "@jimp/plugin-gaussian" "^0.14.0" + "@jimp/plugin-invert" "^0.14.0" + "@jimp/plugin-mask" "^0.14.0" + "@jimp/plugin-normalize" "^0.14.0" + "@jimp/plugin-print" "^0.14.0" + "@jimp/plugin-resize" "^0.14.0" + "@jimp/plugin-rotate" "^0.14.0" + "@jimp/plugin-scale" "^0.14.0" + "@jimp/plugin-shadow" "^0.14.0" + "@jimp/plugin-threshold" "^0.14.0" timm "^1.6.1" -"@jimp/png@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/png/-/png-0.9.6.tgz#00ed7e6fb783b94f2f1a9fadf9a42bd75f70cc7f" - integrity sha512-9vhOG2xylcDqPbBf4lzpa2Sa1WNJrEZNGvPvWcM+XVhqYa8+DJBLYkoBlpI/qWIYA+eVWDnLF3ygtGj8CElICw== +"@jimp/png@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/png/-/png-0.14.0.tgz#0f2dddb5125c0795ca7e67c771204c5437fcda4b" + integrity sha512-0RV/mEIDOrPCcNfXSPmPBqqSZYwGADNRVUTyMt47RuZh7sugbYdv/uvKmQSiqRdR0L1sfbCBMWUEa5G/8MSbdA== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/utils" "^0.9.6" - core-js "^3.4.1" + "@jimp/utils" "^0.14.0" pngjs "^3.3.3" -"@jimp/tiff@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/tiff/-/tiff-0.9.6.tgz#9ff12122e727ee15f27f40a710516102a636f66b" - integrity sha512-pKKEMqPzX9ak8mek2iVVoW34+h/TSWUyI4NjbYWJMQ2WExfuvEJvLocy9Q9xi6HqRuJmUxgNIiC5iZM1PDEEfg== +"@jimp/tiff@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/tiff/-/tiff-0.14.0.tgz#a5b25bbe7c43fc3b07bad4e2ab90e0e164c1967f" + integrity sha512-zBYDTlutc7j88G/7FBCn3kmQwWr0rmm1e0FKB4C3uJ5oYfT8645lftUsvosKVUEfkdmOaMAnhrf4ekaHcb5gQw== dependencies: "@babel/runtime" "^7.7.2" - core-js "^3.4.1" utif "^2.0.1" -"@jimp/types@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/types/-/types-0.9.6.tgz#7be7f415ad93be733387c03b8a228c587a868a18" - integrity sha512-PSjdbLZ8d50En+Wf1XkWFfrXaf/GqyrxxgIwFWPbL+wrW4pmbYovfxSLCY61s8INsOFOft9dzzllhLBtg1aQ6A== +"@jimp/types@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/types/-/types-0.14.0.tgz#ef681ff702883c5f105b5e4e30d49abf39ee9e34" + integrity sha512-hx3cXAW1KZm+b+XCrY3LXtdWy2U+hNtq0rPyJ7NuXCjU7lZR3vIkpz1DLJ3yDdS70hTi5QDXY3Cd9kd6DtloHQ== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/bmp" "^0.9.6" - "@jimp/gif" "^0.9.6" - "@jimp/jpeg" "^0.9.6" - "@jimp/png" "^0.9.6" - "@jimp/tiff" "^0.9.6" - core-js "^3.4.1" + "@jimp/bmp" "^0.14.0" + "@jimp/gif" "^0.14.0" + "@jimp/jpeg" "^0.14.0" + "@jimp/png" "^0.14.0" + "@jimp/tiff" "^0.14.0" timm "^1.6.1" -"@jimp/utils@^0.9.6": - version "0.9.6" - resolved "https://registry.yarnpkg.com/@jimp/utils/-/utils-0.9.6.tgz#a3e6c29e835e2b9ea9f3899c9d3d230dc63bd518" - integrity sha512-kzxcp0i4ecSdMXFEmtH+NYdBQysINEUTsrjm7v0zH8t/uwaEMOG46I16wo/iPBXJkUeNdL2rbXoGoxxoeSfrrA== +"@jimp/utils@^0.14.0": + version "0.14.0" + resolved "https://registry.yarnpkg.com/@jimp/utils/-/utils-0.14.0.tgz#296254e63118554c62c31c19ac6b8c4bfe6490e5" + integrity sha512-MY5KFYUru0y74IsgM/9asDwb3ERxWxXEu3CRCZEvE7DtT86y1bR1XgtlSliMrptjz4qbivNGMQSvUBpEFJDp1A== dependencies: "@babel/runtime" "^7.7.2" - core-js "^3.4.1" + regenerator-runtime "^0.13.3" "@mapbox/extent@0.4.0": version "0.4.0" @@ -4625,10 +4636,10 @@ resolved "https://registry.yarnpkg.com/@types/anymatch/-/anymatch-1.3.1.tgz#336badc1beecb9dacc38bea2cf32adf627a8421a" integrity sha512-/+CRPXpBDpo2RK9C68N3b2cOvO0Cf5B9aPijHsoDQTHivnGSObdOF2BRQOYjojWTDy6nQvMjmqRXIxH55VjxxA== -"@types/archiver@^3.0.0": - version "3.0.0" - resolved "https://registry.yarnpkg.com/@types/archiver/-/archiver-3.0.0.tgz#c0a53e0ed3b7aef626ce683d081d7821d8c638b4" - integrity sha512-orghAMOF+//wSg4ru2znk6jt0eIPvKTtMVLH7XcYcjbcRyAXRClDlh27QVdqnAvVM37yu9xDP6Nh7egRhNr8tQ== +"@types/archiver@^3.1.0": + version "3.1.0" + resolved "https://registry.yarnpkg.com/@types/archiver/-/archiver-3.1.0.tgz#0d5bd922ba5cf06e137cd6793db7942439b1805e" + integrity sha512-nTvHwgWONL+iXG+9CX+gnQ/tTOV+qucAjwpXqeUn4OCRMxP42T29FFP/7XaOo0EqqO3TlENhObeZEe7RUJAriw== dependencies: "@types/glob" "*" @@ -4717,21 +4728,11 @@ resolved "https://registry.yarnpkg.com/@types/base64-js/-/base64-js-1.2.5.tgz#582b2476169a6cba460a214d476c744441d873d5" integrity sha1-WCskdhaabLpGCiFNR2x0REHYc9U= -"@types/blob-util@1.3.3": - version "1.3.3" - resolved "https://registry.yarnpkg.com/@types/blob-util/-/blob-util-1.3.3.tgz#adba644ae34f88e1dd9a5864c66ad651caaf628a" - integrity sha512-4ahcL/QDnpjWA2Qs16ZMQif7HjGP2cw3AGjHabybjw7Vm1EKu+cfQN1D78BaZbS1WJNa1opSMF5HNMztx7lR0w== - "@types/bluebird@*", "@types/bluebird@^3.1.1": version "3.5.30" resolved "https://registry.yarnpkg.com/@types/bluebird/-/bluebird-3.5.30.tgz#ee034a0eeea8b84ed868b1aa60d690b08a6cfbc5" integrity sha512-8LhzvcjIoqoi1TghEkRMkbbmM+jhHnBokPGkJWjclMK+Ks0MxEBow3/p2/iFTZ+OIbJHQDSfpgdZEb+af3gfVw== -"@types/bluebird@3.5.29": - version "3.5.29" - resolved "https://registry.yarnpkg.com/@types/bluebird/-/bluebird-3.5.29.tgz#7cd933c902c4fc83046517a1bef973886d00bdb6" - integrity sha512-kmVtnxTuUuhCET669irqQmPAez4KFnFVKvpleVRyfC3g+SHD1hIkFZcWLim9BVcwUBLO59o8VZE4yGCmTif8Yw== - "@types/boom@*", "@types/boom@^7.2.0": version "7.2.0" resolved "https://registry.yarnpkg.com/@types/boom/-/boom-7.2.0.tgz#19c36cbb5811a7493f0f2e37f31d42b28df1abc1" @@ -4762,15 +4763,7 @@ resolved "https://registry.yarnpkg.com/@types/catbox/-/catbox-10.0.1.tgz#266679017749041fe9873fee1131dd2aaa04a07e" integrity sha512-ECuJ+f5gGHiLeiE4RlE/xdqv/0JVDToegPV1aTb10tQStYa0Ycq2OJfQukDv3IFaw3B+CMV46jHc5bXe6QXEQg== -"@types/chai-jquery@1.1.40": - version "1.1.40" - resolved "https://registry.yarnpkg.com/@types/chai-jquery/-/chai-jquery-1.1.40.tgz#445bedcbbb2ae4e3027f46fa2c1733c43481ffa1" - integrity sha512-mCNEZ3GKP7T7kftKeIs7QmfZZQM7hslGSpYzKbOlR2a2HCFf9ph4nlMRA9UnuOETeOQYJVhJQK7MwGqNZVyUtQ== - dependencies: - "@types/chai" "*" - "@types/jquery" "*" - -"@types/chai@*", "@types/chai@4.2.7", "@types/chai@^4.2.11": +"@types/chai@^4.2.11": version "4.2.11" resolved "https://registry.yarnpkg.com/@types/chai/-/chai-4.2.11.tgz#d3614d6c5f500142358e6ed24e1bf16657536c50" integrity sha512-t7uW6eFafjO+qJ3BIV2gGUyZs27egcNRkUdalkud+Qa3+kg//f129iuOFivHDXQ+vnU3fDXuwgv0cqMCbcE8sw== @@ -5260,7 +5253,7 @@ resolved "https://registry.yarnpkg.com/@types/joi/-/joi-13.6.1.tgz#325486a397504f8e22c8c551dc8b0e1d41d5d5ae" integrity sha512-JxZ0NP8NuB0BJOXi1KvAA6rySLTPmhOy4n2gzSFq/IFM3LNFm0h+2Vn/bPPgEYlWqzS2NPeLgKqfm75baX+Hog== -"@types/jquery@*", "@types/jquery@3.3.31", "@types/jquery@^3.3.31": +"@types/jquery@*", "@types/jquery@^3.3.31": version "3.3.31" resolved "https://registry.yarnpkg.com/@types/jquery/-/jquery-3.3.31.tgz#27c706e4bf488474e1cb54a71d8303f37c93451b" integrity sha512-Lz4BAJihoFw5nRzKvg4nawXPzutkv7wmfQ5121avptaSIXlDNJCUuxZxX/G+9EVidZGuO0UBlk+YjKbwRKJigg== @@ -5346,11 +5339,6 @@ "@types/node" "*" "@types/webpack" "*" -"@types/lodash@4.14.149", "@types/lodash@^4.14.155": - version "4.14.156" - resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.156.tgz#cbe30909c89a1feeb7c60803e785344ea0ec82d1" - integrity sha512-l2AgHXcKUwx2DsvP19wtRPqZ4NkONjmorOdq4sMcxIjqdIuuV/ULo2ftuv4NUpevwfW7Ju/UKLqo0ZXuEt/8lQ== - "@types/lodash@^3.10.1": version "3.10.3" resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-3.10.3.tgz#aaddec6a3c93bf03b402db3acf5d4c77bce8bdff" @@ -5361,6 +5349,11 @@ resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.150.tgz#649fe44684c3f1fcb6164d943c5a61977e8cf0bd" integrity sha512-kMNLM5JBcasgYscD9x/Gvr6lTAv2NVgsKtet/hm93qMyf/D1pt+7jeEZklKJKxMVmXjxbRVQQGfqDSfipYCO6w== +"@types/lodash@^4.14.155": + version "4.14.156" + resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.156.tgz#cbe30909c89a1feeb7c60803e785344ea0ec82d1" + integrity sha512-l2AgHXcKUwx2DsvP19wtRPqZ4NkONjmorOdq4sMcxIjqdIuuV/ULo2ftuv4NUpevwfW7Ju/UKLqo0ZXuEt/8lQ== + "@types/log-symbols@^2.0.0": version "2.0.0" resolved "https://registry.yarnpkg.com/@types/log-symbols/-/log-symbols-2.0.0.tgz#7919e2ec3c8d13879bfdcab310dd7a3f7fc9466d" @@ -5419,7 +5412,7 @@ dependencies: "@types/mime-db" "*" -"@types/minimatch@*", "@types/minimatch@3.0.3", "@types/minimatch@^3.0.3": +"@types/minimatch@*", "@types/minimatch@^3.0.3": version "3.0.3" resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d" integrity sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA== @@ -5441,11 +5434,6 @@ dependencies: "@types/node" "*" -"@types/mocha@5.2.7": - version "5.2.7" - resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-5.2.7.tgz#315d570ccb56c53452ff8638738df60726d5b6ea" - integrity sha512-NYrtPht0wGzhwe9+/idPaBB+TqkY9AhTvOLMkThm0IoEfLaiVQZwBwyJ5puCkO3AUCWrmcoePjp2mbFocKy4SQ== - "@types/mocha@^7.0.2": version "7.0.2" resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-7.0.2.tgz#b17f16cf933597e10d6d78eae3251e692ce8b0ce" @@ -5859,32 +5847,12 @@ dependencies: "@types/node" "*" -"@types/sinon-chai@3.2.3": - version "3.2.3" - resolved "https://registry.yarnpkg.com/@types/sinon-chai/-/sinon-chai-3.2.3.tgz#afe392303dda95cc8069685d1e537ff434fa506e" - integrity sha512-TOUFS6vqS0PVL1I8NGVSNcFaNJtFoyZPXZ5zur+qlhDfOmQECZZM4H4kKgca6O8L+QceX/ymODZASfUfn+y4yQ== - dependencies: - "@types/chai" "*" - "@types/sinon" "*" - -"@types/sinon@*": - version "9.0.4" - resolved "https://registry.yarnpkg.com/@types/sinon/-/sinon-9.0.4.tgz#e934f904606632287a6e7f7ab0ce3f08a0dad4b1" - integrity sha512-sJmb32asJZY6Z2u09bl0G2wglSxDlROlAejCjsnor+LzBMz17gu8IU7vKC/vWDnv9zEq2wqADHVXFjf4eE8Gdw== - dependencies: - "@types/sinonjs__fake-timers" "*" - -"@types/sinon@7.5.1": - version "7.5.1" - resolved "https://registry.yarnpkg.com/@types/sinon/-/sinon-7.5.1.tgz#d27b81af0d1cfe1f9b24eebe7a24f74ae40f5b7c" - integrity sha512-EZQUP3hSZQyTQRfiLqelC9NMWd1kqLcmQE0dMiklxBkgi84T+cHOhnKpgk4NnOWpGX863yE6+IaGnOXUNFqDnQ== - "@types/sinon@^7.0.13": version "7.0.13" resolved "https://registry.yarnpkg.com/@types/sinon/-/sinon-7.0.13.tgz#ca039c23a9e27ebea53e0901ef928ea2a1a6d313" integrity sha512-d7c/C/+H/knZ3L8/cxhicHUiTDxdgap0b/aNJfsmLwFu/iOP17mdgbQsbHA3SJmrzsjD0l3UEE5SN4xxuz5ung== -"@types/sinonjs__fake-timers@*": +"@types/sinonjs__fake-timers@6.0.1": version "6.0.1" resolved "https://registry.yarnpkg.com/@types/sinonjs__fake-timers/-/sinonjs__fake-timers-6.0.1.tgz#681df970358c82836b42f989188d133e218c458e" integrity sha512-yYezQwGWty8ziyYLdZjwxyMb0CZR49h8JALHGrxjQHWlqGgc8kLdHEgWrgL0uZ29DMvEVBDnHU2Wg36zKSIUtA== @@ -6544,11 +6512,6 @@ abbrev@1: resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" integrity sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q== -abbrev@1.0.x: - version "1.0.9" - resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.0.9.tgz#91b4792588a7738c25f35dd6f63752a2f8776135" - integrity sha1-kbR5JYinc4wl813W9jdSovh3YTU= - abort-controller@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/abort-controller/-/abort-controller-2.0.3.tgz#b174827a732efadff81227ed4b8d1cc569baf20a" @@ -6706,11 +6669,6 @@ after-all-results@^2.0.0: resolved "https://registry.yarnpkg.com/after-all-results/-/after-all-results-2.0.0.tgz#6ac2fc202b500f88da8f4f5530cfa100f4c6a2d0" integrity sha1-asL8ICtQD4jaj09VMM+hAPTGotA= -after@0.8.2: - version "0.8.2" - resolved "https://registry.yarnpkg.com/after/-/after-0.8.2.tgz#fedb394f9f0e02aa9768e702bda23b505fae7e1f" - integrity sha1-/ts5T58OAqqXaOcCvaI7UF+ufh8= - agent-base@4: version "4.2.0" resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-4.2.0.tgz#9838b5c3392b962bad031e6a4c5e1024abec45ce" @@ -7388,10 +7346,10 @@ aproba@^1.0.3, aproba@^1.1.1: resolved "https://registry.yarnpkg.com/aproba/-/aproba-1.2.0.tgz#6802e6264efd18c790a1b0d517f0f2627bf2c94a" integrity sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw== -arch@2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/arch/-/arch-2.1.1.tgz#8f5c2731aa35a30929221bb0640eed65175ec84e" - integrity sha512-BLM56aPo9vLLFVa8+/+pJLnrZ7QGGTVHWsCwieAWT9o9K8UeGaQbzZbGoabWLOo2ksBCztoXdqBZBplqLDDCSg== +arch@2.1.2: + version "2.1.2" + resolved "https://registry.yarnpkg.com/arch/-/arch-2.1.2.tgz#0c52bbe7344bb4fa260c443d2cbad9c00ff2f0bf" + integrity sha512-NTBIIbAfkJeIletyABbVtdPgeKfDafR+1mZV/AyyfC1UkVkp9iUjV+wwmqtUgphHYajbI86jejBJp5e+jkGTiQ== archiver-utils@^2.1.0: version "2.1.0" @@ -7557,6 +7515,15 @@ array-includes@^3.0.3: define-properties "^1.1.2" es-abstract "^1.7.0" +array-includes@^3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.1.1.tgz#cdd67e6852bdf9c1215460786732255ed2459348" + integrity sha512-c2VXaCHl7zPsvpkFsw4nxvFie4fh1ur9bpcgsVkIjqn0H/Xwdg+7fv3n2r/isyS8EBj5b06M9kHyZuIr4El6WQ== + dependencies: + define-properties "^1.1.3" + es-abstract "^1.17.0" + is-string "^1.0.5" + array-initial@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/array-initial/-/array-initial-1.1.0.tgz#2fa74b26739371c3947bd7a7adc73be334b3d795" @@ -7643,10 +7610,14 @@ array.prototype.flatmap@^1.2.1: es-abstract "^1.10.0" function-bind "^1.1.1" -arraybuffer.slice@~0.0.7: - version "0.0.7" - resolved "https://registry.yarnpkg.com/arraybuffer.slice/-/arraybuffer.slice-0.0.7.tgz#3bbc4275dd584cc1b10809b89d4e8b63a69e7675" - integrity sha512-wGUIVQXuehL5TCqQun8OW81jGzAWycqzFF8lFp+GOM5BXLYj3bKNsYC4daB7n6XjCqxQA/qgTJ+8ANR3acjrog== +array.prototype.flatmap@^1.2.3: + version "1.2.3" + resolved "https://registry.yarnpkg.com/array.prototype.flatmap/-/array.prototype.flatmap-1.2.3.tgz#1c13f84a178566042dd63de4414440db9222e443" + integrity sha512-OOEk+lkePcg+ODXIpvuU9PAryCikCJyo7GlDG1upleEpQRx6mzL9puEBkozQ5iAx20KV0l3DbyQwqciJtqe5Pg== + dependencies: + define-properties "^1.1.3" + es-abstract "^1.17.0-next.1" + function-bind "^1.1.1" arrify@^1.0.0, arrify@^1.0.1: version "1.0.1" @@ -7813,11 +7784,6 @@ async-value@^1.2.2: resolved "https://registry.yarnpkg.com/async-value/-/async-value-1.2.2.tgz#84517a1e7cb6b1a5b5e181fa31be10437b7fb125" integrity sha1-hFF6Hny2saW14YH6Mb4QQ3t/sSU= -async@1.x, async@^1.4.2, async@^1.5.2, async@~1.5.2: - version "1.5.2" - resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" - integrity sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo= - async@2.4.0: version "2.4.0" resolved "https://registry.yarnpkg.com/async/-/async-2.4.0.tgz#4990200f18ea5b837c2cc4f8c031a6985c385611" @@ -7825,6 +7791,11 @@ async@2.4.0: dependencies: lodash "^4.14.0" +async@^1.4.2, async@^1.5.2, async@~1.5.2: + version "1.5.2" + resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" + integrity sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo= + async@^2.0.0, async@^2.1.4: version "2.6.0" resolved "https://registry.yarnpkg.com/async/-/async-2.6.0.tgz#61a29abb6fcc026fea77e56d1c6ec53a795951f4" @@ -7839,14 +7810,14 @@ async@^2.6.0, async@^2.6.1: dependencies: lodash "^4.17.10" -async@^2.6.2, async@^2.6.3: +async@^2.6.3: version "2.6.3" resolved "https://registry.yarnpkg.com/async/-/async-2.6.3.tgz#d72625e2344a3656e3a3ad4fa749fa83299d82ff" integrity sha512-zflvls11DCy+dQWzTW2dzuilv8Z5X/pjfmZOWba6TNIVDm+2UDaJmXSOXlasHKfNBs8oo3M0aT50fDEWfKZjXg== dependencies: lodash "^4.17.14" -async@^3.1.0: +async@^3.1.0, async@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/async/-/async-3.2.0.tgz#b3a2685c5ebb641d3de02d161002c60fc9f85720" integrity sha512-TR2mEZFVOj2pLStYxLht7TyfuRzaydfpxr3k9RpHIzMgw7A64dzsdqCxH1WJyQdoe8T10nDXd9wnEigmiuHIZw== @@ -8528,11 +8499,6 @@ bach@^1.0.0: async-settle "^1.0.0" now-and-later "^2.0.0" -backo2@1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/backo2/-/backo2-1.0.2.tgz#31ab1ac8b129363463e35b3ebb69f4dfcfba7947" - integrity sha1-MasayLEpNjRj41s+u2n038+6eUc= - backport@5.5.1: version "5.5.1" resolved "https://registry.yarnpkg.com/backport/-/backport-5.5.1.tgz#2eeddbdc4cfc0530119bdb2b0c3c30bc7ef574dd" @@ -8564,11 +8530,6 @@ balanced-match@^1.0.0: resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= -base64-arraybuffer@0.1.5: - version "0.1.5" - resolved "https://registry.yarnpkg.com/base64-arraybuffer/-/base64-arraybuffer-0.1.5.tgz#73926771923b5a19747ad666aa5cd4bf9c6e9ce8" - integrity sha1-c5JncZI7Whl0etZmqlzUv5xunOg= - base64-js@0.0.8: version "0.0.8" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-0.0.8.tgz#1101e9544f4a76b1bc3b26d452ca96d7a35e7978" @@ -8584,11 +8545,6 @@ base64-js@^1.1.2, base64-js@^1.2.1, base64-js@^1.3.0, base64-js@^1.3.1: resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.3.1.tgz#58ece8cb75dd07e71ed08c736abc5fac4dbf8df1" integrity sha512-mLQ4i2QO1ytvGWFWmcngKO//JXAQueZvwEKtjgQFM4jIK0kU+ytMfplL8j+n5mspOfjHwoAg+9yhb7BwAHm36g== -base64id@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/base64id/-/base64id-1.0.0.tgz#47688cb99bb6804f0e06d3e763b1c32e57d8e6b6" - integrity sha1-R2iMuZu2gE8OBtPnY7HDLlfY5rY= - base64url@^3.0.0, base64url@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/base64url/-/base64url-3.0.1.tgz#6399d572e2bc3f90a9a8b22d5dbb0a32d33f788d" @@ -8636,13 +8592,6 @@ before-after-hook@^1.4.0: resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-1.4.0.tgz#2b6bf23dca4f32e628fd2747c10a37c74a4b484d" integrity sha512-l5r9ir56nda3qu14nAXIlyq1MmUSs0meCIaFAh8HwkFwP1F8eToOuS3ah2VAHHcY04jaYD7FpJC5JTXHYRbkzg== -better-assert@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/better-assert/-/better-assert-1.0.2.tgz#40866b9e1b9e0b55b481894311e68faffaebc522" - integrity sha1-QIZrnhueC1W0gYlDEeaPr/rrxSI= - dependencies: - callsite "1.0.0" - big-integer@^1.6.16: version "1.6.48" resolved "https://registry.yarnpkg.com/big-integer/-/big-integer-1.6.48.tgz#8fd88bd1632cba4a1c8c3e3d7159f08bb95b4b9e" @@ -8721,11 +8670,6 @@ bl@^3.0.0: dependencies: readable-stream "^3.0.1" -blob@0.0.5: - version "0.0.5" - resolved "https://registry.yarnpkg.com/blob/-/blob-0.0.5.tgz#d680eeef25f8cd91ad533f5b01eed48e64caf683" - integrity sha512-gaqbzQPqOoamawKg0LGVd7SzLgXS+JH61oWprSLH+P+abTczqJbhTR8CmJ2u9/bUYNmHTGJx/UEmn6doAvvuig== - block-stream@*: version "0.0.9" resolved "https://registry.yarnpkg.com/block-stream/-/block-stream-0.0.9.tgz#13ebfe778a03205cfe03751481ebb4b3300c126a" @@ -8810,22 +8754,6 @@ body-parser@1.19.0, body-parser@^1.18.1, body-parser@^1.18.3: raw-body "2.4.0" type-is "~1.6.17" -body-parser@^1.16.1: - version "1.18.2" - resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.18.2.tgz#87678a19d84b47d859b83199bd59bce222b10454" - integrity sha1-h2eKGdhLR9hZuDGZvVm84iKxBFQ= - dependencies: - bytes "3.0.0" - content-type "~1.0.4" - debug "2.6.9" - depd "~1.1.1" - http-errors "~1.6.2" - iconv-lite "0.4.19" - on-finished "~2.3.0" - qs "6.5.1" - raw-body "2.3.2" - type-is "~1.6.15" - body@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/body/-/body-5.1.0.tgz#e4ba0ce410a46936323367609ecb4e6553125069" @@ -8969,7 +8897,7 @@ braces@^2.3.1, braces@^2.3.2: split-string "^3.0.2" to-regex "^3.0.1" -braces@^3.0.1, braces@^3.0.2, braces@~3.0.2: +braces@^3.0.1, braces@~3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== @@ -9473,11 +9401,6 @@ caller-path@^2.0.0: dependencies: caller-callsite "^2.0.0" -callsite@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/callsite/-/callsite-1.0.0.tgz#280398e5d664bd74038b6f0905153e6e8af1bc20" - integrity sha1-KAOY5dZkvXQDi28JBRU+borxvCA= - callsites@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/callsites/-/callsites-0.2.0.tgz#afab96262910a7f33c19a5775825c69f34e350ca" @@ -9944,7 +9867,7 @@ chokidar@^2.0.0, chokidar@^2.1.2, chokidar@^2.1.8: optionalDependencies: fsevents "^1.2.7" -chokidar@^3.0.0, chokidar@^3.2.2: +chokidar@^3.2.2: version "3.3.1" resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.3.1.tgz#c84e5b3d18d9a4d77558fef466b1bf16bbeb3450" integrity sha512-4QYCEWOcK3OJrxwvyyAOxFuhpvOVCYkr33LPfFNBjAD/w3sEzWsp2BUOkI4l9bHvWioAd0rc6NlHUOEaWkTeqg== @@ -10475,16 +10398,16 @@ colors@1.0.3: resolved "https://registry.yarnpkg.com/colors/-/colors-1.0.3.tgz#0433f44d809680fdeb60ed260f1b0c262e82a40b" integrity sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs= -colors@^1.1.0, colors@^1.2.1: - version "1.3.2" - resolved "https://registry.yarnpkg.com/colors/-/colors-1.3.2.tgz#2df8ff573dfbf255af562f8ce7181d6b971a359b" - integrity sha512-rhP0JSBGYvpcNQj4s5AdShMeE5ahMop96cTeDl/v9qQQm2fYClE2QXZRi8wLzc+GmXSxdIqqbOIAhyObEXDbfQ== - colors@^1.1.2, colors@^1.3.2: version "1.3.3" resolved "https://registry.yarnpkg.com/colors/-/colors-1.3.3.tgz#39e005d546afe01e01f9c4ca8fa50f686a01205d" integrity sha512-mmGt/1pZqYRjMxB1axhTo16/snVZ5krrKkcmMeVKxzECMMXoCgnvTPp10QgHfcbQZw8Dq2jMNG6je4JlWU0gWg== +colors@^1.2.1: + version "1.3.2" + resolved "https://registry.yarnpkg.com/colors/-/colors-1.3.2.tgz#2df8ff573dfbf255af562f8ce7181d6b971a359b" + integrity sha512-rhP0JSBGYvpcNQj4s5AdShMeE5ahMop96cTeDl/v9qQQm2fYClE2QXZRi8wLzc+GmXSxdIqqbOIAhyObEXDbfQ== + colors@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/colors/-/colors-1.1.2.tgz#168a4701756b6a7f51a12ce0c97bfa28c084ed63" @@ -10544,10 +10467,10 @@ commander@3.0.2: resolved "https://registry.yarnpkg.com/commander/-/commander-3.0.2.tgz#6837c3fb677ad9933d1cfba42dd14d5117d6b39e" integrity sha512-Gar0ASD4BDyKC4hl4DwHqDrmvjoxWKZigVnAbn5H1owvm4CxCPdb0HQDehwNYMJpla5+M2tPmPARzhtYuwpHow== -commander@4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.0.tgz#545983a0603fe425bc672d66c9e3c89c42121a83" - integrity sha512-NIQrwvv9V39FHgGFm36+U9SMQzbiHvU79k+iADraJTpmrFFfx7Ds0IvDoAdZsDrknlkRk14OYoWXb57uTh7/sw== +commander@4.1.1, commander@^4.0.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068" + integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA== commander@^2.13.0, commander@^2.15.1, commander@^2.16.0, commander@^2.19.0: version "2.20.0" @@ -10569,11 +10492,6 @@ commander@^3.0.0: resolved "https://registry.yarnpkg.com/commander/-/commander-3.0.0.tgz#0641ea00838c7a964627f04cddc336a2deddd60a" integrity sha512-pl3QrGOBa9RZaslQiqnnKX2J068wcQw7j9AIaBQ9/JEp5RY6je4jKTImg0Bd+rpoONSe7GUFSgkxLeo17m3Pow== -commander@^4.0.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068" - integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA== - commander@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/commander/-/commander-5.0.0.tgz#dbf1909b49e5044f8fdaf0adc809f0c0722bdfd0" @@ -10601,21 +10519,11 @@ compare-versions@3.5.1: resolved "https://registry.yarnpkg.com/compare-versions/-/compare-versions-3.5.1.tgz#26e1f5cf0d48a77eced5046b9f67b6b61075a393" integrity sha512-9fGPIB7C6AyM18CJJBHt5EnCZDG3oiTJYy0NjfIAGjKpzv0tkxWko7TNQHF5ymqm7IH03tqmeuBxtvD+Izh6mg== -component-bind@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/component-bind/-/component-bind-1.0.0.tgz#00c608ab7dcd93897c0009651b1d3a8e1e73bbd1" - integrity sha1-AMYIq33Nk4l8AAllGx06jh5zu9E= - -component-emitter@1.2.1, component-emitter@^1.2.0, component-emitter@^1.2.1: +component-emitter@^1.2.0, component-emitter@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.2.1.tgz#137918d6d78283f7df7a6b7c5a63e140e69425e6" integrity sha1-E3kY1teCg/ffemt8WmPhQOaUJeY= -component-inherit@0.0.3: - version "0.0.3" - resolved "https://registry.yarnpkg.com/component-inherit/-/component-inherit-0.0.3.tgz#645fc4adf58b72b649d5cae65135619db26ff143" - integrity sha1-ZF/ErfWLcrZJ1crmUTVhnbJv8UM= - compose-function@3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/compose-function/-/compose-function-3.0.3.tgz#9ed675f13cc54501d30950a486ff6a7ba3ab185f" @@ -10799,16 +10707,6 @@ connect@^3.4.0: parseurl "~1.3.3" utils-merge "1.0.1" -connect@^3.6.0: - version "3.6.6" - resolved "https://registry.yarnpkg.com/connect/-/connect-3.6.6.tgz#09eff6c55af7236e137135a72574858b6786f524" - integrity sha1-Ce/2xVr3I24TcTWnJXSFi2eG9SQ= - dependencies: - debug "2.6.9" - finalhandler "1.1.0" - parseurl "~1.3.2" - utils-merge "1.0.1" - console-browserify@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/console-browserify/-/console-browserify-1.1.0.tgz#f0241c45730a9fc6323b206dbf38edc741d0bb10" @@ -11037,7 +10935,7 @@ core-js@^2.4.0, core-js@^2.5.0, core-js@^2.5.1, core-js@^2.5.3, core-js@^2.6.5, resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.6.9.tgz#6b4b214620c834152e179323727fc19741b084f2" integrity sha512-HOpZf6eXmnl7la+cUdMnLvUxKNqLUzJvgIziQ0DiF3JwSImNphIqdGqzj6hIKyX04MmV0poclQ7+wjWvxQyR2A== -core-js@^3.0.1, core-js@^3.0.4, core-js@^3.4.1, core-js@^3.6.4: +core-js@^3.0.1, core-js@^3.0.4, core-js@^3.6.4: version "3.6.4" resolved "https://registry.yarnpkg.com/core-js/-/core-js-3.6.4.tgz#440a83536b458114b9cb2ac1580ba377dc470647" integrity sha512-4paDGScNgZP2IXXilaffL9X7968RuvwlkK3xWtZRVqgd8SYNiVKRJvkFd1aqqEuPfN7E68ZHEp9hDj6lHj4Hyw== @@ -11541,11 +11439,6 @@ custom-event-polyfill@^0.3.0: resolved "https://registry.yarnpkg.com/custom-event-polyfill/-/custom-event-polyfill-0.3.0.tgz#99807839be62edb446b645832e0d80ead6fa1888" integrity sha1-mYB4Ob5i7bRGtkWDLg2A6tb6GIg= -custom-event@~1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/custom-event/-/custom-event-1.0.1.tgz#5d02a46850adf1b4a317946a3928fccb5bfd0425" - integrity sha1-XQKkaFCt8bSjF5RqOSj8y1v9BCU= - cyclist@~0.2.2: version "0.2.2" resolved "https://registry.yarnpkg.com/cyclist/-/cyclist-0.2.2.tgz#1b33792e11e914a2fd6d6ed6447464444e5fa640" @@ -11559,48 +11452,39 @@ cypress-multi-reporters@^1.2.3: debug "^4.1.1" lodash "^4.17.11" -cypress@4.5.0: - version "4.5.0" - resolved "https://registry.yarnpkg.com/cypress/-/cypress-4.5.0.tgz#01940d085f6429cec3c87d290daa47bb976a7c7b" - integrity sha512-2A4g5FW5d2fHzq8HKUGAMVTnW6P8nlWYQALiCoGN4bqBLvgwhYM/oG9oKc2CS6LnvgHFiKivKzpm9sfk3uU3zQ== +cypress@4.11.0: + version "4.11.0" + resolved "https://registry.yarnpkg.com/cypress/-/cypress-4.11.0.tgz#054b0b85fd3aea793f186249ee1216126d5f0a7e" + integrity sha512-6Yd598+KPATM+dU1Ig0g2hbA+R/o1MAKt0xIejw4nZBVLSplCouBzqeKve6XsxGU6n4HMSt/+QYsWfFcoQeSEw== dependencies: "@cypress/listr-verbose-renderer" "0.4.1" "@cypress/request" "2.88.5" "@cypress/xvfb" "1.2.4" - "@types/blob-util" "1.3.3" - "@types/bluebird" "3.5.29" - "@types/chai" "4.2.7" - "@types/chai-jquery" "1.1.40" - "@types/jquery" "3.3.31" - "@types/lodash" "4.14.149" - "@types/minimatch" "3.0.3" - "@types/mocha" "5.2.7" - "@types/sinon" "7.5.1" - "@types/sinon-chai" "3.2.3" + "@types/sinonjs__fake-timers" "6.0.1" "@types/sizzle" "2.3.2" - arch "2.1.1" + arch "2.1.2" bluebird "3.7.2" cachedir "2.3.0" chalk "2.4.2" check-more-types "2.24.0" cli-table3 "0.5.1" - commander "4.1.0" + commander "4.1.1" common-tags "1.8.0" debug "4.1.1" - eventemitter2 "4.1.2" + eventemitter2 "6.4.2" execa "1.0.0" executable "4.1.1" extract-zip "1.7.0" fs-extra "8.1.0" - getos "3.1.4" + getos "3.2.1" is-ci "2.0.0" - is-installed-globally "0.1.0" + is-installed-globally "0.3.2" lazy-ass "1.6.0" listr "0.14.3" - lodash "4.17.15" + lodash "4.17.19" log-symbols "3.0.0" minimist "1.2.5" - moment "2.24.0" + moment "2.26.0" ospath "1.2.2" pretty-bytes "5.3.0" ramda "0.26.1" @@ -11864,24 +11748,11 @@ date-fns@^1.27.2: resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-1.29.0.tgz#12e609cdcb935127311d04d33334e2960a2a54e6" integrity sha512-lbTXWZ6M20cWH8N9S6afb0SBm6tMk+uUg6z3MqHPKE9atmsY3kJkTm8vKe93izJ2B2+q5MV990sM2CHgtAZaOw== -date-format@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/date-format/-/date-format-2.1.0.tgz#31d5b5ea211cf5fd764cd38baf9d033df7e125cf" - integrity sha512-bYQuGLeFxhkxNOF3rcMtiZxvCBAquGzZm6oWA1oZ0g2THUzivaRhv8uOhdr19LmoobSOLoIAxeUK2RdbM8IFTA== - date-now@^0.1.4: version "0.1.4" resolved "https://registry.yarnpkg.com/date-now/-/date-now-0.1.4.tgz#eaf439fd4d4848ad74e5cc7dbef200672b9e345b" integrity sha1-6vQ5/U1ISK105cx9vvIAZyueNFs= -dateformat@^1.0.6, dateformat@~1.0.12: - version "1.0.12" - resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-1.0.12.tgz#9f124b67594c937ff706932e4a642cca8dbbfee9" - integrity sha1-nxJLZ1lMk3/3BpMuSmQsyo27/uk= - dependencies: - get-stdin "^4.0.1" - meow "^3.3.0" - dateformat@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-2.2.0.tgz#4065e2013cf9fb916ddfd82efb506ad4c6769062" @@ -11892,6 +11763,14 @@ dateformat@^3.0.2: resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-3.0.3.tgz#a6e37499a4d9a9cf85ef5872044d62901c9889ae" integrity sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q== +dateformat@~1.0.12: + version "1.0.12" + resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-1.0.12.tgz#9f124b67594c937ff706932e4a642cca8dbbfee9" + integrity sha1-nxJLZ1lMk3/3BpMuSmQsyo27/uk= + dependencies: + get-stdin "^4.0.1" + meow "^3.3.0" + debug-fabulous@1.X: version "1.1.0" resolved "https://registry.yarnpkg.com/debug-fabulous/-/debug-fabulous-1.1.0.tgz#af8a08632465224ef4174a9f06308c3c2a1ebc8e" @@ -11908,7 +11787,7 @@ debug@2.6.9, debug@^2.0.0, debug@^2.1.0, debug@^2.1.1, debug@^2.2.0, debug@^2.3. dependencies: ms "2.0.0" -debug@3.1.0, debug@=3.1.0, debug@~3.1.0: +debug@3.1.0, debug@=3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261" integrity sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g== @@ -12282,7 +12161,7 @@ depd@1.1.1: resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.1.tgz#5783b4e1c459f06fa5ca27f991f3d06e7a310359" integrity sha1-V4O04cRZ8G+lyif5kfPQbnoxA1k= -depd@~1.1.1, depd@~1.1.2: +depd@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9" integrity sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak= @@ -12491,11 +12370,6 @@ dfa@^1.2.0: resolved "https://registry.yarnpkg.com/dfa/-/dfa-1.2.0.tgz#96ac3204e2d29c49ea5b57af8d92c2ae12790657" integrity sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q== -di@^0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/di/-/di-0.0.1.tgz#806649326ceaa7caa3306d75d985ea2748ba913c" - integrity sha1-gGZJMmzqp8qjMG112YXqJ0i6kTw= - diacritics@^1.3.0: version "1.3.0" resolved "https://registry.yarnpkg.com/diacritics/-/diacritics-1.3.0.tgz#3efa87323ebb863e6696cebb0082d48ff3d6f7a1" @@ -12650,16 +12524,6 @@ dom-helpers@^5.0.0: "@babel/runtime" "^7.6.3" csstype "^2.6.7" -dom-serialize@^2.2.0: - version "2.2.1" - resolved "https://registry.yarnpkg.com/dom-serialize/-/dom-serialize-2.2.1.tgz#562ae8999f44be5ea3076f5419dcd59eb43ac95b" - integrity sha1-ViromZ9Evl6jB29UGdzVnrQ6yVs= - dependencies: - custom-event "~1.0.0" - ent "~2.2.0" - extend "^3.0.0" - void-elements "^2.0.0" - dom-serializer@0, dom-serializer@~0.1.0, dom-serializer@~0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-0.1.1.tgz#1ec4059e284babed36eec2941d4a970a189ce7c0" @@ -13112,7 +12976,7 @@ enabled@2.0.x: resolved "https://registry.yarnpkg.com/enabled/-/enabled-2.0.0.tgz#f9dd92ec2d6f4bbc0d5d1e64e21d61cd4665e7c2" integrity sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ== -encodeurl@^1.0.2, encodeurl@~1.0.1, encodeurl@~1.0.2: +encodeurl@^1.0.2, encodeurl@~1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59" integrity sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k= @@ -13138,46 +13002,6 @@ end-of-stream@^1.4.1, end-of-stream@^1.4.4: dependencies: once "^1.4.0" -engine.io-client@~3.2.0: - version "3.2.1" - resolved "https://registry.yarnpkg.com/engine.io-client/-/engine.io-client-3.2.1.tgz#6f54c0475de487158a1a7c77d10178708b6add36" - integrity sha512-y5AbkytWeM4jQr7m/koQLc5AxpRKC1hEVUb/s1FUAWEJq5AzJJ4NLvzuKPuxtDi5Mq755WuDvZ6Iv2rXj4PTzw== - dependencies: - component-emitter "1.2.1" - component-inherit "0.0.3" - debug "~3.1.0" - engine.io-parser "~2.1.1" - has-cors "1.1.0" - indexof "0.0.1" - parseqs "0.0.5" - parseuri "0.0.5" - ws "~3.3.1" - xmlhttprequest-ssl "~1.5.4" - yeast "0.1.2" - -engine.io-parser@~2.1.0, engine.io-parser@~2.1.1: - version "2.1.3" - resolved "https://registry.yarnpkg.com/engine.io-parser/-/engine.io-parser-2.1.3.tgz#757ab970fbf2dfb32c7b74b033216d5739ef79a6" - integrity sha512-6HXPre2O4Houl7c4g7Ic/XzPnHBvaEmN90vtRO9uLmwtRqQmTOw0QMevL1TOfL2Cpu1VzsaTmMotQgMdkzGkVA== - dependencies: - after "0.8.2" - arraybuffer.slice "~0.0.7" - base64-arraybuffer "0.1.5" - blob "0.0.5" - has-binary2 "~1.0.2" - -engine.io@~3.2.0: - version "3.2.1" - resolved "https://registry.yarnpkg.com/engine.io/-/engine.io-3.2.1.tgz#b60281c35484a70ee0351ea0ebff83ec8c9522a2" - integrity sha512-+VlKzHzMhaU+GsCIg4AoXF1UdDFjHHwMmMKqMJNDNLlUlejz58FCy4LBqB2YVJskHGYl06BatYWKP2TVdVXE5w== - dependencies: - accepts "~1.3.4" - base64id "1.0.0" - cookie "0.3.1" - debug "~3.1.0" - engine.io-parser "~2.1.0" - ws "~3.3.1" - enhanced-resolve@4.1.0, enhanced-resolve@^4.0.0, enhanced-resolve@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz#41c7e0bfdfe74ac1ffe1e57ad6a5c6c9f3742a7f" @@ -13196,11 +13020,6 @@ enhanced-resolve@~0.9.0: memory-fs "^0.2.0" tapable "^0.1.8" -ent@~2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/ent/-/ent-2.2.0.tgz#e964219325a21d05f44466a2f686ed6ce5f5dd1d" - integrity sha1-6WQhkyWiHQX0RGai9obtbOX13R0= - entities@^1.1.1, entities@^1.1.2, entities@~1.1.1: version "1.1.2" resolved "https://registry.yarnpkg.com/entities/-/entities-1.1.2.tgz#bdfa735299664dfafd34529ed4f8522a275fea56" @@ -13369,39 +13188,39 @@ es-abstract@^1.10.0, es-abstract@^1.11.0, es-abstract@^1.13.0, es-abstract@^1.14 string.prototype.trimleft "^2.1.1" string.prototype.trimright "^2.1.1" -es-abstract@^1.15.0, es-abstract@^1.17.0-next.1: - version "1.17.4" - resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.17.4.tgz#e3aedf19706b20e7c2594c35fc0d57605a79e184" - integrity sha512-Ae3um/gb8F0mui/jPL+QiqmglkUsaQf7FwBEHYIFkztkneosu9imhqHpBzQ3h1vit8t5iQ74t6PEVvphBZiuiQ== +es-abstract@^1.17.0, es-abstract@^1.17.4, es-abstract@^1.17.5: + version "1.17.6" + resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.17.6.tgz#9142071707857b2cacc7b89ecb670316c3e2d52a" + integrity sha512-Fr89bON3WFyUi5EvAeI48QTWX0AyekGgLA8H+c+7fbfCkJwRWRMLd8CQedNEyJuoYYhmtEqY92pgte1FAhBlhw== dependencies: es-to-primitive "^1.2.1" function-bind "^1.1.1" has "^1.0.3" has-symbols "^1.0.1" - is-callable "^1.1.5" - is-regex "^1.0.5" + is-callable "^1.2.0" + is-regex "^1.1.0" object-inspect "^1.7.0" object-keys "^1.1.1" object.assign "^4.1.0" - string.prototype.trimleft "^2.1.1" - string.prototype.trimright "^2.1.1" + string.prototype.trimend "^1.0.1" + string.prototype.trimstart "^1.0.1" -es-abstract@^1.17.4, es-abstract@^1.17.5: - version "1.17.6" - resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.17.6.tgz#9142071707857b2cacc7b89ecb670316c3e2d52a" - integrity sha512-Fr89bON3WFyUi5EvAeI48QTWX0AyekGgLA8H+c+7fbfCkJwRWRMLd8CQedNEyJuoYYhmtEqY92pgte1FAhBlhw== +es-abstract@^1.17.0-next.1: + version "1.17.4" + resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.17.4.tgz#e3aedf19706b20e7c2594c35fc0d57605a79e184" + integrity sha512-Ae3um/gb8F0mui/jPL+QiqmglkUsaQf7FwBEHYIFkztkneosu9imhqHpBzQ3h1vit8t5iQ74t6PEVvphBZiuiQ== dependencies: es-to-primitive "^1.2.1" function-bind "^1.1.1" has "^1.0.3" has-symbols "^1.0.1" - is-callable "^1.2.0" - is-regex "^1.1.0" + is-callable "^1.1.5" + is-regex "^1.0.5" object-inspect "^1.7.0" object-keys "^1.1.1" object.assign "^4.1.0" - string.prototype.trimend "^1.0.1" - string.prototype.trimstart "^1.0.1" + string.prototype.trimleft "^2.1.1" + string.prototype.trimright "^2.1.1" es-get-iterator@^1.1.0: version "1.1.0" @@ -13552,18 +13371,6 @@ escape-string-regexp@1.0.5, escape-string-regexp@^1.0.0, escape-string-regexp@^1 resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= -escodegen@1.8.x: - version "1.8.1" - resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.8.1.tgz#5a5b53af4693110bebb0867aa3430dd3b70a1018" - integrity sha1-WltTr0aTEQvrsIZ6o0MN07cKEBg= - dependencies: - esprima "^2.7.1" - estraverse "^1.9.1" - esutils "^2.0.2" - optionator "^0.8.1" - optionalDependencies: - source-map "~0.2.0" - escodegen@^1.11.0: version "1.14.1" resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.14.1.tgz#ba01d0c8278b5e95a9a45350142026659027a457" @@ -13713,11 +13520,6 @@ eslint-plugin-es@^3.0.0: eslint-utils "^2.0.0" regexpp "^3.0.0" -eslint-plugin-eslint-plugin@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/eslint-plugin-eslint-plugin/-/eslint-plugin-eslint-plugin-2.1.0.tgz#a7a00f15a886957d855feacaafee264f039e62d5" - integrity sha512-kT3A/ZJftt28gbl/Cv04qezb/NQ1dwYIbi8lyf806XMxkus7DvOVCLIfTXMrorp322Pnoez7+zabXH29tADIDg== - eslint-plugin-import@^2.19.1: version "2.19.1" resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.19.1.tgz#5654e10b7839d064dd0d46cd1b88ec2133a11448" @@ -13804,21 +13606,22 @@ eslint-plugin-react-perf@^3.2.3: resolved "https://registry.yarnpkg.com/eslint-plugin-react-perf/-/eslint-plugin-react-perf-3.2.3.tgz#e28d42d3a1f7ec3c8976a94735d8e17e7d652a45" integrity sha512-bMiPt7uywwS1Ly25n752NE3Ei0XBZ3igplTkZ8GPJKyZVVUd3cHgzILGeQW2HIeAkzQ9zwk9HM6EcYDipdFk3Q== -eslint-plugin-react@^7.17.0: - version "7.17.0" - resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.17.0.tgz#a31b3e134b76046abe3cd278e7482bd35a1d12d7" - integrity sha512-ODB7yg6lxhBVMeiH1c7E95FLD4E/TwmFjltiU+ethv7KPdCwgiFuOZg9zNRHyufStTDLl/dEFqI2Q1VPmCd78A== +eslint-plugin-react@^7.20.3: + version "7.20.3" + resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.20.3.tgz#0590525e7eb83890ce71f73c2cf836284ad8c2f1" + integrity sha512-txbo090buDeyV0ugF3YMWrzLIUqpYTsWSDZV9xLSmExE1P/Kmgg9++PD931r+KEWS66O1c9R4srLVVHmeHpoAg== dependencies: - array-includes "^3.0.3" + array-includes "^3.1.1" + array.prototype.flatmap "^1.2.3" doctrine "^2.1.0" - eslint-plugin-eslint-plugin "^2.1.0" has "^1.0.3" - jsx-ast-utils "^2.2.3" - object.entries "^1.1.0" - object.fromentries "^2.0.1" - object.values "^1.1.0" + jsx-ast-utils "^2.4.1" + object.entries "^1.1.2" + object.fromentries "^2.0.2" + object.values "^1.1.1" prop-types "^15.7.2" - resolve "^1.13.1" + resolve "^1.17.0" + string.prototype.matchall "^4.0.2" eslint-rule-composer@^0.3.0: version "0.3.0" @@ -13969,11 +13772,6 @@ espree@^6.1.2: acorn-jsx "^5.1.0" eslint-visitor-keys "^1.1.0" -esprima@2.7.x, esprima@^2.7.1: - version "2.7.3" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-2.7.3.tgz#96e3b70d5779f6ad49cd032673d1c312767ba581" - integrity sha1-luO3DVd59q1JzQMmc9HDEnZ7pYE= - esprima@^3.1.3, esprima@~3.1.0: version "3.1.3" resolved "https://registry.yarnpkg.com/esprima/-/esprima-3.1.3.tgz#fdca51cee6133895e3c88d535ce49dbff62a4633" @@ -14003,11 +13801,6 @@ esrecurse@^4.1.0: dependencies: estraverse "^4.1.0" -estraverse@^1.9.1: - version "1.9.3" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-1.9.3.tgz#af67f2dc922582415950926091a4005d29c9bb44" - integrity sha1-r2fy3JIlgkFZUJJgkaQAXSnJu0Q= - estraverse@^4.0.0, estraverse@^4.1.0, estraverse@^4.1.1, estraverse@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.2.0.tgz#0dee3fed31fcd469618ce7342099fc1afa0bdb13" @@ -14051,21 +13844,16 @@ event-target-shim@^5.0.0: resolved "https://registry.yarnpkg.com/event-target-shim/-/event-target-shim-5.0.1.tgz#5d4d3ebdf9583d63a5333ce2deb7480ab2b05789" integrity sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ== -eventemitter2@4.1.2: - version "4.1.2" - resolved "https://registry.yarnpkg.com/eventemitter2/-/eventemitter2-4.1.2.tgz#0e1a8477af821a6ef3995b311bf74c23a5247f15" - integrity sha1-DhqEd6+CGm7zmVsxG/dMI6UkfxU= +eventemitter2@6.4.2: + version "6.4.2" + resolved "https://registry.yarnpkg.com/eventemitter2/-/eventemitter2-6.4.2.tgz#f31f8b99d45245f0edbc5b00797830ff3b388970" + integrity sha512-r/Pwupa5RIzxIHbEKCkNXqpEQIIT4uQDxmP4G/Lug/NokVUWj0joz/WzWl3OxRpC5kDrH/WdiUJoR+IrwvXJEw== eventemitter2@~0.4.13: version "0.4.14" resolved "https://registry.yarnpkg.com/eventemitter2/-/eventemitter2-0.4.14.tgz#8f61b75cde012b2e9eb284d4545583b5643b61ab" integrity sha1-j2G3XN4BKy6esoTUVFWDtWQ7Yas= -eventemitter3@1.x.x: - version "1.2.0" - resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-1.2.0.tgz#1c86991d816ad1e504750e73874224ecf3bec508" - integrity sha1-HIaZHYFq0eUEdQ5zh0Ik7PO+xQg= - eventemitter3@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-3.1.0.tgz#090b4d6cdbd645ed10bf750d4b5407942d7ba163" @@ -14862,19 +14650,6 @@ filter-obj@^1.1.0: resolved "https://registry.yarnpkg.com/filter-obj/-/filter-obj-1.1.0.tgz#9b311112bc6c6127a16e016c6c5d7f19e0805c5b" integrity sha1-mzERErxsYSehbgFsbF1/GeCAXFs= -finalhandler@1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.1.0.tgz#ce0b6855b45853e791b2fcc680046d88253dd7f5" - integrity sha1-zgtoVbRYU+eRsvzGgARtiCU91/U= - dependencies: - debug "2.6.9" - encodeurl "~1.0.1" - escape-html "~1.0.3" - on-finished "~2.3.0" - parseurl "~1.3.2" - statuses "~1.3.1" - unpipe "~1.0.0" - finalhandler@1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.1.1.tgz#eebf4ed840079c83f4249038c9d703008301b105" @@ -15326,13 +15101,6 @@ front-matter@2.1.2: dependencies: js-yaml "^3.4.6" -fs-access@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/fs-access/-/fs-access-1.0.1.tgz#d6a87f262271cefebec30c553407fb995da8777a" - integrity sha1-1qh/JiJxzv6+wwxVNAf7mV2od3o= - dependencies: - null-check "^1.0.0" - fs-constants@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/fs-constants/-/fs-constants-1.0.0.tgz#6be0de9be998ce16af8afc24497b9ee9b7ccd9ad" @@ -15701,12 +15469,12 @@ getopts@^2.2.5: resolved "https://registry.yarnpkg.com/getopts/-/getopts-2.2.5.tgz#67a0fe471cacb9c687d817cab6450b96dde8313b" integrity sha512-9jb7AW5p3in+IiJWhQiZmmwkpLaR/ccTWdWQCtZM66HJcHHLegowh4q4tSD7gouUyeNvFWRavfK9GXosQHDpFA== -getos@3.1.4: - version "3.1.4" - resolved "https://registry.yarnpkg.com/getos/-/getos-3.1.4.tgz#29cdf240ed10a70c049add7b6f8cb08c81876faf" - integrity sha512-UORPzguEB/7UG5hqiZai8f0vQ7hzynMQyJLxStoQ8dPGAcmgsfXOPA4iE/fGtweHYkK+z4zc9V0g+CIFRf5HYw== +getos@3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/getos/-/getos-3.2.1.tgz#0134d1f4e00eb46144c5a9c0ac4dc087cbb27dc5" + integrity sha512-U56CfOK17OKgTVqozZjUKNdkfEv6jk5WISBJ8SHoagjE6L69zOwl3Z+O8myjY9MEW3i2HPWQBt/LTbCgcC973Q== dependencies: - async "^3.1.0" + async "^3.2.0" getos@^3.1.0: version "3.1.0" @@ -15730,6 +15498,14 @@ gh-got@^5.0.0: got "^6.2.0" is-plain-obj "^1.1.0" +gifwrap@^0.9.2: + version "0.9.2" + resolved "https://registry.yarnpkg.com/gifwrap/-/gifwrap-0.9.2.tgz#348e286e67d7cf57942172e1e6f05a71cee78489" + integrity sha512-fcIswrPaiCDAyO8xnWvHSZdWChjKXUanKKpAiWWJ/UTkEi/aYKn5+90e7DE820zbEaVR9CE2y4z9bzhQijZ0BA== + dependencies: + image-q "^1.1.1" + omggif "^1.0.10" + git-clone@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/git-clone/-/git-clone-0.1.0.tgz#0d76163778093aef7f1c30238f2a9ef3f07a2eb9" @@ -15861,17 +15637,6 @@ glob@7.1.4, glob@~7.1.4: once "^1.3.0" path-is-absolute "^1.0.0" -glob@^5.0.15, glob@~5.0.0: - version "5.0.15" - resolved "https://registry.yarnpkg.com/glob/-/glob-5.0.15.tgz#1bc936b9e02f4a603fcc222ecf7633d30b8b93b1" - integrity sha1-G8k2ueAvSmA/zCIuz3Yz0wuLk7E= - dependencies: - inflight "^1.0.4" - inherits "2" - minimatch "2 || 3" - once "^1.3.0" - path-is-absolute "^1.0.0" - glob@^6.0.1, glob@^6.0.4: version "6.0.4" resolved "https://registry.yarnpkg.com/glob/-/glob-6.0.4.tgz#0f08860f6a155127b2fadd4f9ce24b1aab6e4d22" @@ -15895,6 +15660,17 @@ glob@^7.0.5, glob@^7.1.3, glob@^7.1.4, glob@^7.1.6, glob@~7.1.6: once "^1.3.0" path-is-absolute "^1.0.0" +glob@~5.0.0: + version "5.0.15" + resolved "https://registry.yarnpkg.com/glob/-/glob-5.0.15.tgz#1bc936b9e02f4a603fcc222ecf7633d30b8b93b1" + integrity sha1-G8k2ueAvSmA/zCIuz3Yz0wuLk7E= + dependencies: + inflight "^1.0.4" + inherits "2" + minimatch "2 || 3" + once "^1.3.0" + path-is-absolute "^1.0.0" + glob@~7.0.0: version "7.0.6" resolved "https://registry.yarnpkg.com/glob/-/glob-7.0.6.tgz#211bafaf49e525b8cd93260d14ab136152b3f57a" @@ -16606,13 +16382,6 @@ grunt-contrib-watch@^1.1.0: lodash "^4.17.10" tiny-lr "^1.1.1" -grunt-karma@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/grunt-karma/-/grunt-karma-3.0.2.tgz#4f14386d43ee45f8f6b98081862e4910f5056764" - integrity sha512-imNhQO1bR1O7X6/3F5vO0o7mKy4xdkpSd40QVfxGO70cBAFcOqjv2Zu5QzsfEsSrppuu3N0vIQPbfBRjeGdpWg== - dependencies: - lodash "^4.17.10" - grunt-known-options@~1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/grunt-known-options/-/grunt-known-options-1.1.0.tgz#a4274eeb32fa765da5a7a3b1712617ce3b144149" @@ -16903,23 +16672,11 @@ has-ansi@^3.0.0: dependencies: ansi-regex "^3.0.0" -has-binary2@~1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/has-binary2/-/has-binary2-1.0.3.tgz#7776ac627f3ea77250cfc332dab7ddf5e4f5d11d" - integrity sha512-G1LWKhDSvhGeAQ8mPVQlqNcOB2sJdwATtZKl2pDKKHfpf/rYj24lkinxf69blJbnsvtqqNU+L3SL50vzZhXOnw== - dependencies: - isarray "2.0.1" - has-color@~0.1.0: version "0.1.7" resolved "https://registry.yarnpkg.com/has-color/-/has-color-0.1.7.tgz#67144a5260c34fc3cca677d041daf52fe7b78b2f" integrity sha1-ZxRKUmDDT8PMpnfQQdr1L+e3iy8= -has-cors@1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/has-cors/-/has-cors-1.1.0.tgz#5e474793f7ea9843d1bb99c23eef49ff126fff39" - integrity sha1-XkdHk/fqmEPRu5nCPu9J/xJv/zk= - has-flag@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa" @@ -17334,16 +17091,6 @@ http-deceiver@^1.2.7: resolved "https://registry.yarnpkg.com/http-deceiver/-/http-deceiver-1.2.7.tgz#fa7168944ab9a519d337cb0bec7284dc3e723d87" integrity sha1-+nFolEq5pRnTN8sL7HKE3D5yPYc= -http-errors@1.6.2, http-errors@~1.6.2: - version "1.6.2" - resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.6.2.tgz#0a002cc85707192a7e7946ceedc11155f60ec736" - integrity sha1-CgAsyFcHGSp+eUbO7cERVfYOxzY= - dependencies: - depd "1.1.1" - inherits "2.0.3" - setprototypeof "1.0.3" - statuses ">= 1.3.1 < 2" - http-errors@1.6.3, http-errors@~1.6.3: version "1.6.3" resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.6.3.tgz#8b55680bb4be283a0b5bf4ea2e38580be1d9320d" @@ -17365,6 +17112,16 @@ http-errors@1.7.2, http-errors@~1.7.2: statuses ">= 1.5.0 < 2" toidentifier "1.0.0" +http-errors@~1.6.2: + version "1.6.2" + resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.6.2.tgz#0a002cc85707192a7e7946ceedc11155f60ec736" + integrity sha1-CgAsyFcHGSp+eUbO7cERVfYOxzY= + dependencies: + depd "1.1.1" + inherits "2.0.3" + setprototypeof "1.0.3" + statuses ">= 1.3.1 < 2" + http-errors@~1.7.0: version "1.7.3" resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.7.3.tgz#6c619e4f9c60308c38519498c14fbb10aacebb06" @@ -17411,14 +17168,6 @@ http-proxy-middleware@0.19.1: lodash "^4.17.11" micromatch "^3.1.10" -http-proxy@^1.13.0: - version "1.16.2" - resolved "https://registry.yarnpkg.com/http-proxy/-/http-proxy-1.16.2.tgz#06dff292952bf64dbe8471fa9df73066d4f37742" - integrity sha1-Bt/ykpUr9k2+hHH6nfcwZtTzd0I= - dependencies: - eventemitter3 "1.x.x" - requires-port "1.x.x" - http-proxy@^1.17.0: version "1.17.0" resolved "https://registry.yarnpkg.com/http-proxy/-/http-proxy-1.17.0.tgz#7ad38494658f84605e2f6db4436df410f4e5be9a" @@ -17638,6 +17387,11 @@ ignore@^5.1.1, ignore@^5.1.4: resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.1.8.tgz#f150a8b50a34289b33e22f5889abd4d8016f0e57" integrity sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw== +image-q@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/image-q/-/image-q-1.1.1.tgz#fc84099664460b90ca862d9300b6bfbbbfbf8056" + integrity sha1-/IQJlmRGC5DKhi2TALa/u7+/gFY= + image-size@^0.8.2: version "0.8.3" resolved "https://registry.yarnpkg.com/image-size/-/image-size-0.8.3.tgz#f0b568857e034f29baffd37013587f2c0cad8b46" @@ -18059,6 +17813,15 @@ internal-ip@^4.3.0: default-gateway "^4.2.0" ipaddr.js "^1.9.0" +internal-slot@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/internal-slot/-/internal-slot-1.0.2.tgz#9c2e9fb3cd8e5e4256c6f45fe310067fcfa378a3" + integrity sha512-2cQNfwhAfJIkU4KZPkDI+Gj5yNNnbqi40W9Gge6dfnk4TocEVm00B3bdiL+JINrbGJil2TeHvM4rETGzk/f/0g== + dependencies: + es-abstract "^1.17.0-next.1" + has "^1.0.3" + side-channel "^1.0.2" + interpret@1.2.0, interpret@^1.0.0, interpret@^1.1.0, interpret@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.2.0.tgz#d5061a6224be58e8083985f5014d844359576296" @@ -18460,15 +18223,7 @@ is-hexadecimal@^1.0.0: resolved "https://registry.yarnpkg.com/is-hexadecimal/-/is-hexadecimal-1.0.1.tgz#6e084bbc92061fbb0971ec58b6ce6d404e24da69" integrity sha1-bghLvJIGH7sJcexYts5tQE4k2mk= -is-installed-globally@0.1.0, is-installed-globally@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/is-installed-globally/-/is-installed-globally-0.1.0.tgz#0dfd98f5a9111716dd535dda6492f67bf3d25a80" - integrity sha1-Df2Y9akRFxbdU13aZJL2e/PSWoA= - dependencies: - global-dirs "^0.1.0" - is-path-inside "^1.0.0" - -is-installed-globally@^0.3.1: +is-installed-globally@0.3.2, is-installed-globally@^0.3.1: version "0.3.2" resolved "https://registry.yarnpkg.com/is-installed-globally/-/is-installed-globally-0.3.2.tgz#fd3efa79ee670d1187233182d5b0a1dd00313141" integrity sha512-wZ8x1js7Ia0kecP/CHM/3ABkAmujX7WPvQk6uu3Fly/Mk44pySulQpnHG46OMjHGXApINnV4QhY3SWnECO2z5g== @@ -18476,6 +18231,14 @@ is-installed-globally@^0.3.1: global-dirs "^2.0.1" is-path-inside "^3.0.1" +is-installed-globally@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/is-installed-globally/-/is-installed-globally-0.1.0.tgz#0dfd98f5a9111716dd535dda6492f67bf3d25a80" + integrity sha1-Df2Y9akRFxbdU13aZJL2e/PSWoA= + dependencies: + global-dirs "^0.1.0" + is-path-inside "^1.0.0" + is-integer@^1.0.6: version "1.0.7" resolved "https://registry.yarnpkg.com/is-integer/-/is-integer-1.0.7.tgz#6bde81aacddf78b659b6629d629cadc51a886d5c" @@ -18906,11 +18669,6 @@ isarray@1.0.0, isarray@^1.0.0, isarray@~1.0.0: resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= -isarray@2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-2.0.1.tgz#a37d94ed9cda2d59865c9f76fe596ee1f338741e" - integrity sha1-o32U7ZzaLVmGXJ92/llu4fM4dB4= - isarray@^2.0.5: version "2.0.5" resolved "https://registry.yarnpkg.com/isarray/-/isarray-2.0.5.tgz#8af1e4c1221244cc62459faf38940d4e644a5723" @@ -18921,11 +18679,6 @@ isbinaryfile@4.0.2: resolved "https://registry.yarnpkg.com/isbinaryfile/-/isbinaryfile-4.0.2.tgz#bfc45642da645681c610cca831022e30af426488" integrity sha512-C3FSxJdNrEr2F4z6uFtNzECDM5hXk+46fxaa+cwBe5/XrWSmzdG8DDgyjfX6/NRdBB21q2JXuRAzPCUs+fclnQ== -isbinaryfile@^4.0.2: - version "4.0.6" - resolved "https://registry.yarnpkg.com/isbinaryfile/-/isbinaryfile-4.0.6.tgz#edcb62b224e2b4710830b67498c8e4e5a4d2610b" - integrity sha512-ORrEy+SNVqUhrCaal4hA4fBzhggQQ+BaLntyPOdoEiwlKZW9BZiJXjg3RMiruE4tPEI3pyVPpySHQF/dKWperg== - isemail@3.x.x: version "3.1.4" resolved "https://registry.yarnpkg.com/isemail/-/isemail-3.1.4.tgz#76e2187ff7bee59d57522c6fd1c3f09a331933cf" @@ -19083,26 +18836,6 @@ istanbul-reports@^3.0.2: html-escaper "^2.0.0" istanbul-lib-report "^3.0.0" -istanbul@^0.4.0: - version "0.4.5" - resolved "https://registry.yarnpkg.com/istanbul/-/istanbul-0.4.5.tgz#65c7d73d4c4da84d4f3ac310b918fb0b8033733b" - integrity sha1-ZcfXPUxNqE1POsMQuRj7C4Azczs= - dependencies: - abbrev "1.0.x" - async "1.x" - escodegen "1.8.x" - esprima "2.7.x" - glob "^5.0.15" - handlebars "^4.0.1" - js-yaml "3.x" - mkdirp "0.5.x" - nopt "3.x" - once "1.x" - resolve "1.1.x" - supports-color "^3.1.0" - which "^1.1.1" - wordwrap "^1.0.0" - istextorbinary@^2.1.0: version "2.2.1" resolved "https://registry.yarnpkg.com/istextorbinary/-/istextorbinary-2.2.1.tgz#a5231a08ef6dd22b268d0895084cf8d58b5bec53" @@ -19689,16 +19422,15 @@ jest@^25.5.4: import-local "^3.0.2" jest-cli "^25.5.4" -jimp@^0.9.6: - version "0.9.6" - resolved "https://registry.yarnpkg.com/jimp/-/jimp-0.9.6.tgz#abf381daf193a4fa335cb4ee0e22948049251eb9" - integrity sha512-DBDHYeNVqVpoPkcvo0PKTNGvD+i7NYvkKTsl0I3k7ql36uN8wGTptRg0HtgQyYE/bhGSLI6Lq5qLwewaOPXNfg== +jimp@^0.14.0: + version "0.14.0" + resolved "https://registry.yarnpkg.com/jimp/-/jimp-0.14.0.tgz#fde55f69bdb918c1b01ac633d89a25853af85625" + integrity sha512-8BXU+J8+SPmwwyq9ELihpSV4dWPTiOKBWCEgtkbnxxAVMjXdf3yGmyaLSshBfXc8sP/JQ9OZj5R8nZzz2wPXgA== dependencies: "@babel/runtime" "^7.7.2" - "@jimp/custom" "^0.9.6" - "@jimp/plugins" "^0.9.6" - "@jimp/types" "^0.9.6" - core-js "^3.4.1" + "@jimp/custom" "^0.14.0" + "@jimp/plugins" "^0.14.0" + "@jimp/types" "^0.14.0" regenerator-runtime "^0.13.3" jit-grunt@0.10.0: @@ -19720,10 +19452,10 @@ joi@13.x.x, joi@^13.5.2: isemail "3.x.x" topo "3.x.x" -jpeg-js@^0.3.4: - version "0.3.4" - resolved "https://registry.yarnpkg.com/jpeg-js/-/jpeg-js-0.3.4.tgz#dc2ba501ee3d58b7bb893c5d1fab47294917e7e7" - integrity sha512-6IzjQxvnlT8UlklNmDXIJMWxijULjqGrzgqc0OG7YadZdvm7KPQ1j0ehmQQHckgEWOfgpptzcnWgESovxudpTA== +jpeg-js@^0.4.0: + version "0.4.1" + resolved "https://registry.yarnpkg.com/jpeg-js/-/jpeg-js-0.4.1.tgz#937a3ae911eb6427f151760f8123f04c8bfe6ef7" + integrity sha512-jA55yJiB5tCXEddos8JBbvW+IMrqY0y1tjjx9KNVtA+QPmu7ND5j0zkKopClpUTsaETL135uOM2XfcYG4XRjmw== jquery@^3.5.0: version "3.5.0" @@ -19775,7 +19507,7 @@ js-tokens@^3.0.0, js-tokens@^3.0.2: resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== -js-yaml@3.13.1, js-yaml@3.x, js-yaml@^3.10.0, js-yaml@^3.13.1, js-yaml@^3.4.6, js-yaml@^3.5.1, js-yaml@^3.5.4, js-yaml@^3.9.0, js-yaml@~3.13.0, js-yaml@~3.13.1: +js-yaml@3.13.1, js-yaml@^3.10.0, js-yaml@^3.13.1, js-yaml@^3.4.6, js-yaml@^3.5.1, js-yaml@^3.5.4, js-yaml@^3.9.0, js-yaml@~3.13.0, js-yaml@~3.13.1: version "3.13.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.13.1.tgz#aff151b30bfdfa8e49e05da22e7415e9dfa37847" integrity sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw== @@ -20100,12 +19832,12 @@ jsx-ast-utils@^2.2.1: array-includes "^3.0.3" object.assign "^4.1.0" -jsx-ast-utils@^2.2.3: - version "2.2.3" - resolved "https://registry.yarnpkg.com/jsx-ast-utils/-/jsx-ast-utils-2.2.3.tgz#8a9364e402448a3ce7f14d357738310d9248054f" - integrity sha512-EdIHFMm+1BPynpKOpdPqiOsvnIrInRGJD7bzPZdPkjitQEqpdpUuFpq4T0npZFKTiB3RhWFdGN+oqOJIdhDhQA== +jsx-ast-utils@^2.4.1: + version "2.4.1" + resolved "https://registry.yarnpkg.com/jsx-ast-utils/-/jsx-ast-utils-2.4.1.tgz#1114a4c1209481db06c690c2b4f488cc665f657e" + integrity sha512-z1xSldJ6imESSzOjd3NNkieVJKRlKYSOtMG8SFyCj2FIrvSaSuli/WjpBkEzCBoR9bYYYFgqJw61Xhu7Lcgk+w== dependencies: - array-includes "^3.0.3" + array-includes "^3.1.1" object.assign "^4.1.0" jsx-to-string@^1.4.0: @@ -20186,92 +19918,16 @@ jws@^3.2.2: jwa "^1.4.1" safe-buffer "^5.0.1" -karma-chrome-launcher@2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/karma-chrome-launcher/-/karma-chrome-launcher-2.2.0.tgz#cf1b9d07136cc18fe239327d24654c3dbc368acf" - integrity sha512-uf/ZVpAabDBPvdPdveyk1EPgbnloPvFFGgmRhYLTDH7gEB4nZdSBk8yTU47w1g/drLSx5uMOkjKk7IWKfWg/+w== - dependencies: - fs-access "^1.0.0" - which "^1.2.1" - -karma-coverage@1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/karma-coverage/-/karma-coverage-1.1.2.tgz#cc09dceb589a83101aca5fe70c287645ef387689" - integrity sha512-eQawj4Cl3z/CjxslYy9ariU4uDh7cCNFZHNWXWRpl0pNeblY/4wHR7M7boTYXWrn9bY0z2pZmr11eKje/S/hIw== - dependencies: - dateformat "^1.0.6" - istanbul "^0.4.0" - lodash "^4.17.0" - minimatch "^3.0.0" - source-map "^0.5.1" - -karma-firefox-launcher@1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/karma-firefox-launcher/-/karma-firefox-launcher-1.1.0.tgz#2c47030452f04531eb7d13d4fc7669630bb93339" - integrity sha512-LbZ5/XlIXLeQ3cqnCbYLn+rOVhuMIK9aZwlP6eOLGzWdo1UVp7t6CN3DP4SafiRLjexKwHeKHDm0c38Mtd3VxA== - -karma-ie-launcher@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/karma-ie-launcher/-/karma-ie-launcher-1.0.0.tgz#497986842c490190346cd89f5494ca9830c6d59c" - integrity sha1-SXmGhCxJAZA0bNifVJTKmDDG1Zw= - dependencies: - lodash "^4.6.1" - -karma-junit-reporter@1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/karma-junit-reporter/-/karma-junit-reporter-1.2.0.tgz#4f9c40cedfb1a395f8aef876abf96189917c6396" - integrity sha1-T5xAzt+xo5X4rvh2q/lhiZF8Y5Y= - dependencies: - path-is-absolute "^1.0.0" - xmlbuilder "8.2.2" - -karma-mocha@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/karma-mocha/-/karma-mocha-2.0.0.tgz#ad6b56b6a72e9b191e4c432dd30f4a44fc2435bc" - integrity sha512-qiZkZDJnn2kb9t2m4LoM4cYJHJVPoxvAYYe0B+go5s+A/3vc/3psUT05zW4yFz4vT0xHf+XzTTery8zdr8GWgA== - dependencies: - minimist "^1.2.3" - -karma-safari-launcher@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/karma-safari-launcher/-/karma-safari-launcher-1.0.0.tgz#96982a2cc47d066aae71c553babb28319115a2ce" - integrity sha1-lpgqLMR9BmquccVTursoMZEVos4= - -karma@5.0.2: - version "5.0.2" - resolved "https://registry.yarnpkg.com/karma/-/karma-5.0.2.tgz#e404373dac6e3fa08409ae4d9eda7d83adb43ee5" - integrity sha512-RpUuCuGJfN3WnjYPGIH+VBF8023Lfm3TQH6D1kcNL+FxtEPc2UUz/nVjbVAGXH4Pm+Q7FVOAQjdAeFUpXpQ3IA== - dependencies: - body-parser "^1.16.1" - braces "^3.0.2" - chokidar "^3.0.0" - colors "^1.1.0" - connect "^3.6.0" - di "^0.0.1" - dom-serialize "^2.2.0" - flatted "^2.0.0" - glob "^7.1.1" - graceful-fs "^4.1.2" - http-proxy "^1.13.0" - isbinaryfile "^4.0.2" - lodash "^4.17.14" - log4js "^4.0.0" - mime "^2.3.1" - minimatch "^3.0.2" - qjobs "^1.1.4" - range-parser "^1.2.0" - rimraf "^2.6.0" - socket.io "2.1.1" - source-map "^0.6.1" - tmp "0.0.33" - ua-parser-js "0.7.21" - yargs "^15.3.1" - kdbush@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/kdbush/-/kdbush-3.0.0.tgz#f8484794d47004cc2d85ed3a79353dbe0abc2bf0" integrity sha512-hRkd6/XW4HTsA9vjVpY9tuXJYLSlelnkTmVFu4M9/7MIYQtFcHpbugAU7UbOfjOiVSVYl2fqgBuJ32JUmRo5Ew== +kea@^2.0.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/kea/-/kea-2.1.1.tgz#6e3c65c4873b67d270a2ec7bf73b0d178937234c" + integrity sha512-W9o4lHLOcEDIu3ASHPrWJJJzL1bMkGyxaHn9kuaDgI96ztBShVrf52R0QPGlQ2k9ca3XnkB/dnVHio1UB8kGWA== + kew@~0.1.7: version "0.1.7" resolved "https://registry.yarnpkg.com/kew/-/kew-0.1.7.tgz#0a32a817ff1a9b3b12b8c9bacf4bc4d679af8e72" @@ -21104,21 +20760,26 @@ lodash.uniq@^4.5.0: resolved "https://registry.yarnpkg.com/lodash.uniq/-/lodash.uniq-4.5.0.tgz#d0225373aeb652adc1bc82e4945339a842754773" integrity sha1-0CJTc662Uq3BvILklFM5qEJ1R3M= -lodash@4.17.11, lodash@4.17.15, lodash@>4.17.4, lodash@^4, lodash@^4.0.0, lodash@^4.0.1, lodash@^4.10.0, lodash@^4.11.1, lodash@^4.14.0, lodash@^4.15.0, lodash@^4.17.0, lodash@^4.17.10, lodash@^4.17.11, lodash@^4.17.12, lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.2, lodash@^4.17.4, lodash@^4.2.0, lodash@^4.2.1, lodash@^4.3.0, lodash@^4.6.1, lodash@~4.17.10, lodash@~4.17.15, lodash@~4.17.5: +lodash@4.17.11, lodash@>4.17.4, lodash@^4, lodash@^4.0.0, lodash@^4.0.1, lodash@^4.10.0, lodash@^4.11.1, lodash@^4.14.0, lodash@^4.15.0, lodash@^4.17.10, lodash@^4.17.11, lodash@^4.17.12, lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.16, lodash@^4.17.2, lodash@^4.17.4, lodash@^4.2.0, lodash@^4.2.1, lodash@^4.3.0, lodash@~4.17.10, lodash@~4.17.15, lodash@~4.17.5: + version "4.17.19" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b" + integrity sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ== + +lodash@4.17.15: version "4.17.15" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.15.tgz#b447f6670a0455bbfeedd11392eff330ea097548" integrity sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A== +lodash@4.17.19, lodash@^4.17.16: + version "4.17.19" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b" + integrity sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ== + lodash@^3.10.1: version "3.10.1" resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6" integrity sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y= -lodash@^4.17.16: - version "4.17.19" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b" - integrity sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ== - "lodash@npm:@elastic/lodash@3.10.1-kibana4": version "3.10.1-kibana4" resolved "https://registry.yarnpkg.com/@elastic/lodash/-/lodash-3.10.1-kibana4.tgz#d491228fd659b4a1b0dfa08ba9c67a4979b9746d" @@ -21177,17 +20838,6 @@ log-update@^1.0.2: ansi-escapes "^1.0.0" cli-cursor "^1.0.2" -log4js@^4.0.0: - version "4.5.1" - resolved "https://registry.yarnpkg.com/log4js/-/log4js-4.5.1.tgz#e543625e97d9e6f3e6e7c9fc196dd6ab2cae30b5" - integrity sha512-EEEgFcE9bLgaYUKuozyFfytQM2wDHtXn4tAN41pkaxpNjAykv11GVdeI4tHtmPWW4Xrgh9R/2d7XYghDVjbKKw== - dependencies: - date-format "^2.0.0" - debug "^4.1.1" - flatted "^2.0.0" - rfdc "^1.1.4" - streamroller "^1.0.6" - logform@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/logform/-/logform-2.1.2.tgz#957155ebeb67a13164069825ce67ddb5bb2dd360" @@ -22025,7 +21675,7 @@ minimist@1.2.0, minimist@^1.1.0, minimist@^1.1.1, minimist@^1.1.3, minimist@^1.2 resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" integrity sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ= -minimist@1.2.5, minimist@^1.2.3, minimist@^1.2.5: +minimist@1.2.5, minimist@^1.2.5: version "1.2.5" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602" integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw== @@ -22295,7 +21945,12 @@ moment-timezone@^0.5.27: dependencies: moment ">= 2.9.0" -moment@2.24.0, "moment@>= 2.9.0", moment@>=1.6.0, moment@>=2.14.0, moment@^2.10.6, moment@^2.24.0: +moment@2.26.0: + version "2.26.0" + resolved "https://registry.yarnpkg.com/moment/-/moment-2.26.0.tgz#5e1f82c6bafca6e83e808b30c8705eed0dcbd39a" + integrity sha512-oIixUO+OamkUkwjhAVE18rAMfRJNsNe/Stid/gwHSOfHrOtw9EhAY2AHvdKZ/k/MggcYELFCJz/Sn2pL8b8JMw== + +"moment@>= 2.9.0", moment@>=1.6.0, moment@>=2.14.0, moment@^2.10.6, moment@^2.24.0: version "2.24.0" resolved "https://registry.yarnpkg.com/moment/-/moment-2.24.0.tgz#0d055d53f5052aa653c9f6eb68bb5d12bf5c2b5b" integrity sha512-bV7f+6l2QigeBBZSM/6yTNq4P2fNpSWj/0e7jQcy87A8e7o2nAfP/34/2ky5Vw4B9S446EtIhodAzkFCcR4dQg== @@ -22947,7 +22602,7 @@ nodemon@^2.0.2: chalk "~0.4.0" underscore "~1.6.0" -"nopt@2 || 3", nopt@3.x, nopt@~3.0.1, nopt@~3.0.6: +"nopt@2 || 3", nopt@~3.0.1, nopt@~3.0.6: version "3.0.6" resolved "https://registry.yarnpkg.com/nopt/-/nopt-3.0.6.tgz#c6465dbf08abcd4db359317f79ac68a646b28ff9" integrity sha1-xkZdvwirzU2zWTF/eaxopkayj/k= @@ -23149,11 +22804,6 @@ nth-check@^1.0.2, nth-check@~1.0.1: dependencies: boolbase "~1.0.0" -null-check@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/null-check/-/null-check-1.0.0.tgz#977dffd7176012b9ec30d2a39db5cf72a0439edd" - integrity sha1-l33/1xdgErnsMNKjnbXPcqBDnt0= - null-loader@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/null-loader/-/null-loader-3.0.0.tgz#3e2b6c663c5bda8c73a54357d8fa0708dc61b245" @@ -23239,11 +22889,6 @@ object-assign@^3.0.0: resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-3.0.0.tgz#9bedd5ca0897949bca47e7ff408062d549f587f2" integrity sha1-m+3VygiXlJvKR+f/QIBi1Un1h/I= -object-component@0.0.3: - version "0.0.3" - resolved "https://registry.yarnpkg.com/object-component/-/object-component-0.0.3.tgz#f0c69aa50efc95b866c186f400a33769cb2f1291" - integrity sha1-8MaapQ78lbhmwYb0AKM3acsvEpE= - object-copy@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/object-copy/-/object-copy-0.1.0.tgz#7e7d858b781bd7c991a41ba975ed3812754e998c" @@ -23352,6 +22997,15 @@ object.entries@^1.0.4, object.entries@^1.1.0, object.entries@^1.1.1: function-bind "^1.1.1" has "^1.0.3" +object.entries@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/object.entries/-/object.entries-1.1.2.tgz#bc73f00acb6b6bb16c203434b10f9a7e797d3add" + integrity sha512-BQdB9qKmb/HyNdMNWVr7O3+z5MUIx3aiegEIJqjMBbBf0YT9RRxTJSim4mzFqtyr7PDAHigq0N9dO0m0tRakQA== + dependencies: + define-properties "^1.1.3" + es-abstract "^1.17.5" + has "^1.0.3" + object.fromentries@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/object.fromentries/-/object.fromentries-1.0.0.tgz#e90ec27445ec6e37f48be9af9077d9aa8bef0d40" @@ -23362,16 +23016,6 @@ object.fromentries@^1.0.0: function-bind "^1.1.1" has "^1.0.1" -object.fromentries@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/object.fromentries/-/object.fromentries-2.0.1.tgz#050f077855c7af8ae6649f45c80b16ee2d31e704" - integrity sha512-PUQv8Hbg3j2QX0IQYv3iAGCbGcu4yY4KQ92/dhA4sFSixBmSmp13UpDLs6jGK8rBtbmhNNIK99LD2k293jpiGA== - dependencies: - define-properties "^1.1.3" - es-abstract "^1.15.0" - function-bind "^1.1.1" - has "^1.0.3" - object.fromentries@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/object.fromentries/-/object.fromentries-2.0.2.tgz#4a09c9b9bb3843dd0f89acdb517a794d4f355ac9" @@ -23445,6 +23089,11 @@ octokit-pagination-methods@^1.1.0: resolved "https://registry.yarnpkg.com/octokit-pagination-methods/-/octokit-pagination-methods-1.1.0.tgz#cf472edc9d551055f9ef73f6e42b4dbb4c80bea4" integrity sha512-fZ4qZdQ2nxJvtcasX7Ghl+WlWS/d9IgnBIwFZXVNNZUmzpno91SX5bc5vuxiuKoCtK78XxGGNuSCrDC7xYB3OQ== +omggif@^1.0.10: + version "1.0.10" + resolved "https://registry.yarnpkg.com/omggif/-/omggif-1.0.10.tgz#ddaaf90d4a42f532e9e7cb3a95ecdd47f17c7b19" + integrity sha512-LMJTtvgc/nugXj0Vcrrs68Mn2D1r0zf630VNtqtpI1FEO7e+O9FP4gqs9AcnBaSEeoHIPm28u6qgPR0oyEpGSw== + omggif@^1.0.9: version "1.0.9" resolved "https://registry.yarnpkg.com/omggif/-/omggif-1.0.9.tgz#dcb7024dacd50c52b4d303f04802c91c057c765f" @@ -23462,7 +23111,7 @@ on-headers@~1.0.2: resolved "https://registry.yarnpkg.com/on-headers/-/on-headers-1.0.2.tgz#772b0ae6aaa525c399e489adfad90c403eb3c28f" integrity sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA== -once@1.x, once@^1.3.0, once@^1.3.1, once@^1.3.2, once@^1.4.0: +once@^1.3.0, once@^1.3.1, once@^1.3.2, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= @@ -24155,20 +23804,6 @@ parse5@^3.0.1: dependencies: "@types/node" "*" -parseqs@0.0.5: - version "0.0.5" - resolved "https://registry.yarnpkg.com/parseqs/-/parseqs-0.0.5.tgz#d5208a3738e46766e291ba2ea173684921a8b89d" - integrity sha1-1SCKNzjkZ2bikbouoXNoSSGouJ0= - dependencies: - better-assert "~1.0.0" - -parseuri@0.0.5: - version "0.0.5" - resolved "https://registry.yarnpkg.com/parseuri/-/parseuri-0.0.5.tgz#80204a50d4dbb779bfdc6ebe2778d90e4bce320a" - integrity sha1-gCBKUNTbt3m/3G6+J3jZDkvOMgo= - dependencies: - better-assert "~1.0.0" - parseurl@~1.3.2: version "1.3.2" resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.2.tgz#fc289d4ed8993119460c156253262cdc8de65bf3" @@ -25312,16 +24947,6 @@ q@^1.1.2: resolved "https://registry.yarnpkg.com/q/-/q-1.5.1.tgz#7e32f75b41381291d04611f1bf14109ac00651d7" integrity sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc= -qjobs@^1.1.4: - version "1.2.0" - resolved "https://registry.yarnpkg.com/qjobs/-/qjobs-1.2.0.tgz#c45e9c61800bd087ef88d7e256423bdd49e5d071" - integrity sha512-8YOJEHtxpySA3fFDyCRxA+UUV+fA+rTWnuWvylOK/NCjhY+b4ocCtmu8TtsWb+mYeU+GCHf/S66KZF/AsteKHg== - -qs@6.5.1: - version "6.5.1" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.1.tgz#349cdf6eef89ec45c12d7d5eb3fc0c870343a6d8" - integrity sha512-eRzhrN1WSINYCDCbrz796z37LOe3m5tmW7RQf6oBntukAG1nmovJvhnwHHRMAfeoItc1m2Hk02WER2aQ/iqs+A== - qs@6.5.2, qs@^6.4.0, qs@^6.5.1, qs@~6.5.1, qs@~6.5.2: version "6.5.2" resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.2.tgz#cb3ae806e8740444584ef154ce8ee98d403f3e36" @@ -25470,25 +25095,15 @@ randomfill@^1.0.3: randombytes "^2.0.5" safe-buffer "^5.1.0" -range-parser@^1.2.0, range-parser@~1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.0.tgz#f49be6b487894ddc40dcc94a322f611092e00d5e" - integrity sha1-9JvmtIeJTdxA3MlKMi9hEJLgDV4= - range-parser@^1.2.1, range-parser@~1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031" integrity sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg== -raw-body@2.3.2: - version "2.3.2" - resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.3.2.tgz#bcd60c77d3eb93cde0050295c3f379389bc88f89" - integrity sha1-vNYMd9Prk83gBQKVw/N5OJvIj4k= - dependencies: - bytes "3.0.0" - http-errors "1.6.2" - iconv-lite "0.4.19" - unpipe "1.0.0" +range-parser@~1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.0.tgz#f49be6b487894ddc40dcc94a322f611092e00d5e" + integrity sha1-9JvmtIeJTdxA3MlKMi9hEJLgDV4= raw-body@2.3.3: version "2.3.3" @@ -27374,7 +26989,7 @@ requirejs@^2.3.5: resolved "https://registry.yarnpkg.com/requirejs/-/requirejs-2.3.6.tgz#e5093d9601c2829251258c0b9445d4d19fa9e7c9" integrity sha512-ipEzlWQe6RK3jkzikgCupiTbTvm4S0/CAU5GlgptkN5SO6F3u0UD0K18wy6ErDqiCyP4J4YYe1HuAShvsxePLg== -requires-port@1.x.x, requires-port@^1.0.0: +requires-port@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/requires-port/-/requires-port-1.0.0.tgz#925d2601d39ac485e091cf0da5c6e694dc3dcaff" integrity sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8= @@ -27493,7 +27108,7 @@ resolve-url@^0.2.1: resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a" integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo= -resolve@1.1.7, resolve@1.1.x, resolve@~1.1.0, resolve@~1.1.7: +resolve@1.1.7, resolve@~1.1.0, resolve@~1.1.7: version "1.1.7" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" integrity sha1-IDEU2CrSxe2ejgQRs5ModeiJ6Xs= @@ -27505,7 +27120,7 @@ resolve@1.8.1: dependencies: path-parse "^1.0.5" -resolve@^1.1.10, resolve@^1.1.5, resolve@^1.1.6, resolve@^1.1.7, resolve@^1.10.0, resolve@^1.10.1, resolve@^1.11.0, resolve@^1.11.1, resolve@^1.12.0, resolve@^1.13.1, resolve@^1.17.0, resolve@^1.3.2, resolve@^1.4.0, resolve@^1.5.0, resolve@^1.7.1, resolve@^1.8.1: +resolve@^1.1.10, resolve@^1.1.5, resolve@^1.1.6, resolve@^1.1.7, resolve@^1.10.0, resolve@^1.10.1, resolve@^1.11.0, resolve@^1.11.1, resolve@^1.12.0, resolve@^1.17.0, resolve@^1.3.2, resolve@^1.4.0, resolve@^1.5.0, resolve@^1.7.1, resolve@^1.8.1: version "1.17.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" integrity sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w== @@ -27611,11 +27226,6 @@ rework@1.0.1: convert-source-map "^0.3.3" css "^2.0.0" -rfdc@^1.1.4: - version "1.1.4" - resolved "https://registry.yarnpkg.com/rfdc/-/rfdc-1.1.4.tgz#ba72cc1367a0ccd9cf81a870b3b58bd3ad07f8c2" - integrity sha512-5C9HXdzK8EAqN7JDif30jqsBzavB7wLpaubisuQIGHWf2gUXSpzy6ArX/+Da8RjFpagWsCn+pIgxTMAmKw9Zug== - right-align@^0.1.1: version "0.1.3" resolved "https://registry.yarnpkg.com/right-align/-/right-align-0.1.3.tgz#61339b722fe6a3515689210d24e14c96148613ef" @@ -27623,7 +27233,7 @@ right-align@^0.1.1: dependencies: align-text "^0.1.1" -rimraf@2, rimraf@^2.2.0, rimraf@^2.2.8, rimraf@^2.5.1, rimraf@^2.6.0, rimraf@^2.6.1, rimraf@^2.6.2: +rimraf@2, rimraf@^2.2.0, rimraf@^2.2.8, rimraf@^2.5.1, rimraf@^2.6.1, rimraf@^2.6.2: version "2.6.2" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.2.tgz#2ed8150d24a16ea8651e6d6ef0f47c4158ce7a36" integrity sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w== @@ -28694,52 +28304,6 @@ socket-location@^1.0.0: dependencies: await-event "^2.1.0" -socket.io-adapter@~1.1.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/socket.io-adapter/-/socket.io-adapter-1.1.1.tgz#2a805e8a14d6372124dd9159ad4502f8cb07f06b" - integrity sha1-KoBeihTWNyEk3ZFZrUUC+MsH8Gs= - -socket.io-client@2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/socket.io-client/-/socket.io-client-2.1.1.tgz#dcb38103436ab4578ddb026638ae2f21b623671f" - integrity sha512-jxnFyhAuFxYfjqIgduQlhzqTcOEQSn+OHKVfAxWaNWa7ecP7xSNk2Dx/3UEsDcY7NcFafxvNvKPmmO7HTwTxGQ== - dependencies: - backo2 "1.0.2" - base64-arraybuffer "0.1.5" - component-bind "1.0.0" - component-emitter "1.2.1" - debug "~3.1.0" - engine.io-client "~3.2.0" - has-binary2 "~1.0.2" - has-cors "1.1.0" - indexof "0.0.1" - object-component "0.0.3" - parseqs "0.0.5" - parseuri "0.0.5" - socket.io-parser "~3.2.0" - to-array "0.1.4" - -socket.io-parser@~3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/socket.io-parser/-/socket.io-parser-3.2.0.tgz#e7c6228b6aa1f814e6148aea325b51aa9499e077" - integrity sha512-FYiBx7rc/KORMJlgsXysflWx/RIvtqZbyGLlHZvjfmPTPeuD/I8MaW7cfFrj5tRltICJdgwflhfZ3NVVbVLFQA== - dependencies: - component-emitter "1.2.1" - debug "~3.1.0" - isarray "2.0.1" - -socket.io@2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/socket.io/-/socket.io-2.1.1.tgz#a069c5feabee3e6b214a75b40ce0652e1cfb9980" - integrity sha512-rORqq9c+7W0DAK3cleWNSyfv/qKXV99hV4tZe+gGLfBECw3XEhBy7x85F3wypA9688LKjtwO9pX9L33/xQI8yA== - dependencies: - debug "~3.1.0" - engine.io "~3.2.0" - has-binary2 "~1.0.2" - socket.io-adapter "~1.1.0" - socket.io-client "2.1.1" - socket.io-parser "~3.2.0" - sockjs-client@1.3.0: version "1.3.0" resolved "https://registry.yarnpkg.com/sockjs-client/-/sockjs-client-1.3.0.tgz#12fc9d6cb663da5739d3dc5fb6e8687da95cb177" @@ -28871,13 +28435,6 @@ source-map@~0.1.30: dependencies: amdefine ">=0.0.4" -source-map@~0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.2.0.tgz#dab73fbcfc2ba819b4de03bd6f6eaa48164b3f9d" - integrity sha1-2rc/vPwrqBm03gO9b26qSBZLP50= - dependencies: - amdefine ">=0.0.4" - sourcemap-codec@^1.4.1: version "1.4.6" resolved "https://registry.yarnpkg.com/sourcemap-codec/-/sourcemap-codec-1.4.6.tgz#e30a74f0402bad09807640d39e971090a08ce1e9" @@ -29220,11 +28777,6 @@ stats-lite@^2.2.0: resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.5.0.tgz#161c7dac177659fd9811f43771fa99381478628c" integrity sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow= -statuses@~1.3.1: - version "1.3.1" - resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.3.1.tgz#faf51b9eb74aaef3b3acf4ad5f61abf24cb7b93e" - integrity sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4= - stdout-stream@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/stdout-stream/-/stdout-stream-1.4.0.tgz#a2c7c8587e54d9427ea9edb3ac3f2cd522df378b" @@ -29298,17 +28850,6 @@ stream-spigot@~2.1.2: dependencies: readable-stream "~1.1.0" -streamroller@^1.0.6: - version "1.0.6" - resolved "https://registry.yarnpkg.com/streamroller/-/streamroller-1.0.6.tgz#8167d8496ed9f19f05ee4b158d9611321b8cacd9" - integrity sha512-3QC47Mhv3/aZNFpDDVO44qQb9gwB9QggMEE0sQmkTAwBVYdBRWISdsywlkfm5II1Q5y/pmrHflti/IgmIzdDBg== - dependencies: - async "^2.6.2" - date-format "^2.0.0" - debug "^3.2.6" - fs-extra "^7.0.1" - lodash "^4.17.14" - strict-uri-encode@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/strict-uri-encode/-/strict-uri-encode-1.1.0.tgz#279b225df1d582b1f54e65addd4352e18faa0713" @@ -29396,6 +28937,18 @@ string.prototype.matchall@^3.0.0: has-symbols "^1.0.0" regexp.prototype.flags "^1.2.0" +string.prototype.matchall@^4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/string.prototype.matchall/-/string.prototype.matchall-4.0.2.tgz#48bb510326fb9fdeb6a33ceaa81a6ea04ef7648e" + integrity sha512-N/jp6O5fMf9os0JU3E72Qhf590RSRZU/ungsL/qJUYVTNv7hTG0P/dbPjxINVN9jpscu3nzYwKESU3P3RY5tOg== + dependencies: + define-properties "^1.1.3" + es-abstract "^1.17.0" + has-symbols "^1.0.1" + internal-slot "^1.0.2" + regexp.prototype.flags "^1.3.0" + side-channel "^1.0.2" + string.prototype.padend@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/string.prototype.padend/-/string.prototype.padend-3.0.0.tgz#f3aaef7c1719f170c5eab1c32bf780d96e21f2f0" @@ -29800,7 +29353,7 @@ supports-color@^2.0.0: resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" integrity sha1-U10EXOa2Nj+kARcIRimZXp3zJMc= -supports-color@^3.1.0, supports-color@^3.1.2: +supports-color@^3.1.2: version "3.2.3" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-3.2.3.tgz#65ac0504b3954171d8a64946b2ae3cbb8a5f54f6" integrity sha1-ZawFBLOVQXHYpklGsq48u4pfVPY= @@ -30497,7 +30050,7 @@ tmp@0.0.30: dependencies: os-tmpdir "~1.0.1" -tmp@0.0.33, tmp@0.0.x, tmp@^0.0.33: +tmp@0.0.x, tmp@^0.0.33: version "0.0.33" resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" integrity sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw== @@ -30531,11 +30084,6 @@ to-absolute-glob@^2.0.0: is-absolute "^1.0.0" is-negated-glob "^1.0.0" -to-array@0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/to-array/-/to-array-0.1.4.tgz#17e6c11f73dd4f3d74cda7a4ff3238e9ad9bf890" - integrity sha1-F+bBH3PdTz10zaek/zI46a2b+JA= - to-arraybuffer@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz#7d229b1fcc637e466ca081180836a7aabff83f43" @@ -31429,7 +30977,7 @@ type-fest@^0.8.0, type-fest@^0.8.1: resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d" integrity sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA== -type-is@~1.6.15, type-is@~1.6.16: +type-is@~1.6.16: version "1.6.16" resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.16.tgz#f89ce341541c672b25ee7ae3c73dee3b2be50194" integrity sha512-HRkVv/5qY2G6I8iab9cI7v1bOIdhm94dVjQCPFElW9W+3GeDOSHmy2EBYe4VTApuzolPcmgFTN3ftVJRKR2J9Q== @@ -31510,7 +31058,7 @@ typings-tester@^0.3.2: dependencies: commander "^2.12.2" -ua-parser-js@0.7.21, ua-parser-js@^0.7.18, ua-parser-js@^0.7.9: +ua-parser-js@^0.7.18, ua-parser-js@^0.7.9: version "0.7.21" resolved "https://registry.yarnpkg.com/ua-parser-js/-/ua-parser-js-0.7.21.tgz#853cf9ce93f642f67174273cc34565ae6f308777" integrity sha512-+O8/qh/Qj8CgC6eYBVBykMrNtp5Gebn4dlGD/kKXVkJNDwyrAwSIqwz8CDf+tsAIWVycKcku6gIXJ0qwx/ZXaQ== @@ -31560,11 +31108,6 @@ uid-safe@2.1.5: dependencies: random-bytes "~1.0.0" -ultron@~1.1.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/ultron/-/ultron-1.1.1.tgz#9fe1536a10a664a65266a1e3ccf85fd36302bc9c" - integrity sha512-UIEXBNeYmKptWH6z8ZnqTeS8fV74zG0/eRU9VGkpzz+LIJNs8W/zM/L+7ctCkRrgbNnnR0xxw4bKOr0cW0N0Og== - unbzip2-stream@^1.0.9: version "1.2.5" resolved "https://registry.yarnpkg.com/unbzip2-stream/-/unbzip2-stream-1.2.5.tgz#73a033a567bbbde59654b193c44d48a7e4f43c47" @@ -32791,7 +32334,7 @@ vm-browserify@^1.0.1: resolved "https://registry.yarnpkg.com/vm-browserify/-/vm-browserify-1.1.0.tgz#bd76d6a23323e2ca8ffa12028dc04559c75f9019" integrity sha512-iq+S7vZJE60yejDYM0ek6zg308+UZsdtPExWP9VZoCFCz1zkJoXFnAX7aZfd/ZwrkidzdUZL0C/ryW+JwAiIGw== -void-elements@^2.0.0, void-elements@^2.0.1: +void-elements@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/void-elements/-/void-elements-2.0.1.tgz#c066afb582bb1cb4128d60ea92392e94d5e9dbec" integrity sha1-wGavtYK7HLQSjWDqkjkulNXp2+w= @@ -33216,7 +32759,7 @@ which@1, which@1.3.1, which@^1.2.9, which@^1.3.1, which@~1.3.0: dependencies: isexe "^2.0.0" -which@^1.1.1, which@^1.2.1, which@^1.2.14, which@^1.2.8: +which@^1.2.14, which@^1.2.8: version "1.3.0" resolved "https://registry.yarnpkg.com/which/-/which-1.3.0.tgz#ff04bdfc010ee547d780bec38e1ac1c2777d253a" integrity sha512-xcJpopdamTuY5duC/KnTTNBraPK54YwpenP4lzxU8H91GudWpFv38u0CKjclE1Wi2EH2EDz5LRcHcKbCIzqGyg== @@ -33556,15 +33099,6 @@ ws@^7.0.0: dependencies: async-limiter "^1.0.0" -ws@~3.3.1: - version "3.3.3" - resolved "https://registry.yarnpkg.com/ws/-/ws-3.3.3.tgz#f1cf84fe2d5e901ebce94efaece785f187a228f2" - integrity sha512-nnWLa/NwZSt4KQJu51MYlCcSQ5g7INpOrOMt4XV8j4dqTXdmlUmSHQ8/oLC069ckre0fRsgfvsKwbTdtKLCDkA== - dependencies: - async-limiter "~1.0.0" - safe-buffer "~5.1.0" - ultron "~1.1.0" - x-is-function@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/x-is-function/-/x-is-function-1.0.4.tgz#5d294dc3d268cbdd062580e0c5df77a391d1fa1e" @@ -33647,11 +33181,6 @@ xmlbuilder@13.0.2: resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-13.0.2.tgz#02ae33614b6a047d1c32b5389c1fdacb2bce47a7" integrity sha512-Eux0i2QdDYKbdbA6AM6xE4m6ZTZr4G4xF9kahI2ukSEMCzwce2eX9WlTI5J3s+NU7hpasFsr8hWIONae7LluAQ== -xmlbuilder@8.2.2: - version "8.2.2" - resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-8.2.2.tgz#69248673410b4ba42e1a6136551d2922335aa773" - integrity sha1-aSSGc0ELS6QuGmE2VR0pIjNap3M= - xmlbuilder@~11.0.0: version "11.0.1" resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-11.0.1.tgz#be9bae1c8a046e76b31127726347d0ad7002beb3" @@ -33672,11 +33201,6 @@ xmldom@0.1.27: resolved "https://registry.yarnpkg.com/xmldom/-/xmldom-0.1.27.tgz#d501f97b3bdb403af8ef9ecc20573187aadac0e9" integrity sha1-1QH5ezvbQDr4757MIFcxh6rawOk= -xmlhttprequest-ssl@~1.5.4: - version "1.5.5" - resolved "https://registry.yarnpkg.com/xmlhttprequest-ssl/-/xmlhttprequest-ssl-1.5.5.tgz#c2876b06168aadc40e57d97e81191ac8f4398b3e" - integrity sha1-wodrBhaKrcQOV9l+gRkayPQ5iz4= - xpath@0.0.27: version "0.0.27" resolved "https://registry.yarnpkg.com/xpath/-/xpath-0.0.27.tgz#dd3421fbdcc5646ac32c48531b4d7e9d0c2cfa92" @@ -33976,11 +33500,6 @@ yazl@^2.5.1: dependencies: buffer-crc32 "~0.2.3" -yeast@0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/yeast/-/yeast-0.1.2.tgz#008e06d8094320c372dbc2f8ed76a0ca6c8ac419" - integrity sha1-AI4G2AlDIMNy28L47XagymyKxBk= - yeoman-character@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/yeoman-character/-/yeoman-character-1.1.0.tgz#90d4b5beaf92759086177015b2fdfa2e0684d7c7"