diff --git a/packages/elastic-eslint-config-kibana/.eslintrc.js b/packages/elastic-eslint-config-kibana/.eslintrc.js index 2e978c543cc69..a8c2e9546510e 100644 --- a/packages/elastic-eslint-config-kibana/.eslintrc.js +++ b/packages/elastic-eslint-config-kibana/.eslintrc.js @@ -70,6 +70,11 @@ module.exports = { to: '@kbn/tinymath', disallowedMessage: `Don't use 'tinymath', use '@kbn/tinymath'` }, + { + from: '@kbn/test/types/ftr', + to: '@kbn/test', + disallowedMessage: `import from the root of @kbn/test instead` + }, ], ], }, diff --git a/packages/kbn-optimizer/limits.yml b/packages/kbn-optimizer/limits.yml index 5748984c7bc6e..348ecb7eea7f2 100644 --- a/packages/kbn-optimizer/limits.yml +++ b/packages/kbn-optimizer/limits.yml @@ -68,7 +68,7 @@ pageLoadAssetSize: searchprofiler: 67080 security: 95864 securityOss: 30806 - securitySolution: 187863 + securitySolution: 76000 share: 99061 snapshotRestore: 79032 spaces: 57868 diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_aliases.ts b/packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts similarity index 80% rename from x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_aliases.ts rename to packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts index d9e90cccc20af..885103c1fb584 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_aliases.ts +++ b/packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts @@ -1,11 +1,12 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. */ -import { ElasticsearchClient } from 'src/core/server'; +import { ElasticsearchClient } from '../elasticsearch_client'; interface AliasesResponse { [indexName: string]: { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_count.ts b/packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts similarity index 71% rename from x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_count.ts rename to packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts index f45ef0a9ff59f..523b41303a569 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_count.ts +++ b/packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts @@ -1,11 +1,12 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. */ -import { ElasticsearchClient } from 'src/core/server'; +import { ElasticsearchClient } from '../elasticsearch_client'; /** * Retrieves the count of documents in a given index diff --git a/packages/kbn-securitysolution-es-utils/src/index.ts b/packages/kbn-securitysolution-es-utils/src/index.ts index 657a63eef15cd..cfa6820e9aac5 100644 --- a/packages/kbn-securitysolution-es-utils/src/index.ts +++ b/packages/kbn-securitysolution-es-utils/src/index.ts @@ -12,9 +12,12 @@ export * from './delete_all_index'; export * from './delete_policy'; export * from './delete_template'; export * from './elasticsearch_client'; +export * from './get_index_aliases'; +export * from './get_index_count'; export * from './get_index_exists'; export * from './get_policy_exists'; export * from './get_template_exists'; +export * from './read_index'; export * from './read_privileges'; export * from './set_policy'; export * from './set_template'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/read_index.ts b/packages/kbn-securitysolution-es-utils/src/read_index/index.ts similarity index 55% rename from x-pack/plugins/security_solution/server/lib/detection_engine/index/read_index.ts rename to packages/kbn-securitysolution-es-utils/src/read_index/index.ts index 7674ca3b48304..cc16645120b70 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/read_index.ts +++ b/packages/kbn-securitysolution-es-utils/src/read_index/index.ts @@ -1,11 +1,12 @@ /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. */ -import { ElasticsearchClient } from 'kibana/server'; +import { ElasticsearchClient } from '../elasticsearch_client'; export const readIndex = async (esClient: ElasticsearchClient, index: string): Promise => { return esClient.indices.get({ diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/from/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/from/index.ts index 3bf4592a581f5..37ed4b2daa510 100644 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/from/index.ts +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/from/index.ts @@ -24,3 +24,6 @@ export const from = new t.Type( t.identity ); export type From = t.TypeOf; + +export const fromOrUndefined = t.union([from, t.undefined]); +export type FromOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/index.ts index 639140be049f2..c6f29862206e6 100644 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/index.ts +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/index.ts @@ -24,6 +24,7 @@ export * from './default_to_string'; export * from './default_uuid'; export * from './from'; export * from './language'; +export * from './machine_learning_job_id'; export * from './max_signals'; export * from './normalized_ml_job_id'; export * from './references_default_array'; @@ -38,3 +39,4 @@ export * from './threat_subtechnique'; export * from './threat_tactic'; export * from './threat_technique'; export * from './throttle'; +export * from './type'; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/language/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/language/index.ts index fc3f70f1f2d88..0632f09e6a393 100644 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/language/index.ts +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/language/index.ts @@ -10,3 +10,6 @@ import * as t from 'io-ts'; export const language = t.keyof({ eql: null, kuery: null, lucene: null }); export type Language = t.TypeOf; + +export const languageOrUndefined = t.union([language, t.undefined]); +export type LanguageOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/machine_learning_job_id/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/machine_learning_job_id/index.ts new file mode 100644 index 0000000000000..9e9c25c62b938 --- /dev/null +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/machine_learning_job_id/index.ts @@ -0,0 +1,19 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +/* eslint-disable @typescript-eslint/naming-convention */ + +import * as t from 'io-ts'; + +import { machine_learning_job_id_normalized } from '../normalized_ml_job_id'; + +export const machine_learning_job_id = t.union([t.string, machine_learning_job_id_normalized]); +export type MachineLearningJobId = t.TypeOf; + +export const machineLearningJobIdOrUndefined = t.union([machine_learning_job_id, t.undefined]); +export type MachineLearningJobIdOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/max_signals/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/max_signals/index.ts index 83360234c65a1..ef7a225d93733 100644 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/max_signals/index.ts +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/max_signals/index.ts @@ -13,3 +13,6 @@ import { PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-type export const max_signals = PositiveIntegerGreaterThanZero; export type MaxSignals = t.TypeOf; + +export const maxSignalsOrUndefined = t.union([max_signals, t.undefined]); +export type MaxSignalsOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.ts index 0aca7dd70ba1d..98b9c33e7e3ea 100644 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.ts +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score/index.ts @@ -6,6 +6,8 @@ * Side Public License, v 1. */ +/* eslint-disable @typescript-eslint/naming-convention */ + import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; @@ -26,3 +28,9 @@ export const RiskScore = new t.Type( ); export type RiskScoreC = typeof RiskScore; + +export const risk_score = RiskScore; +export type RiskScore = t.TypeOf; + +export const riskScoreOrUndefined = t.union([risk_score, t.undefined]); +export type RiskScoreOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score_mapping/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score_mapping/index.ts index b35b502811ec9..be07bab64f469 100644 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score_mapping/index.ts +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/risk_score_mapping/index.ts @@ -10,10 +10,7 @@ import * as t from 'io-ts'; import { operator } from '@kbn/securitysolution-io-ts-types'; -import { RiskScore } from '../risk_score'; - -export const riskScoreOrUndefined = t.union([RiskScore, t.undefined]); -export type RiskScoreOrUndefined = t.TypeOf; +import { riskScoreOrUndefined } from '../risk_score'; export const risk_score_mapping_field = t.string; export const risk_score_mapping_value = t.string; @@ -28,3 +25,6 @@ export const risk_score_mapping_item = t.exact( export const risk_score_mapping = t.array(risk_score_mapping_item); export type RiskScoreMapping = t.TypeOf; + +export const riskScoreMappingOrUndefined = t.union([risk_score_mapping, t.undefined]); +export type RiskScoreMappingOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat/index.ts index 0e4022e3ec26e..08ff6cca60a49 100644 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat/index.ts +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat/index.ts @@ -32,3 +32,6 @@ export type Threat = t.TypeOf; export const threats = t.array(threat); export type Threats = t.TypeOf; + +export const threatsOrUndefined = t.union([threats, t.undefined]); +export type ThreatsOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_subtechnique/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_subtechnique/index.ts index 8d64f53cb1623..4909b82d8ec54 100644 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_subtechnique/index.ts +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_subtechnique/index.ts @@ -21,3 +21,5 @@ export const threat_subtechnique = t.type({ }); export const threat_subtechniques = t.array(threat_subtechnique); + +export type ThreatSubtechnique = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_technique/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_technique/index.ts index ed2e771e1e118..2d56e842287d8 100644 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_technique/index.ts +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_technique/index.ts @@ -30,3 +30,5 @@ export const threat_technique = t.intersection([ ), ]); export const threat_techniques = t.array(threat_technique); + +export type ThreatTechnique = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/type/index.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/type/index.ts new file mode 100644 index 0000000000000..0e74037878992 --- /dev/null +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/type/index.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import * as t from 'io-ts'; + +export const type = t.keyof({ + eql: null, + machine_learning: null, + query: null, + saved_query: null, + threshold: null, + threat_match: null, +}); +export type Type = t.TypeOf; + +export const typeOrUndefined = t.union([type, t.undefined]); +export type TypeOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/index.ts index 1a1c1c3314821..3c60df315e430 100644 --- a/packages/kbn-securitysolution-io-ts-list-types/src/index.ts +++ b/packages/kbn-securitysolution-io-ts-list-types/src/index.ts @@ -16,7 +16,6 @@ export * from './default_create_comments_array'; export * from './default_namespace'; export * from './default_namespace_array'; export * from './default_update_comments_array'; -export * from './default_version_number'; export * from './description'; export * from './endpoint'; export * from './entries'; @@ -43,4 +42,3 @@ export * from './type'; export * from './update_comment'; export * from './updated_at'; export * from './updated_by'; -export * from './version'; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/type/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/type/index.ts index 90a8c36eb8b31..50cacb8e0259b 100644 --- a/packages/kbn-securitysolution-io-ts-list-types/src/type/index.ts +++ b/packages/kbn-securitysolution-io-ts-list-types/src/type/index.ts @@ -40,3 +40,4 @@ export const type = t.keyof({ export const typeOrUndefined = t.union([type, t.undefined]); export type Type = t.TypeOf; +export type TypeOrUndefined = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/default_version_number/index.test.ts b/packages/kbn-securitysolution-io-ts-types/src/default_version_number/index.test.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-list-types/src/default_version_number/index.test.ts rename to packages/kbn-securitysolution-io-ts-types/src/default_version_number/index.test.ts diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/default_version_number/index.ts b/packages/kbn-securitysolution-io-ts-types/src/default_version_number/index.ts similarity index 100% rename from packages/kbn-securitysolution-io-ts-list-types/src/default_version_number/index.ts rename to packages/kbn-securitysolution-io-ts-types/src/default_version_number/index.ts diff --git a/packages/kbn-securitysolution-io-ts-types/src/index.ts b/packages/kbn-securitysolution-io-ts-types/src/index.ts index 8b5a4d9e4de9a..fc0f017016e9f 100644 --- a/packages/kbn-securitysolution-io-ts-types/src/index.ts +++ b/packages/kbn-securitysolution-io-ts-types/src/index.ts @@ -13,6 +13,7 @@ export * from './default_empty_string'; export * from './default_string_array'; export * from './default_string_boolean_false'; export * from './default_uuid'; +export * from './default_version_number'; export * from './empty_string_array'; export * from './iso_date_string'; export * from './non_empty_array'; @@ -26,3 +27,4 @@ export * from './positive_integer'; export * from './positive_integer_greater_than_zero'; export * from './string_to_positive_number'; export * from './uuid'; +export * from './version'; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/version/index.ts b/packages/kbn-securitysolution-io-ts-types/src/version/index.ts similarity index 78% rename from packages/kbn-securitysolution-io-ts-list-types/src/version/index.ts rename to packages/kbn-securitysolution-io-ts-types/src/version/index.ts index 97a81b546c841..245b64781a7f8 100644 --- a/packages/kbn-securitysolution-io-ts-list-types/src/version/index.ts +++ b/packages/kbn-securitysolution-io-ts-types/src/version/index.ts @@ -7,7 +7,7 @@ */ import * as t from 'io-ts'; -import { PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-types'; +import { PositiveIntegerGreaterThanZero } from '../positive_integer_greater_than_zero'; /** * Note this is just a positive number, but we use it as a type here which is still ok. @@ -16,3 +16,6 @@ import { PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-type */ export const version = PositiveIntegerGreaterThanZero; export type Version = t.TypeOf; + +export const versionOrUndefined = t.union([version, t.undefined]); +export type VersionOrUndefined = t.TypeOf; diff --git a/packages/kbn-test/package.json b/packages/kbn-test/package.json index e8e42de3114aa..275d9fac73c58 100644 --- a/packages/kbn-test/package.json +++ b/packages/kbn-test/package.json @@ -3,8 +3,8 @@ "version": "1.0.0", "private": true, "license": "SSPL-1.0 OR Elastic License 2.0", - "main": "./target/index.js", - "types": "./target/types/index.d.ts", + "main": "./target", + "types": "./target/types", "scripts": { "build": "node scripts/build", "kbn:bootstrap": "node scripts/build --source-maps", diff --git a/packages/kbn-test/src/functional_test_runner/index.ts b/packages/kbn-test/src/functional_test_runner/index.ts index 80d257f1cfb23..268c6b2bd9a67 100644 --- a/packages/kbn-test/src/functional_test_runner/index.ts +++ b/packages/kbn-test/src/functional_test_runner/index.ts @@ -10,3 +10,4 @@ export { FunctionalTestRunner } from './functional_test_runner'; export { readConfigFile, Config } from './lib'; export { runFtrCli } from './cli'; export * from './lib/docker_servers'; +export * from './public_types'; diff --git a/packages/kbn-test/types/ftr.d.ts b/packages/kbn-test/src/functional_test_runner/public_types.ts similarity index 94% rename from packages/kbn-test/types/ftr.d.ts rename to packages/kbn-test/src/functional_test_runner/public_types.ts index 83f725d86857e..915cb34f6ffe5 100644 --- a/packages/kbn-test/types/ftr.d.ts +++ b/packages/kbn-test/src/functional_test_runner/public_types.ts @@ -7,13 +7,9 @@ */ import { ToolingLog } from '@kbn/dev-utils'; -import { - Config, - Lifecycle, - FailureMetadata, - DockerServersService, -} from '../src/functional_test_runner/lib'; -import { Test, Suite } from '../src/functional_test_runner/fake_mocha_types'; + +import { Config, Lifecycle, FailureMetadata, DockerServersService } from './lib'; +import { Test, Suite } from './fake_mocha_types'; export { Lifecycle, Config, FailureMetadata }; diff --git a/packages/kbn-test/tsconfig.json b/packages/kbn-test/tsconfig.json index 8536ad7e0c12f..3cb68029d74cf 100644 --- a/packages/kbn-test/tsconfig.json +++ b/packages/kbn-test/tsconfig.json @@ -8,19 +8,17 @@ "declaration": true, "declarationMap": true, "sourceMap": true, - "sourceRoot": "../../../../../packages/kbn-test/src", + "sourceRoot": "../../../../../../packages/kbn-test/src", "types": [ "jest", "node" ], }, "include": [ - "types/**/*", "src/**/*", "index.d.ts" ], "exclude": [ - "types/ftr_globals/**/*", "**/__fixtures__/**/*" ] } diff --git a/packages/kbn-test/types/README.md b/packages/kbn-test/types/README.md deleted file mode 100644 index 1298d2a4afc0a..0000000000000 --- a/packages/kbn-test/types/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# @kbn/test/types - -Shared types used by different parts of the tests - - - **`ftr.d.ts`**: These types are generic types for using the functional test runner. They are here because we plan to move the functional test runner into the `@kbn/test` package at some point and having them here makes them a lot easier to import from all over the place like we do. \ No newline at end of file diff --git a/src/plugins/home/server/services/index.ts b/src/plugins/home/server/services/index.ts index 7f26c886ab4b6..5674a3501f064 100644 --- a/src/plugins/home/server/services/index.ts +++ b/src/plugins/home/server/services/index.ts @@ -15,7 +15,6 @@ export type { TutorialsRegistrySetup, TutorialsRegistryStart } from './tutorials export { TutorialsCategory } from './tutorials'; export type { - ParamTypes, InstructionSetSchema, ParamsSchema, InstructionsSchema, diff --git a/src/plugins/home/server/services/sample_data/lib/sample_dataset_registry_types.ts b/src/plugins/home/server/services/sample_data/lib/sample_dataset_registry_types.ts index 4d9dc3885e67d..09af7728f74d2 100644 --- a/src/plugins/home/server/services/sample_data/lib/sample_dataset_registry_types.ts +++ b/src/plugins/home/server/services/sample_data/lib/sample_dataset_registry_types.ts @@ -6,7 +6,8 @@ * Side Public License, v 1. */ -import { SavedObject } from 'src/core/server'; +import type { SampleDatasetSchema } from './sample_dataset_schema'; +export type { SampleDatasetSchema, AppLinkSchema, DataIndexSchema } from './sample_dataset_schema'; export enum DatasetStatusTypes { NOT_INSTALLED = 'not_installed', @@ -26,57 +27,4 @@ export enum EmbeddableTypes { SEARCH_EMBEDDABLE_TYPE = 'search', VISUALIZE_EMBEDDABLE_TYPE = 'visualization', } -export interface DataIndexSchema { - id: string; - - // path to newline delimented JSON file containing data relative to KIBANA_HOME - dataPath: string; - - // Object defining Elasticsearch field mappings (contents of index.mappings.type.properties) - fields: object; - - // times fields that will be updated relative to now when data is installed - timeFields: string[]; - - // Reference to now in your test data set. - // When data is installed, timestamps are converted to the present time. - // The distance between a timestamp and currentTimeMarker is preserved but the date and time will change. - // For example: - // sample data set: timestamp: 2018-01-01T00:00:00Z, currentTimeMarker: 2018-01-01T12:00:00Z - // installed data set: timestamp: 2018-04-18T20:33:14Z, currentTimeMarker: 2018-04-19T08:33:14Z - currentTimeMarker: string; - - // Set to true to move timestamp to current week, preserving day of week and time of day - // Relative distance from timestamp to currentTimeMarker will not remain the same - preserveDayOfWeekTimeOfDay: boolean; -} - -export interface AppLinkSchema { - path: string; - icon: string; - label: string; -} - -export interface SampleDatasetSchema { - id: string; - name: string; - description: string; - previewImagePath: string; - darkPreviewImagePath: string; - - // saved object id of main dashboard for sample data set - overviewDashboard: string; - appLinks: AppLinkSchema[]; - - // saved object id of default index-pattern for sample data set - defaultIndex: string; - - // Kibana saved objects (index patter, visualizations, dashboard, ...) - // Should provide a nice demo of Kibana's functionality with the sample data set - savedObjects: Array>; - dataIndices: DataIndexSchema[]; - status?: string | undefined; - statusMsg?: unknown; -} - export type SampleDatasetProvider = () => SampleDatasetSchema; diff --git a/src/plugins/home/server/services/sample_data/lib/sample_dataset_schema.ts b/src/plugins/home/server/services/sample_data/lib/sample_dataset_schema.ts index eb0b2252774b5..3c1764b2b8df1 100644 --- a/src/plugins/home/server/services/sample_data/lib/sample_dataset_schema.ts +++ b/src/plugins/home/server/services/sample_data/lib/sample_dataset_schema.ts @@ -5,22 +5,27 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ +import type { Writable } from '@kbn/utility-types'; +import { schema, TypeOf } from '@kbn/config-schema'; -import Joi from 'joi'; - -const dataIndexSchema = Joi.object({ - id: Joi.string() - .regex(/^[a-zA-Z0-9-]+$/) - .required(), +const idRegExp = /^[a-zA-Z0-9-]+$/; +const dataIndexSchema = schema.object({ + id: schema.string({ + validate(value: string) { + if (!idRegExp.test(value)) { + return `Does not satisfy regexp: ${idRegExp.toString()}`; + } + }, + }), // path to newline delimented JSON file containing data relative to KIBANA_HOME - dataPath: Joi.string().required(), + dataPath: schema.string(), // Object defining Elasticsearch field mappings (contents of index.mappings.type.properties) - fields: Joi.object().required(), + fields: schema.recordOf(schema.string(), schema.any()), // times fields that will be updated relative to now when data is installed - timeFields: Joi.array().items(Joi.string()).required(), + timeFields: schema.arrayOf(schema.string()), // Reference to now in your test data set. // When data is installed, timestamps are converted to the present time. @@ -28,37 +33,66 @@ const dataIndexSchema = Joi.object({ // For example: // sample data set: timestamp: 2018-01-01T00:00:00Z, currentTimeMarker: 2018-01-01T12:00:00Z // installed data set: timestamp: 2018-04-18T20:33:14Z, currentTimeMarker: 2018-04-19T08:33:14Z - currentTimeMarker: Joi.string().isoDate().required(), + currentTimeMarker: schema.string({ + validate(value: string) { + if (isNaN(Date.parse(value))) { + return 'Expected a valid string in iso format'; + } + }, + }), // Set to true to move timestamp to current week, preserving day of week and time of day // Relative distance from timestamp to currentTimeMarker will not remain the same - preserveDayOfWeekTimeOfDay: Joi.boolean().default(false), + preserveDayOfWeekTimeOfDay: schema.boolean({ defaultValue: false }), }); -const appLinkSchema = Joi.object({ - path: Joi.string().required(), - label: Joi.string().required(), - icon: Joi.string().required(), +export type DataIndexSchema = TypeOf; + +const appLinkSchema = schema.object({ + path: schema.string(), + label: schema.string(), + icon: schema.string(), }); +export type AppLinkSchema = TypeOf; -export const sampleDataSchema = { - id: Joi.string() - .regex(/^[a-zA-Z0-9-]+$/) - .required(), - name: Joi.string().required(), - description: Joi.string().required(), - previewImagePath: Joi.string().required(), - darkPreviewImagePath: Joi.string(), +export const sampleDataSchema = schema.object({ + id: schema.string({ + validate(value: string) { + if (!idRegExp.test(value)) { + return `Does not satisfy regexp: ${idRegExp.toString()}`; + } + }, + }), + name: schema.string(), + description: schema.string(), + previewImagePath: schema.string(), + darkPreviewImagePath: schema.maybe(schema.string()), // saved object id of main dashboard for sample data set - overviewDashboard: Joi.string().required(), - appLinks: Joi.array().items(appLinkSchema).default([]), + overviewDashboard: schema.string(), + appLinks: schema.arrayOf(appLinkSchema, { defaultValue: [] }), // saved object id of default index-pattern for sample data set - defaultIndex: Joi.string().required(), + defaultIndex: schema.string(), // Kibana saved objects (index patter, visualizations, dashboard, ...) // Should provide a nice demo of Kibana's functionality with the sample data set - savedObjects: Joi.array().items(Joi.object()).required(), - dataIndices: Joi.array().items(dataIndexSchema).required(), -}; + savedObjects: schema.arrayOf( + schema.object( + { + id: schema.string(), + type: schema.string(), + attributes: schema.any(), + references: schema.arrayOf(schema.any()), + version: schema.maybe(schema.any()), + }, + { unknowns: 'allow' } + ) + ), + dataIndices: schema.arrayOf(dataIndexSchema), + + status: schema.maybe(schema.string()), + statusMsg: schema.maybe(schema.string()), +}); + +export type SampleDatasetSchema = Writable>; diff --git a/src/plugins/home/server/services/sample_data/routes/install.ts b/src/plugins/home/server/services/sample_data/routes/install.ts index e5ff33d5c199d..d0457f0a6d301 100644 --- a/src/plugins/home/server/services/sample_data/routes/install.ts +++ b/src/plugins/home/server/services/sample_data/routes/install.ts @@ -7,7 +7,12 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter, Logger, IScopedClusterClient } from 'src/core/server'; +import type { + IRouter, + Logger, + IScopedClusterClient, + SavedObjectsBulkCreateObject, +} from 'src/core/server'; import { SampleDatasetSchema } from '../lib/sample_dataset_registry_types'; import { createIndexName } from '../lib/create_index_name'; import { @@ -148,8 +153,9 @@ export function createInstallRoute( const client = getClient({ includedHiddenTypes }); + const savedObjects = sampleDataset.savedObjects as SavedObjectsBulkCreateObject[]; createResults = await client.bulkCreate( - sampleDataset.savedObjects.map(({ version, ...savedObject }) => savedObject), + savedObjects.map(({ version, ...savedObject }) => savedObject), { overwrite: true } ); } catch (err) { diff --git a/src/plugins/home/server/services/sample_data/sample_data_registry.ts b/src/plugins/home/server/services/sample_data/sample_data_registry.ts index ca75d20dc1d3f..dff0d86409974 100644 --- a/src/plugins/home/server/services/sample_data/sample_data_registry.ts +++ b/src/plugins/home/server/services/sample_data/sample_data_registry.ts @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import Joi from 'joi'; import { CoreSetup, PluginInitializerContext } from 'src/core/server'; import { SavedObject } from 'src/core/public'; import { @@ -55,11 +54,13 @@ export class SampleDataRegistry { return { registerSampleDataset: (specProvider: SampleDatasetProvider) => { - const { error, value } = Joi.validate(specProvider(), sampleDataSchema); - - if (error) { + let value: SampleDatasetSchema; + try { + value = sampleDataSchema.validate(specProvider()); + } catch (error) { throw new Error(`Unable to register sample dataset spec because it's invalid. ${error}`); } + const defaultIndexSavedObjectJson = value.savedObjects.find((savedObjectJson: any) => { return ( savedObjectJson.type === 'index-pattern' && savedObjectJson.id === value.defaultIndex diff --git a/src/plugins/home/server/services/tutorials/index.ts b/src/plugins/home/server/services/tutorials/index.ts index 92f6de716185d..f745d0190efd5 100644 --- a/src/plugins/home/server/services/tutorials/index.ts +++ b/src/plugins/home/server/services/tutorials/index.ts @@ -12,7 +12,6 @@ export type { TutorialsRegistrySetup, TutorialsRegistryStart } from './tutorials export { TutorialsCategory } from './lib/tutorials_registry_types'; export type { - ParamTypes, InstructionSetSchema, ParamsSchema, InstructionsSchema, diff --git a/src/plugins/home/server/services/tutorials/lib/tutorial_schema.ts b/src/plugins/home/server/services/tutorials/lib/tutorial_schema.ts index 0f06b6c3257c2..5efbe067f6ece 100644 --- a/src/plugins/home/server/services/tutorials/lib/tutorial_schema.ts +++ b/src/plugins/home/server/services/tutorials/lib/tutorial_schema.ts @@ -5,121 +5,153 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ +import { schema, TypeOf } from '@kbn/config-schema'; -import Joi from 'joi'; - -const PARAM_TYPES = { - NUMBER: 'number', - STRING: 'string', -}; - -const TUTORIAL_CATEGORY = { - LOGGING: 'logging', - SECURITY_SOLUTION: 'security solution', - METRICS: 'metrics', - OTHER: 'other', -}; - -const dashboardSchema = Joi.object({ - id: Joi.string().required(), // Dashboard saved object id - linkLabel: Joi.string().when('isOverview', { - is: true, - then: Joi.required(), - }), +const dashboardSchema = schema.object({ + // Dashboard saved object id + id: schema.string(), // Is this an Overview / Entry Point dashboard? - isOverview: Joi.boolean().required(), + isOverview: schema.boolean(), + linkLabel: schema.conditional( + schema.siblingRef('isOverview'), + true, + schema.string(), + schema.maybe(schema.string()) + ), }); +export type DashboardSchema = TypeOf; -const artifactsSchema = Joi.object({ +const artifactsSchema = schema.object({ // Fields present in Elasticsearch documents created by this product. - exportedFields: Joi.object({ - documentationUrl: Joi.string().required(), - }), + exportedFields: schema.maybe( + schema.object({ + documentationUrl: schema.string(), + }) + ), // Kibana dashboards created by this product. - dashboards: Joi.array().items(dashboardSchema).required(), - application: Joi.object({ - path: Joi.string().required(), - label: Joi.string().required(), - }), + dashboards: schema.arrayOf(dashboardSchema), + application: schema.maybe( + schema.object({ + path: schema.string(), + label: schema.string(), + }) + ), }); - -const statusCheckSchema = Joi.object({ - title: Joi.string(), - text: Joi.string(), - btnLabel: Joi.string(), - success: Joi.string(), - error: Joi.string(), - esHitsCheck: Joi.object({ - index: Joi.alternatives().try(Joi.string(), Joi.array().items(Joi.string())).required(), - query: Joi.object().required(), - }).required(), +export type ArtifactsSchema = TypeOf; + +const statusCheckSchema = schema.object({ + title: schema.maybe(schema.string()), + text: schema.maybe(schema.string()), + btnLabel: schema.maybe(schema.string()), + success: schema.maybe(schema.string()), + error: schema.maybe(schema.string()), + esHitsCheck: schema.object({ + index: schema.oneOf([schema.string(), schema.arrayOf(schema.string())]), + query: schema.recordOf(schema.string(), schema.any()), + }), }); -const instructionSchema = Joi.object({ - title: Joi.string(), - textPre: Joi.string(), - commands: Joi.array().items(Joi.string().allow('')), - textPost: Joi.string(), +const instructionSchema = schema.object({ + title: schema.maybe(schema.string()), + textPre: schema.maybe(schema.string()), + commands: schema.maybe(schema.arrayOf(schema.string())), + textPost: schema.maybe(schema.string()), }); +export type Instruction = TypeOf; -const instructionVariantSchema = Joi.object({ - id: Joi.string().required(), - instructions: Joi.array().items(instructionSchema).required(), +const instructionVariantSchema = schema.object({ + id: schema.string(), + instructions: schema.arrayOf(instructionSchema), }); -const instructionSetSchema = Joi.object({ - title: Joi.string(), - callOut: Joi.object({ - title: Joi.string().required(), - message: Joi.string(), - iconType: Joi.string(), - }), +export type InstructionVariant = TypeOf; + +const instructionSetSchema = schema.object({ + title: schema.maybe(schema.string()), + callOut: schema.maybe( + schema.object({ + title: schema.string(), + message: schema.maybe(schema.string()), + iconType: schema.maybe(schema.string()), + }) + ), // Variants (OSes, languages, etc.) for which tutorial instructions are specified. - instructionVariants: Joi.array().items(instructionVariantSchema).required(), - statusCheck: statusCheckSchema, + instructionVariants: schema.arrayOf(instructionVariantSchema), + statusCheck: schema.maybe(statusCheckSchema), }); - -const paramSchema = Joi.object({ - defaultValue: Joi.required(), - id: Joi.string() - .regex(/^[a-zA-Z_]+$/) - .required(), - label: Joi.string().required(), - type: Joi.string().valid(Object.values(PARAM_TYPES)).required(), +export type InstructionSetSchema = TypeOf; + +const idRegExp = /^[a-zA-Z_]+$/; +const paramSchema = schema.object({ + defaultValue: schema.any(), + id: schema.string({ + validate(value: string) { + if (!idRegExp.test(value)) { + return `Does not satisfy regexp ${idRegExp.toString()}`; + } + }, + }), + label: schema.string(), + type: schema.oneOf([schema.literal('number'), schema.literal('string')]), }); +export type ParamsSchema = TypeOf; -const instructionsSchema = Joi.object({ - instructionSets: Joi.array().items(instructionSetSchema).required(), - params: Joi.array().items(paramSchema), +const instructionsSchema = schema.object({ + instructionSets: schema.arrayOf(instructionSetSchema), + params: schema.maybe(schema.arrayOf(paramSchema)), }); - -export const tutorialSchema = { - id: Joi.string() - .regex(/^[a-zA-Z0-9-]+$/) - .required(), - category: Joi.string().valid(Object.values(TUTORIAL_CATEGORY)).required(), - name: Joi.string().required(), - moduleName: Joi.string(), - isBeta: Joi.boolean().default(false), - shortDescription: Joi.string().required(), - euiIconType: Joi.string(), // EUI icon type string, one of https://elastic.github.io/eui/#/icons - longDescription: Joi.string().required(), - completionTimeMinutes: Joi.number().integer(), - previewImagePath: Joi.string(), - +export type InstructionsSchema = TypeOf; + +const tutorialIdRegExp = /^[a-zA-Z0-9-]+$/; +export const tutorialSchema = schema.object({ + id: schema.string({ + validate(value: string) { + if (!tutorialIdRegExp.test(value)) { + return `Does not satisfy regexp ${tutorialIdRegExp.toString()}`; + } + }, + }), + category: schema.oneOf([ + schema.literal('logging'), + schema.literal('security'), + schema.literal('metrics'), + schema.literal('other'), + ]), + name: schema.string({ + validate(value: string) { + if (value === '') { + return 'is not allowed to be empty'; + } + }, + }), + moduleName: schema.maybe(schema.string()), + isBeta: schema.maybe(schema.boolean()), + shortDescription: schema.string(), + // EUI icon type string, one of https://elastic.github.io/eui/#/icons + euiIconType: schema.maybe(schema.string()), + longDescription: schema.string(), + completionTimeMinutes: schema.maybe( + schema.number({ + validate(value: number) { + if (!Number.isInteger(value)) { + return 'Expected to be a valid integer number'; + } + }, + }) + ), + previewImagePath: schema.maybe(schema.string()), // kibana and elastic cluster running on prem - onPrem: instructionsSchema.required(), - + onPrem: instructionsSchema, // kibana and elastic cluster running in elastic's cloud - elasticCloud: instructionsSchema, - + elasticCloud: schema.maybe(instructionsSchema), // kibana running on prem and elastic cluster running in elastic's cloud - onPremElasticCloud: instructionsSchema, - + onPremElasticCloud: schema.maybe(instructionsSchema), // Elastic stack artifacts produced by product when it is setup and run. - artifacts: artifactsSchema, + artifacts: schema.maybe(artifactsSchema), // saved objects used by data module. - savedObjects: Joi.array().items(), - savedObjectsInstallMsg: Joi.string(), -}; + savedObjects: schema.maybe(schema.arrayOf(schema.any())), + savedObjectsInstallMsg: schema.maybe(schema.string()), +}); + +export type TutorialSchema = TypeOf; diff --git a/src/plugins/home/server/services/tutorials/lib/tutorials_registry_types.ts b/src/plugins/home/server/services/tutorials/lib/tutorials_registry_types.ts index b0837a99d65ad..4c80c8858a475 100644 --- a/src/plugins/home/server/services/tutorials/lib/tutorials_registry_types.ts +++ b/src/plugins/home/server/services/tutorials/lib/tutorials_registry_types.ts @@ -6,8 +6,18 @@ * Side Public License, v 1. */ -import { IconType } from '@elastic/eui'; -import { KibanaRequest } from 'src/core/server'; +import type { KibanaRequest } from 'src/core/server'; +import type { TutorialSchema } from './tutorial_schema'; +export type { + TutorialSchema, + ArtifactsSchema, + DashboardSchema, + InstructionsSchema, + ParamsSchema, + InstructionSetSchema, + InstructionVariant, + Instruction, +} from './tutorial_schema'; /** @public */ export enum TutorialsCategory { @@ -18,82 +28,6 @@ export enum TutorialsCategory { } export type Platform = 'WINDOWS' | 'OSX' | 'DEB' | 'RPM'; -export interface ParamTypes { - NUMBER: string; - STRING: string; -} -export interface Instruction { - title?: string; - textPre?: string; - commands?: string[]; - textPost?: string; -} -export interface InstructionVariant { - id: string; - instructions: Instruction[]; -} -export interface InstructionSetSchema { - readonly title?: string; - readonly callOut?: { - title: string; - message?: string; - iconType?: IconType; - }; - instructionVariants: InstructionVariant[]; -} -export interface ParamsSchema { - defaultValue: any; - id: string; - label: string; - type: ParamTypes; -} -export interface InstructionsSchema { - readonly instructionSets: InstructionSetSchema[]; - readonly params?: ParamsSchema[]; -} -export interface DashboardSchema { - id: string; - linkLabel?: string; - isOverview: boolean; -} -export interface ArtifactsSchema { - exportedFields?: { - documentationUrl: string; - }; - dashboards: DashboardSchema[]; - application?: { - path: string; - label: string; - }; -} -export interface TutorialSchema { - id: string; - category: TutorialsCategory; - name: string; - moduleName?: string; - isBeta?: boolean; - shortDescription: string; - euiIconType?: IconType; // EUI icon type string, one of https://elastic.github.io/eui/#/display/icons; - longDescription: string; - completionTimeMinutes?: number; - previewImagePath?: string; - - // kibana and elastic cluster running on prem - onPrem: InstructionsSchema; - - // kibana and elastic cluster running in elastic's cloud - elasticCloud?: InstructionsSchema; - - // kibana running on prem and elastic cluster running in elastic's cloud - onPremElasticCloud?: InstructionsSchema; - - // Elastic stack artifacts produced by product when it is setup and run. - artifacts?: ArtifactsSchema; - - // saved objects used by data module. - savedObjects?: any[]; - savedObjectsInstallMsg?: string; -} export interface TutorialContext { [key: string]: unknown; } diff --git a/src/plugins/home/server/services/tutorials/tutorials_registry.test.ts b/src/plugins/home/server/services/tutorials/tutorials_registry.test.ts index 94f5d65610083..a82699c231ad4 100644 --- a/src/plugins/home/server/services/tutorials/tutorials_registry.test.ts +++ b/src/plugins/home/server/services/tutorials/tutorials_registry.test.ts @@ -92,7 +92,7 @@ describe('TutorialsRegistry', () => { const setup = new TutorialsRegistry().setup(mockCoreSetup); testProvider = ({}) => invalidTutorialProvider; expect(() => setup.registerTutorial(testProvider)).toThrowErrorMatchingInlineSnapshot( - `"Unable to register tutorial spec because its invalid. ValidationError: child \\"name\\" fails because [\\"name\\" is not allowed to be empty]"` + `"Unable to register tutorial spec because its invalid. Error: [name]: is not allowed to be empty"` ); }); diff --git a/src/plugins/home/server/services/tutorials/tutorials_registry.ts b/src/plugins/home/server/services/tutorials/tutorials_registry.ts index f21f2ccd719c5..05f5600af307a 100644 --- a/src/plugins/home/server/services/tutorials/tutorials_registry.ts +++ b/src/plugins/home/server/services/tutorials/tutorials_registry.ts @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import Joi from 'joi'; import { CoreSetup } from 'src/core/server'; import { TutorialProvider, @@ -42,10 +41,10 @@ export class TutorialsRegistry { ); return { registerTutorial: (specProvider: TutorialProvider) => { - const emptyContext = {}; - const { error } = Joi.validate(specProvider(emptyContext), tutorialSchema); - - if (error) { + try { + const emptyContext = {}; + tutorialSchema.validate(specProvider(emptyContext)); + } catch (error) { throw new Error(`Unable to register tutorial spec because its invalid. ${error}`); } diff --git a/src/plugins/vis_type_vega/server/usage_collector/get_usage_collector.ts b/src/plugins/vis_type_vega/server/usage_collector/get_usage_collector.ts index d5f8d978d5252..310486bfdfffd 100644 --- a/src/plugins/vis_type_vega/server/usage_collector/get_usage_collector.ts +++ b/src/plugins/vis_type_vega/server/usage_collector/get_usage_collector.ts @@ -7,7 +7,7 @@ */ import { parse } from 'hjson'; -import { ElasticsearchClient, SavedObject } from 'src/core/server'; +import type { ElasticsearchClient } from 'src/core/server'; import { VegaSavedObjectAttributes, VisTypeVegaPluginSetupDependencies } from '../types'; @@ -27,7 +27,7 @@ const getDefaultVegaVisualizations = (home: UsageCollectorDependencies['home']) const sampleDataSets = home?.sampleData.getSampleDatasets() ?? []; sampleDataSets.forEach((sampleDataSet) => - sampleDataSet.savedObjects.forEach((savedObject: SavedObject) => { + sampleDataSet.savedObjects.forEach((savedObject) => { try { if (savedObject.type === 'visualization') { const visState = JSON.parse(savedObject.attributes?.visState); diff --git a/test/accessibility/config.ts b/test/accessibility/config.ts index 7364aced7af2c..2643ed8ab2a78 100644 --- a/test/accessibility/config.ts +++ b/test/accessibility/config.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; import { pageObjects } from './page_objects'; diff --git a/test/accessibility/ftr_provider_context.d.ts b/test/accessibility/ftr_provider_context.d.ts index 3cf8ae3e9a1c5..4c827393e1ef3 100644 --- a/test/accessibility/ftr_provider_context.d.ts +++ b/test/accessibility/ftr_provider_context.d.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { services } from './services'; diff --git a/test/api_integration/ftr_provider_context.d.ts b/test/api_integration/ftr_provider_context.d.ts index 56dd8965b8411..91d35a2dbc32a 100644 --- a/test/api_integration/ftr_provider_context.d.ts +++ b/test/api_integration/ftr_provider_context.d.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/test/common/ftr_provider_context.d.ts b/test/common/ftr_provider_context.d.ts index 56dd8965b8411..91d35a2dbc32a 100644 --- a/test/common/ftr_provider_context.d.ts +++ b/test/common/ftr_provider_context.d.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/test/functional/apps/dashboard/dashboard_save.ts b/test/functional/apps/dashboard/dashboard_save.ts index 0a0a2fc1dd286..dce59744db305 100644 --- a/test/functional/apps/dashboard/dashboard_save.ts +++ b/test/functional/apps/dashboard/dashboard_save.ts @@ -9,12 +9,12 @@ import { FtrProviderContext } from '../../ftr_provider_context'; export default function ({ getService, getPageObjects }: FtrProviderContext) { - const PageObjects = getPageObjects(['dashboard', 'header']); + const PageObjects = getPageObjects(['dashboard', 'header', 'visualize']); const listingTable = getService('listingTable'); const testSubjects = getService('testSubjects'); + const dashboardAddPanel = getService('dashboardAddPanel'); - // FLAKY: https://github.com/elastic/kibana/issues/89476 - describe.skip('dashboard save', function describeIndexTests() { + describe('dashboard save', function describeIndexTests() { this.tags('includeFirefox'); const dashboardName = 'Dashboard Save Test'; const dashboardNameEnterKey = 'Dashboard Save Test with Enter Key'; @@ -127,6 +127,9 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.dashboard.switchToEditMode(); await PageObjects.dashboard.expectExistsQuickSaveOption(); + await dashboardAddPanel.clickMarkdownQuickButton(); + await PageObjects.visualize.saveVisualizationAndReturn(); + await PageObjects.dashboard.waitForRenderComplete(); await PageObjects.dashboard.clickQuickSave(); await testSubjects.existOrFail('saveDashboardSuccess'); diff --git a/test/functional/apps/discover/ftr_provider_context.d.ts b/test/functional/apps/discover/ftr_provider_context.d.ts index e0113899b0836..5bf34af1bf9f3 100644 --- a/test/functional/apps/discover/ftr_provider_context.d.ts +++ b/test/functional/apps/discover/ftr_provider_context.d.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from '../../services'; import { pageObjects } from '../../page_objects'; diff --git a/test/functional/apps/visualize/_visualize_listing.ts b/test/functional/apps/visualize/_visualize_listing.ts index 90e7da1696702..78474693e939a 100644 --- a/test/functional/apps/visualize/_visualize_listing.ts +++ b/test/functional/apps/visualize/_visualize_listing.ts @@ -45,7 +45,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { describe('search', function () { before(async function () { // create one new viz - await PageObjects.visualize.gotoVisualizationLandingPage(); await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickMarkdownWidget(); await PageObjects.visEditor.setMarkdownTxt('HELLO'); diff --git a/test/functional/config.legacy.ts b/test/functional/config.legacy.ts index 9c5064b3b376c..d38f30a32ef61 100644 --- a/test/functional/config.legacy.ts +++ b/test/functional/config.legacy.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; // eslint-disable-next-line import/no-default-export export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/test/functional/ftr_provider_context.d.ts b/test/functional/ftr_provider_context.d.ts index 3cf8ae3e9a1c5..4c827393e1ef3 100644 --- a/test/functional/ftr_provider_context.d.ts +++ b/test/functional/ftr_provider_context.d.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { services } from './services'; diff --git a/test/functional/page_objects/common_page.ts b/test/functional/page_objects/common_page.ts index 6d9641a1a920e..bc60b8ce5f19c 100644 --- a/test/functional/page_objects/common_page.ts +++ b/test/functional/page_objects/common_page.ts @@ -257,7 +257,7 @@ export function CommonPageProvider({ getService, getPageObjects }: FtrProviderCo return currentUrl; }); - await retry.try(async () => { + await retry.tryForTime(defaultFindTimeout, async () => { await this.sleep(501); const currentUrl = await browser.getCurrentUrl(); log.debug('in navigateTo url = ' + currentUrl); @@ -266,10 +266,6 @@ export function CommonPageProvider({ getService, getPageObjects }: FtrProviderCo throw new Error('URL changed, waiting for it to settle'); } }); - if (appName === 'status_page') return; - if (await testSubjects.exists('statusPageContainer')) { - throw new Error('Navigation ended up at the status page.'); - } }); } diff --git a/test/functional/page_objects/dashboard_page.ts b/test/functional/page_objects/dashboard_page.ts index 576e7e516e251..ba75ab75cc6e8 100644 --- a/test/functional/page_objects/dashboard_page.ts +++ b/test/functional/page_objects/dashboard_page.ts @@ -277,6 +277,7 @@ export function DashboardPageProvider({ getService, getPageObjects }: FtrProvide } public async clickQuickSave() { + await this.expectQuickSaveButtonEnabled(); log.debug('clickQuickSave'); await testSubjects.click('dashboardQuickSaveMenuItem'); } @@ -630,6 +631,15 @@ export function DashboardPageProvider({ getService, getPageObjects }: FtrProvide await testSubjects.existOrFail('dashboardQuickSaveMenuItem'); } + public async expectQuickSaveButtonEnabled() { + log.debug('expectQuickSaveButtonEnabled'); + const quickSaveButton = await testSubjects.find('dashboardQuickSaveMenuItem'); + const isDisabled = await quickSaveButton.getAttribute('disabled'); + if (isDisabled) { + throw new Error('Quick save button disabled'); + } + } + public async getNotLoadedVisualizations(vizList: string[]) { const checkList = []; for (const name of vizList) { diff --git a/test/functional/page_objects/visualize_page.ts b/test/functional/page_objects/visualize_page.ts index 9a4c01f0f2767..78a963867b8c2 100644 --- a/test/functional/page_objects/visualize_page.ts +++ b/test/functional/page_objects/visualize_page.ts @@ -129,14 +129,14 @@ export function VisualizePageProvider({ getService, getPageObjects }: FtrProvide } public async navigateToNewVisualization() { - await common.navigateToApp('visualize'); + await this.gotoVisualizationLandingPage(); await header.waitUntilLoadingHasFinished(); await this.clickNewVisualization(); await this.waitForGroupsSelectPage(); } public async navigateToNewAggBasedVisualization() { - await common.navigateToApp('visualize'); + await this.gotoVisualizationLandingPage(); await header.waitUntilLoadingHasFinished(); await this.clickNewVisualization(); await this.clickAggBasedVisualizations(); diff --git a/test/functional/services/common/browser.ts b/test/functional/services/common/browser.ts index d9212e48f73fc..4dfd30c3b3b68 100644 --- a/test/functional/services/common/browser.ts +++ b/test/functional/services/common/browser.ts @@ -11,7 +11,7 @@ import { cloneDeepWith } from 'lodash'; import { Key, Origin } from 'selenium-webdriver'; // @ts-ignore internal modules are not typed import { LegacyActionSequence } from 'selenium-webdriver/lib/actions'; -import { ProvidedType } from '@kbn/test/types/ftr'; +import { ProvidedType } from '@kbn/test'; import { modifyUrl } from '@kbn/std'; import Jimp from 'jimp'; diff --git a/test/functional/services/common/test_subjects.ts b/test/functional/services/common/test_subjects.ts index 111206ec9eafe..d0050859cbb32 100644 --- a/test/functional/services/common/test_subjects.ts +++ b/test/functional/services/common/test_subjects.ts @@ -8,7 +8,7 @@ import testSubjSelector from '@kbn/test-subj-selector'; import { map as mapAsync } from 'bluebird'; -import { ProvidedType } from '@kbn/test/types/ftr'; +import { ProvidedType } from '@kbn/test'; import { WebElementWrapper } from '../lib/web_element_wrapper'; import { FtrProviderContext } from '../../ftr_provider_context'; diff --git a/test/functional/services/remote/webdriver.ts b/test/functional/services/remote/webdriver.ts index 21150e3d2ed08..7d629ee817252 100644 --- a/test/functional/services/remote/webdriver.ts +++ b/test/functional/services/remote/webdriver.ts @@ -11,7 +11,7 @@ import Fs from 'fs'; import * as Rx from 'rxjs'; import { mergeMap, map, takeUntil, catchError } from 'rxjs/operators'; -import { Lifecycle } from '@kbn/test/src/functional_test_runner/lib/lifecycle'; +import { Lifecycle } from '@kbn/test'; import { ToolingLog } from '@kbn/dev-utils'; import chromeDriver from 'chromedriver'; // @ts-ignore types not available diff --git a/test/interpreter_functional/config.ts b/test/interpreter_functional/config.ts index 2e52c52784afd..adcac520125ad 100644 --- a/test/interpreter_functional/config.ts +++ b/test/interpreter_functional/config.ts @@ -8,7 +8,7 @@ import path from 'path'; import fs from 'fs'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const functionalConfig = await readConfigFile(require.resolve('../functional/config')); diff --git a/test/new_visualize_flow/config.ts b/test/new_visualize_flow/config.ts index 612dcbbd2e1eb..a6bd97464e2d0 100644 --- a/test/new_visualize_flow/config.ts +++ b/test/new_visualize_flow/config.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const commonConfig = await readConfigFile(require.resolve('../functional/config.js')); diff --git a/test/plugin_functional/config.ts b/test/plugin_functional/config.ts index d21a157975ac8..1ff55edc010da 100644 --- a/test/plugin_functional/config.ts +++ b/test/plugin_functional/config.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import path from 'path'; import fs from 'fs'; diff --git a/test/security_functional/config.ts b/test/security_functional/config.ts index fd87ff9bb2ffe..f61f3bbf240ec 100644 --- a/test/security_functional/config.ts +++ b/test/security_functional/config.ts @@ -7,7 +7,7 @@ */ import path from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const functionalConfig = await readConfigFile(require.resolve('../functional/config')); diff --git a/test/server_integration/http/platform/config.ts b/test/server_integration/http/platform/config.ts index 5b92d44c66485..f3cdf426e9cbb 100644 --- a/test/server_integration/http/platform/config.ts +++ b/test/server_integration/http/platform/config.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; // eslint-disable-next-line import/no-default-export export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/test/server_integration/services/types.d.ts b/test/server_integration/services/types.d.ts index 5689100c671bb..2df95f0297f90 100644 --- a/test/server_integration/services/types.d.ts +++ b/test/server_integration/services/types.d.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services as kibanaCommonServices } from '../../common/services'; import { services as kibanaApiIntegrationServices } from '../../api_integration/services'; diff --git a/test/ui_capabilities/newsfeed_err/config.ts b/test/ui_capabilities/newsfeed_err/config.ts index 81448bf641ebb..e9548b41b67a0 100644 --- a/test/ui_capabilities/newsfeed_err/config.ts +++ b/test/ui_capabilities/newsfeed_err/config.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; // @ts-ignore untyped module import getFunctionalConfig from '../../functional/config'; diff --git a/test/visual_regression/config.ts b/test/visual_regression/config.ts index 0d38b067f35d9..3c11a4c2689ba 100644 --- a/test/visual_regression/config.ts +++ b/test/visual_regression/config.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/test/visual_regression/ftr_provider_context.d.ts b/test/visual_regression/ftr_provider_context.d.ts index 2dd5767f2270c..ba3eb370048b8 100644 --- a/test/visual_regression/ftr_provider_context.d.ts +++ b/test/visual_regression/ftr_provider_context.d.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from '../functional/page_objects'; import { services } from './services'; diff --git a/test/visual_regression/services/visual_testing/visual_testing.ts b/test/visual_regression/services/visual_testing/visual_testing.ts index d0a714d6759b5..a0d9afa90f3fe 100644 --- a/test/visual_regression/services/visual_testing/visual_testing.ts +++ b/test/visual_regression/services/visual_testing/visual_testing.ts @@ -8,7 +8,7 @@ import { postSnapshot } from '@percy/agent/dist/utils/sdk-utils'; import testSubjSelector from '@kbn/test-subj-selector'; -import { Test } from '@kbn/test/types/ftr'; +import { Test } from '@kbn/test'; import { kibanaPackageJson as pkg } from '@kbn/utils'; import { FtrProviderContext } from '../../ftr_provider_context'; diff --git a/x-pack/plugins/apm/ftr_e2e/config.ts b/x-pack/plugins/apm/ftr_e2e/config.ts index cbbac3a5eb6a3..cace655ad7c5b 100644 --- a/x-pack/plugins/apm/ftr_e2e/config.ts +++ b/x-pack/plugins/apm/ftr_e2e/config.ts @@ -7,7 +7,7 @@ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { CA_CERT_PATH } from '@kbn/dev-utils'; async function config({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/plugins/apm/ftr_e2e/cypress_open.ts b/x-pack/plugins/apm/ftr_e2e/cypress_open.ts index 77416518f113b..ec52f387a8b98 100644 --- a/x-pack/plugins/apm/ftr_e2e/cypress_open.ts +++ b/x-pack/plugins/apm/ftr_e2e/cypress_open.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { cypressOpenTests } from './cypress_start'; async function openE2ETests({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/plugins/apm/ftr_e2e/cypress_run.ts b/x-pack/plugins/apm/ftr_e2e/cypress_run.ts index 19ea68b817ce5..0e9efb775fc7a 100644 --- a/x-pack/plugins/apm/ftr_e2e/cypress_run.ts +++ b/x-pack/plugins/apm/ftr_e2e/cypress_run.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { cypressRunTests } from './cypress_start'; async function runE2ETests({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/plugins/apm/ftr_e2e/ftr_provider_context.d.ts b/x-pack/plugins/apm/ftr_e2e/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/plugins/apm/ftr_e2e/ftr_provider_context.d.ts +++ b/x-pack/plugins/apm/ftr_e2e/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/plugins/apm/server/plugin.ts b/x-pack/plugins/apm/server/plugin.ts index 44334889128c4..cf5be4369f79e 100644 --- a/x-pack/plugins/apm/server/plugin.ts +++ b/x-pack/plugins/apm/server/plugin.ts @@ -108,6 +108,7 @@ export class APMPlugin plugins.home?.tutorials.registerTutorial(() => { const ossPart = ossTutorialProvider({}); if (this.currentConfig!['xpack.apm.ui.enabled'] && ossPart.artifacts) { + // @ts-expect-error ossPart.artifacts.application is readonly ossPart.artifacts.application = { path: '/app/apm', label: i18n.translate( diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.test.ts similarity index 72% rename from x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.test.js rename to x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.test.ts index 500224a7a3bbe..93cf07a9dd5dd 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.test.ts @@ -5,19 +5,21 @@ * 2.0. */ +// @ts-expect-error untyped lib import { functionWrapper } from '../../../test_helpers/function_wrapper'; import { getFunctionErrors } from '../../../i18n'; import { csv } from './csv'; +import { Datatable } from 'src/plugins/expressions'; const errors = getFunctionErrors().csv; describe('csv', () => { const fn = functionWrapper(csv); - const expected = { + const expected: Datatable = { type: 'datatable', columns: [ - { name: 'name', type: 'string' }, - { name: 'number', type: 'string' }, + { id: 'name', name: 'name', meta: { type: 'string' } }, + { id: 'number', name: 'number', meta: { type: 'string' } }, ], rows: [ { name: 'one', number: '1' }, @@ -69,43 +71,47 @@ fourty two%SPLIT%42`, }); it('should trim column names', () => { - expect( - fn(null, { - data: `foo," bar ", baz, " buz " -1,2,3,4`, - }) - ).toEqual({ + const expectedResult: Datatable = { type: 'datatable', columns: [ - { name: 'foo', type: 'string' }, - { name: 'bar', type: 'string' }, - { name: 'baz', type: 'string' }, - { name: 'buz', type: 'string' }, + { id: 'foo', name: 'foo', meta: { type: 'string' } }, + { id: 'bar', name: 'bar', meta: { type: 'string' } }, + { id: 'baz', name: 'baz', meta: { type: 'string' } }, + { id: 'buz', name: 'buz', meta: { type: 'string' } }, ], rows: [{ foo: '1', bar: '2', baz: '3', buz: '4' }], - }); - }); + }; - it('should handle odd spaces correctly', () => { expect( fn(null, { data: `foo," bar ", baz, " buz " -1," best ",3, " ok" -" good", bad, better , " worst " `, +1,2,3,4`, }) - ).toEqual({ + ).toEqual(expectedResult); + }); + + it('should handle odd spaces correctly', () => { + const expectedResult: Datatable = { type: 'datatable', columns: [ - { name: 'foo', type: 'string' }, - { name: 'bar', type: 'string' }, - { name: 'baz', type: 'string' }, - { name: 'buz', type: 'string' }, + { id: 'foo', name: 'foo', meta: { type: 'string' } }, + { id: 'bar', name: 'bar', meta: { type: 'string' } }, + { id: 'baz', name: 'baz', meta: { type: 'string' } }, + { id: 'buz', name: 'buz', meta: { type: 'string' } }, ], rows: [ { foo: '1', bar: ' best ', baz: '3', buz: ' ok' }, { foo: ' good', bar: ' bad', baz: ' better ', buz: ' worst ' }, ], - }); + }; + + expect( + fn(null, { + data: `foo," bar ", baz, " buz " +1," best ",3, " ok" +" good", bad, better , " worst " `, + }) + ).toEqual(expectedResult); }); it('throws when given invalid csv', () => { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.ts index 1f810e3658c6a..078721fc08d05 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/csv.ts @@ -73,7 +73,11 @@ export function csv(): ExpressionFunctionDefinition<'csv', null, Arguments, Data if (i === 0) { // first row, assume header values row.forEach((colName: string) => - acc.columns.push({ name: colName.trim(), type: 'string' }) + acc.columns.push({ + id: colName.trim(), + name: colName.trim(), + meta: { type: 'string' }, + }) ); } else { // any other row is a data row diff --git a/x-pack/plugins/canvas/shareable_runtime/components/app.test.tsx b/x-pack/plugins/canvas/shareable_runtime/components/app.test.tsx index acf71cad3f3ba..b68642d184542 100644 --- a/x-pack/plugins/canvas/shareable_runtime/components/app.test.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/components/app.test.tsx @@ -59,7 +59,8 @@ const getWrapper: (name?: WorkpadNames) => ReactWrapper = (name = 'hello') => { return mount(); }; -describe('', () => { +// FLAKY: https://github.com/elastic/kibana/issues/95899 +describe.skip('', () => { test('App renders properly', () => { expect(getWrapper().html()).toMatchSnapshot(); }); diff --git a/x-pack/plugins/features/server/__snapshots__/feature_registry.test.ts.snap b/x-pack/plugins/features/server/__snapshots__/feature_registry.test.ts.snap index 3043de27534f1..c91a891d4825f 100644 --- a/x-pack/plugins/features/server/__snapshots__/feature_registry.test.ts.snap +++ b/x-pack/plugins/features/server/__snapshots__/feature_registry.test.ts.snap @@ -1,21 +1,21 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`FeatureRegistry Kibana Features prevents features from being registered with a catalogue entry of "" 1`] = `"child \\"catalogue\\" fails because [\\"catalogue\\" at position 0 fails because [\\"0\\" is not allowed to be empty]]"`; +exports[`FeatureRegistry Kibana Features prevents features from being registered with a catalogue entry of "" 1`] = `"[catalogue.0]: Does not satisfy regexp /^[a-zA-Z0-9:_-]+$/"`; -exports[`FeatureRegistry Kibana Features prevents features from being registered with a catalogue entry of "contains space" 1`] = `"child \\"catalogue\\" fails because [\\"catalogue\\" at position 0 fails because [\\"0\\" with value \\"contains space\\" fails to match the required pattern: /^[a-zA-Z0-9:_-]+$/]]"`; +exports[`FeatureRegistry Kibana Features prevents features from being registered with a catalogue entry of "contains space" 1`] = `"[catalogue.0]: Does not satisfy regexp /^[a-zA-Z0-9:_-]+$/"`; -exports[`FeatureRegistry Kibana Features prevents features from being registered with a catalogue entry of "contains_invalid()_chars" 1`] = `"child \\"catalogue\\" fails because [\\"catalogue\\" at position 0 fails because [\\"0\\" with value \\"contains_invalid()_chars\\" fails to match the required pattern: /^[a-zA-Z0-9:_-]+$/]]"`; +exports[`FeatureRegistry Kibana Features prevents features from being registered with a catalogue entry of "contains_invalid()_chars" 1`] = `"[catalogue.0]: Does not satisfy regexp /^[a-zA-Z0-9:_-]+$/"`; -exports[`FeatureRegistry Kibana Features prevents features from being registered with a management id of "" 1`] = `"child \\"management\\" fails because [child \\"kibana\\" fails because [\\"kibana\\" at position 0 fails because [\\"0\\" is not allowed to be empty]]]"`; +exports[`FeatureRegistry Kibana Features prevents features from being registered with a management id of "" 1`] = `"[management.kibana.0]: Does not satisfy regexp /^[a-zA-Z0-9:_-]+$/"`; -exports[`FeatureRegistry Kibana Features prevents features from being registered with a management id of "contains space" 1`] = `"child \\"management\\" fails because [child \\"kibana\\" fails because [\\"kibana\\" at position 0 fails because [\\"0\\" with value \\"contains space\\" fails to match the required pattern: /^[a-zA-Z0-9:_-]+$/]]]"`; +exports[`FeatureRegistry Kibana Features prevents features from being registered with a management id of "contains space" 1`] = `"[management.kibana.0]: Does not satisfy regexp /^[a-zA-Z0-9:_-]+$/"`; -exports[`FeatureRegistry Kibana Features prevents features from being registered with a management id of "contains_invalid()_chars" 1`] = `"child \\"management\\" fails because [child \\"kibana\\" fails because [\\"kibana\\" at position 0 fails because [\\"0\\" with value \\"contains_invalid()_chars\\" fails to match the required pattern: /^[a-zA-Z0-9:_-]+$/]]]"`; +exports[`FeatureRegistry Kibana Features prevents features from being registered with a management id of "contains_invalid()_chars" 1`] = `"[management.kibana.0]: Does not satisfy regexp /^[a-zA-Z0-9:_-]+$/"`; -exports[`FeatureRegistry Kibana Features prevents features from being registered with an ID of "catalogue" 1`] = `"child \\"id\\" fails because [\\"id\\" contains an invalid value]"`; +exports[`FeatureRegistry Kibana Features prevents features from being registered with an ID of "catalogue" 1`] = `"[id]: [catalogue] is not allowed"`; -exports[`FeatureRegistry Kibana Features prevents features from being registered with an ID of "doesn't match valid regex" 1`] = `"child \\"id\\" fails because [\\"id\\" with value \\"doesn't match valid regex\\" fails to match the required pattern: /^[a-zA-Z0-9_-]+$/]"`; +exports[`FeatureRegistry Kibana Features prevents features from being registered with an ID of "doesn't match valid regex" 1`] = `"[id]: Does not satisfy regexp /^[a-zA-Z0-9_-]+$/"`; -exports[`FeatureRegistry Kibana Features prevents features from being registered with an ID of "management" 1`] = `"child \\"id\\" fails because [\\"id\\" contains an invalid value]"`; +exports[`FeatureRegistry Kibana Features prevents features from being registered with an ID of "management" 1`] = `"[id]: [management] is not allowed"`; -exports[`FeatureRegistry Kibana Features prevents features from being registered with an ID of "navLinks" 1`] = `"child \\"id\\" fails because [\\"id\\" contains an invalid value]"`; +exports[`FeatureRegistry Kibana Features prevents features from being registered with an ID of "navLinks" 1`] = `"[id]: [navLinks] is not allowed"`; diff --git a/x-pack/plugins/features/server/feature_privilege_iterator.js b/x-pack/plugins/features/server/feature_privilege_iterator.js index f813eeebc9550..842c30d643b67 100644 --- a/x-pack/plugins/features/server/feature_privilege_iterator.js +++ b/x-pack/plugins/features/server/feature_privilege_iterator.js @@ -6,5 +6,6 @@ */ // the file created to remove TS cicular dependency between features and security pluin +// https://github.com/elastic/kibana/issues/87388 // eslint-disable-next-line @kbn/eslint/no-restricted-paths export { featurePrivilegeIterator } from '../../security/server/authorization'; diff --git a/x-pack/plugins/features/server/feature_registry.test.ts b/x-pack/plugins/features/server/feature_registry.test.ts index eb9b35cc644a7..0eb00b43d6f5d 100644 --- a/x-pack/plugins/features/server/feature_registry.test.ts +++ b/x-pack/plugins/features/server/feature_registry.test.ts @@ -158,7 +158,7 @@ describe('FeatureRegistry', () => { expect(() => featureRegistry.registerKibanaFeature(feature) ).toThrowErrorMatchingInlineSnapshot( - `"child \\"category\\" fails because [\\"category\\" is required]"` + `"[category.id]: expected value of type [string] but got [undefined]"` ); }); @@ -175,7 +175,7 @@ describe('FeatureRegistry', () => { expect(() => featureRegistry.registerKibanaFeature(feature) ).toThrowErrorMatchingInlineSnapshot( - `"child \\"category\\" fails because [child \\"id\\" fails because [\\"id\\" is required]]"` + `"[category.id]: expected value of type [string] but got [undefined]"` ); }); @@ -192,7 +192,7 @@ describe('FeatureRegistry', () => { expect(() => featureRegistry.registerKibanaFeature(feature) ).toThrowErrorMatchingInlineSnapshot( - `"child \\"category\\" fails because [child \\"label\\" fails because [\\"label\\" is required]]"` + `"[category.label]: expected value of type [string] but got [undefined]"` ); }); }); @@ -209,7 +209,7 @@ describe('FeatureRegistry', () => { expect(() => featureRegistry.registerKibanaFeature(feature) ).toThrowErrorMatchingInlineSnapshot( - `"child \\"privileges\\" fails because [\\"privileges\\" is required]"` + `"[privileges]: expected at least one defined value but got [undefined]"` ); }); @@ -248,7 +248,7 @@ describe('FeatureRegistry', () => { expect(() => featureRegistry.registerKibanaFeature(feature) ).toThrowErrorMatchingInlineSnapshot( - `"child \\"subFeatures\\" fails because [\\"subFeatures\\" must contain less than or equal to 0 items]"` + `"[subFeatures]: array size is [1], but cannot be greater than [0]"` ); }); @@ -488,11 +488,12 @@ describe('FeatureRegistry', () => { }; const featureRegistry = new FeatureRegistry(); - expect(() => - featureRegistry.registerKibanaFeature(feature) - ).toThrowErrorMatchingInlineSnapshot( - `"child \\"privileges\\" fails because [\\"foo\\" is not allowed]"` - ); + expect(() => featureRegistry.registerKibanaFeature(feature)) + .toThrowErrorMatchingInlineSnapshot(` + "[privileges]: types that failed validation: + - [privileges.0]: expected value to equal [null] + - [privileges.1.foo]: definition for this key is missing" + `); }); it(`prevents privileges from specifying app entries that don't exist at the root level`, () => { @@ -1278,7 +1279,7 @@ describe('FeatureRegistry', () => { expect(() => featureRegistry.registerKibanaFeature(feature) ).toThrowErrorMatchingInlineSnapshot( - `"child \\"reserved\\" fails because [child \\"privileges\\" fails because [\\"privileges\\" at position 0 fails because [child \\"id\\" fails because [\\"id\\" with value \\"reserved_1\\" fails to match the required pattern: /^(?!reserved_)[a-zA-Z0-9_-]+$/]]]]"` + `"[reserved.privileges.0.id]: Does not satisfy regexp /^(?!reserved_)[a-zA-Z0-9_-]+$/"` ); }); @@ -1394,9 +1395,11 @@ describe('FeatureRegistry', () => { const featureRegistry = new FeatureRegistry(); expect(() => { featureRegistry.registerKibanaFeature(feature1); - }).toThrowErrorMatchingInlineSnapshot( - `"child \\"subFeatures\\" fails because [\\"subFeatures\\" at position 0 fails because [child \\"privilegeGroups\\" fails because [\\"privilegeGroups\\" at position 0 fails because [child \\"privileges\\" fails because [\\"privileges\\" at position 0 fails because [child \\"minimumLicense\\" fails because [\\"minimumLicense\\" is not allowed]]]]]]]"` - ); + }).toThrowErrorMatchingInlineSnapshot(` + "[subFeatures.0.privilegeGroups.0]: types that failed validation: + - [subFeatures.0.privilegeGroups.0.0.privileges.0.minimumLicense]: a value wasn't expected to be present + - [subFeatures.0.privilegeGroups.0.1.groupType]: expected value to equal [independent]" + `); }); it('cannot register feature after getAll has been called', () => { @@ -1575,7 +1578,7 @@ describe('FeatureRegistry', () => { expect(() => featureRegistry.registerElasticsearchFeature(feature) ).toThrowErrorMatchingInlineSnapshot( - `"child \\"privileges\\" fails because [\\"privileges\\" is required]"` + `"[privileges]: expected value of type [array] but got [undefined]"` ); }); diff --git a/x-pack/plugins/features/server/feature_schema.ts b/x-pack/plugins/features/server/feature_schema.ts index 204c5bdfe2469..51d3331ac7da1 100644 --- a/x-pack/plugins/features/server/feature_schema.ts +++ b/x-pack/plugins/features/server/feature_schema.ts @@ -5,7 +5,7 @@ * 2.0. */ -import Joi from 'joi'; +import { schema } from '@kbn/config-schema'; import { difference } from 'lodash'; import { Capabilities as UICapabilities } from '../../../../src/core/server'; @@ -14,7 +14,11 @@ import { FeatureKibanaPrivileges, ElasticsearchFeatureConfig } from '.'; // Each feature gets its own property on the UICapabilities object, // but that object has a few built-in properties which should not be overwritten. -const prohibitedFeatureIds: Array = ['catalogue', 'management', 'navLinks']; +const prohibitedFeatureIds: Set = new Set([ + 'catalogue', + 'management', + 'navLinks', +]); const featurePrivilegePartRegex = /^[a-zA-Z0-9_-]+$/; const subFeaturePrivilegePartRegex = /^[a-zA-Z0-9_-]+$/; @@ -22,144 +26,211 @@ const managementSectionIdRegex = /^[a-zA-Z0-9_-]+$/; const reservedFeaturePrrivilegePartRegex = /^(?!reserved_)[a-zA-Z0-9_-]+$/; export const uiCapabilitiesRegex = /^[a-zA-Z0-9:_-]+$/; -const validLicenses = ['basic', 'standard', 'gold', 'platinum', 'enterprise', 'trial']; +const validLicenseSchema = schema.oneOf([ + schema.literal('basic'), + schema.literal('standard'), + schema.literal('gold'), + schema.literal('platinum'), + schema.literal('enterprise'), + schema.literal('trial'), +]); // sub-feature privileges are only available with a `gold` license or better, so restricting sub-feature privileges // for `gold` or below doesn't make a whole lot of sense. -const validSubFeaturePrivilegeLicenses = ['platinum', 'enterprise', 'trial']; - -const managementSchema = Joi.object().pattern( - managementSectionIdRegex, - Joi.array().items(Joi.string().regex(uiCapabilitiesRegex)) +const validSubFeaturePrivilegeLicensesSchema = schema.oneOf([ + schema.literal('platinum'), + schema.literal('enterprise'), + schema.literal('trial'), +]); + +const listOfCapabilitiesSchema = schema.arrayOf( + schema.string({ + validate(key: string) { + if (!uiCapabilitiesRegex.test(key)) { + return `Does not satisfy regexp ${uiCapabilitiesRegex.toString()}`; + } + }, + }) +); +const managementSchema = schema.recordOf( + schema.string({ + validate(key: string) { + if (!managementSectionIdRegex.test(key)) { + return `Does not satisfy regexp ${managementSectionIdRegex.toString()}`; + } + }, + }), + listOfCapabilitiesSchema ); -const catalogueSchema = Joi.array().items(Joi.string().regex(uiCapabilitiesRegex)); -const alertingSchema = Joi.array().items(Joi.string()); - -const appCategorySchema = Joi.object({ - id: Joi.string().required(), - label: Joi.string().required(), - ariaLabel: Joi.string(), - euiIconType: Joi.string(), - order: Joi.number(), -}).required(); - -const kibanaPrivilegeSchema = Joi.object({ - excludeFromBasePrivileges: Joi.boolean(), - management: managementSchema, - catalogue: catalogueSchema, - api: Joi.array().items(Joi.string()), - app: Joi.array().items(Joi.string()), - alerting: Joi.object({ - all: alertingSchema, - read: alertingSchema, +const catalogueSchema = listOfCapabilitiesSchema; +const alertingSchema = schema.arrayOf(schema.string()); + +const appCategorySchema = schema.object({ + id: schema.string(), + label: schema.string(), + ariaLabel: schema.maybe(schema.string()), + euiIconType: schema.maybe(schema.string()), + order: schema.maybe(schema.number()), +}); + +const kibanaPrivilegeSchema = schema.object({ + excludeFromBasePrivileges: schema.maybe(schema.boolean()), + management: schema.maybe(managementSchema), + catalogue: schema.maybe(catalogueSchema), + api: schema.maybe(schema.arrayOf(schema.string())), + app: schema.maybe(schema.arrayOf(schema.string())), + alerting: schema.maybe( + schema.object({ + all: schema.maybe(alertingSchema), + read: schema.maybe(alertingSchema), + }) + ), + savedObject: schema.object({ + all: schema.arrayOf(schema.string()), + read: schema.arrayOf(schema.string()), }), - savedObject: Joi.object({ - all: Joi.array().items(Joi.string()).required(), - read: Joi.array().items(Joi.string()).required(), - }).required(), - ui: Joi.array().items(Joi.string().regex(uiCapabilitiesRegex)).required(), + ui: listOfCapabilitiesSchema, }); -const kibanaIndependentSubFeaturePrivilegeSchema = Joi.object({ - id: Joi.string().regex(subFeaturePrivilegePartRegex).required(), - name: Joi.string().required(), - includeIn: Joi.string().allow('all', 'read', 'none').required(), - minimumLicense: Joi.string().valid(...validSubFeaturePrivilegeLicenses), - management: managementSchema, - catalogue: catalogueSchema, - alerting: Joi.object({ - all: alertingSchema, - read: alertingSchema, +const kibanaIndependentSubFeaturePrivilegeSchema = schema.object({ + id: schema.string({ + validate(key: string) { + if (!subFeaturePrivilegePartRegex.test(key)) { + return `Does not satisfy regexp ${subFeaturePrivilegePartRegex.toString()}`; + } + }, + }), + name: schema.string(), + includeIn: schema.oneOf([schema.literal('all'), schema.literal('read'), schema.literal('none')]), + minimumLicense: schema.maybe(validSubFeaturePrivilegeLicensesSchema), + management: schema.maybe(managementSchema), + catalogue: schema.maybe(catalogueSchema), + alerting: schema.maybe( + schema.object({ + all: schema.maybe(alertingSchema), + read: schema.maybe(alertingSchema), + }) + ), + api: schema.maybe(schema.arrayOf(schema.string())), + app: schema.maybe(schema.arrayOf(schema.string())), + savedObject: schema.object({ + all: schema.arrayOf(schema.string()), + read: schema.arrayOf(schema.string()), }), - api: Joi.array().items(Joi.string()), - app: Joi.array().items(Joi.string()), - savedObject: Joi.object({ - all: Joi.array().items(Joi.string()).required(), - read: Joi.array().items(Joi.string()).required(), - }).required(), - ui: Joi.array().items(Joi.string().regex(uiCapabilitiesRegex)).required(), + ui: listOfCapabilitiesSchema, }); -const kibanaMutuallyExclusiveSubFeaturePrivilegeSchema = kibanaIndependentSubFeaturePrivilegeSchema.keys( +const kibanaMutuallyExclusiveSubFeaturePrivilegeSchema = kibanaIndependentSubFeaturePrivilegeSchema.extends( { - minimumLicense: Joi.forbidden(), + minimumLicense: schema.never(), } ); -const kibanaSubFeatureSchema = Joi.object({ - name: Joi.string().required(), - privilegeGroups: Joi.array().items( - Joi.object({ - groupType: Joi.string().valid('mutually_exclusive', 'independent').required(), - privileges: Joi.when('groupType', { - is: 'mutually_exclusive', - then: Joi.array().items(kibanaMutuallyExclusiveSubFeaturePrivilegeSchema).min(1), - otherwise: Joi.array().items(kibanaIndependentSubFeaturePrivilegeSchema).min(1), - }), - }) +const kibanaSubFeatureSchema = schema.object({ + name: schema.string(), + privilegeGroups: schema.maybe( + schema.arrayOf( + schema.oneOf([ + schema.object({ + groupType: schema.literal('mutually_exclusive'), + privileges: schema.maybe( + schema.arrayOf(kibanaMutuallyExclusiveSubFeaturePrivilegeSchema, { minSize: 1 }) + ), + }), + schema.object({ + groupType: schema.literal('independent'), + privileges: schema.maybe( + schema.arrayOf(kibanaIndependentSubFeaturePrivilegeSchema, { minSize: 1 }) + ), + }), + ]) + ) ), }); -const kibanaFeatureSchema = Joi.object({ - id: Joi.string() - .regex(featurePrivilegePartRegex) - .invalid(...prohibitedFeatureIds) - .required(), - name: Joi.string().required(), - category: appCategorySchema, - order: Joi.number(), - excludeFromBasePrivileges: Joi.boolean(), - minimumLicense: Joi.string().valid(...validLicenses), - app: Joi.array().items(Joi.string()).required(), - management: managementSchema, - catalogue: catalogueSchema, - alerting: alertingSchema, - privileges: Joi.object({ - all: kibanaPrivilegeSchema, - read: kibanaPrivilegeSchema, - }) - .allow(null) - .required(), - subFeatures: Joi.when('privileges', { - is: null, - then: Joi.array().items(kibanaSubFeatureSchema).max(0), - otherwise: Joi.array().items(kibanaSubFeatureSchema), +const kibanaFeatureSchema = schema.object({ + id: schema.string({ + validate(value: string) { + if (!featurePrivilegePartRegex.test(value)) { + return `Does not satisfy regexp ${featurePrivilegePartRegex.toString()}`; + } + if (prohibitedFeatureIds.has(value)) { + return `[${value}] is not allowed`; + } + }, }), - privilegesTooltip: Joi.string(), - reserved: Joi.object({ - description: Joi.string().required(), - privileges: Joi.array() - .items( - Joi.object({ - id: Joi.string().regex(reservedFeaturePrrivilegePartRegex).required(), - privilege: kibanaPrivilegeSchema.required(), + name: schema.string(), + category: appCategorySchema, + order: schema.maybe(schema.number()), + excludeFromBasePrivileges: schema.maybe(schema.boolean()), + minimumLicense: schema.maybe(validLicenseSchema), + app: schema.arrayOf(schema.string()), + management: schema.maybe(managementSchema), + catalogue: schema.maybe(catalogueSchema), + alerting: schema.maybe(alertingSchema), + privileges: schema.oneOf([ + schema.literal(null), + schema.object({ + all: schema.maybe(kibanaPrivilegeSchema), + read: schema.maybe(kibanaPrivilegeSchema), + }), + ]), + subFeatures: schema.maybe( + schema.conditional( + schema.siblingRef('privileges'), + null, + // allows an empty array only + schema.arrayOf(schema.never(), { maxSize: 0 }), + schema.arrayOf(kibanaSubFeatureSchema) + ) + ), + privilegesTooltip: schema.maybe(schema.string()), + reserved: schema.maybe( + schema.object({ + description: schema.string(), + privileges: schema.arrayOf( + schema.object({ + id: schema.string({ + validate(value: string) { + if (!reservedFeaturePrrivilegePartRegex.test(value)) { + return `Does not satisfy regexp ${reservedFeaturePrrivilegePartRegex.toString()}`; + } + }, + }), + privilege: kibanaPrivilegeSchema, }) - ) - .required(), - }), + ), + }) + ), }); -const elasticsearchPrivilegeSchema = Joi.object({ - ui: Joi.array().items(Joi.string()).required(), - requiredClusterPrivileges: Joi.array().items(Joi.string()), - requiredIndexPrivileges: Joi.object().pattern(Joi.string(), Joi.array().items(Joi.string())), - requiredRoles: Joi.array().items(Joi.string()), +const elasticsearchPrivilegeSchema = schema.object({ + ui: schema.arrayOf(schema.string()), + requiredClusterPrivileges: schema.maybe(schema.arrayOf(schema.string())), + requiredIndexPrivileges: schema.maybe( + schema.recordOf(schema.string(), schema.arrayOf(schema.string())) + ), + requiredRoles: schema.maybe(schema.arrayOf(schema.string())), }); -const elasticsearchFeatureSchema = Joi.object({ - id: Joi.string() - .regex(featurePrivilegePartRegex) - .invalid(...prohibitedFeatureIds) - .required(), - management: managementSchema, - catalogue: catalogueSchema, - privileges: Joi.array().items(elasticsearchPrivilegeSchema).required(), +const elasticsearchFeatureSchema = schema.object({ + id: schema.string({ + validate(value: string) { + if (!featurePrivilegePartRegex.test(value)) { + return `Does not satisfy regexp ${featurePrivilegePartRegex.toString()}`; + } + if (prohibitedFeatureIds.has(value)) { + return `[${value}] is not allowed`; + } + }, + }), + management: schema.maybe(managementSchema), + catalogue: schema.maybe(catalogueSchema), + privileges: schema.arrayOf(elasticsearchPrivilegeSchema), }); export function validateKibanaFeature(feature: KibanaFeatureConfig) { - const validateResult = Joi.validate(feature, kibanaFeatureSchema); - if (validateResult.error) { - throw validateResult.error; - } + kibanaFeatureSchema.validate(feature); + // 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 = [], alerting = [] } = feature; @@ -343,10 +414,7 @@ export function validateKibanaFeature(feature: KibanaFeatureConfig) { } export function validateElasticsearchFeature(feature: ElasticsearchFeatureConfig) { - const validateResult = Joi.validate(feature, elasticsearchFeatureSchema); - if (validateResult.error) { - throw validateResult.error; - } + elasticsearchFeatureSchema.validate(feature); // the following validation can't be enforced by the Joi schema without a very convoluted and verbose definition const { privileges } = feature; privileges.forEach((privilege, index) => { diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/fleet_server_upgrade_modal.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/fleet_server_upgrade_modal.tsx index 4d6ac864ee8b5..ede997f185c7e 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/fleet_server_upgrade_modal.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/components/fleet_server_upgrade_modal.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import React, { useCallback, useState } from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; import { EuiButton, EuiCheckbox, @@ -24,7 +24,15 @@ import { import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; -import { sendPutSettings, useLink, useStartServices } from '../../../hooks'; +import { + sendGetAgents, + sendGetOneAgentPolicy, + sendPutSettings, + useLink, + useStartServices, +} from '../../../hooks'; +import type { PackagePolicy } from '../../../types'; +import { FLEET_SERVER_PACKAGE } from '../../../constants'; interface Props { onClose: () => void; @@ -37,6 +45,56 @@ export const FleetServerUpgradeModal: React.FunctionComponent = ({ onClos const isCloud = !!cloud?.cloudId; const [checked, setChecked] = useState(false); + const [isAgentsAndPoliciesLoaded, setAgentsAndPoliciesLoaded] = useState(false); + + // Check if an other agent than the fleet server is already enrolled + useEffect(() => { + async function check() { + try { + const agentPoliciesAlreadyChecked: { [k: string]: boolean } = {}; + + const res = await sendGetAgents({ + page: 1, + perPage: 10, + showInactive: false, + }); + + if (res.error) { + throw res.error; + } + + for (const agent of res.data?.list ?? []) { + if (!agent.policy_id || agentPoliciesAlreadyChecked[agent.policy_id]) { + continue; + } + + agentPoliciesAlreadyChecked[agent.policy_id] = true; + const policyRes = await sendGetOneAgentPolicy(agent.policy_id); + const hasFleetServer = + (policyRes.data?.item.package_policies as PackagePolicy[]).some((p: PackagePolicy) => { + return p.package?.name === FLEET_SERVER_PACKAGE; + }) ?? false; + if (!hasFleetServer) { + await sendPutSettings({ + has_seen_fleet_migration_notice: true, + }); + onClose(); + return; + } + } + setAgentsAndPoliciesLoaded(true); + } catch (err) { + notifications.toasts.addError(err, { + title: i18n.translate('xpack.fleet.fleetServerUpgradeModal.errorLoadingAgents', { + defaultMessage: `Error loading agents`, + }), + }); + } + } + + check(); + }, [notifications.toasts, onClose]); + const onChange = useCallback(async () => { try { setChecked(!checked); @@ -52,18 +110,23 @@ export const FleetServerUpgradeModal: React.FunctionComponent = ({ onClos } }, [checked, setChecked, notifications]); + if (!isAgentsAndPoliciesLoaded) { + return null; + } + return ( = ({ onClos {isCloud ? ( @@ -84,17 +147,6 @@ export const FleetServerUpgradeModal: React.FunctionComponent = ({ onClos /> ), - link: ( - - - - ), }} /> ) : ( diff --git a/x-pack/plugins/fleet/server/services/fleet_server/saved_object_migrations.ts b/x-pack/plugins/fleet/server/services/fleet_server/saved_object_migrations.ts index 82fd937092477..5c05ed7532ac6 100644 --- a/x-pack/plugins/fleet/server/services/fleet_server/saved_object_migrations.ts +++ b/x-pack/plugins/fleet/server/services/fleet_server/saved_object_migrations.ts @@ -28,6 +28,7 @@ import { invalidateAPIKeys } from '../api_keys'; import { settingsService } from '..'; export async function runFleetServerMigration() { + await settingsService.settingsSetup(getInternalUserSOClient()); await Promise.all([migrateEnrollmentApiKeys(), migrateAgentPolicies(), migrateAgents()]); } diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/__jest__/processors/registered_domain.test.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/__jest__/processors/registered_domain.test.tsx new file mode 100644 index 0000000000000..962e099f5b667 --- /dev/null +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/__jest__/processors/registered_domain.test.tsx @@ -0,0 +1,130 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { act } from 'react-dom/test-utils'; +import { setup, SetupResult, getProcessorValue } from './processor.helpers'; + +// Default parameter values automatically added to the registered domain processor when saved +const defaultRegisteredDomainParameters = { + description: undefined, + if: undefined, + ignore_missing: undefined, + ignore_failure: undefined, +}; + +const REGISTERED_DOMAIN_TYPE = 'registered_domain'; + +describe('Processor: Registered Domain', () => { + let onUpdate: jest.Mock; + let testBed: SetupResult; + + beforeAll(() => { + jest.useFakeTimers(); + }); + + afterAll(() => { + jest.useRealTimers(); + }); + + beforeEach(async () => { + onUpdate = jest.fn(); + + await act(async () => { + testBed = await setup({ + value: { + processors: [], + }, + onFlyoutOpen: jest.fn(), + onUpdate, + }); + }); + + testBed.component.update(); + + // Open flyout to add new processor + testBed.actions.addProcessor(); + // Add type (the other fields are not visible until a type is selected) + await testBed.actions.addProcessorType(REGISTERED_DOMAIN_TYPE); + }); + + test('prevents form submission if required fields are not provided', async () => { + const { + actions: { saveNewProcessor }, + form, + } = testBed; + + // Click submit button with only the type defined + await saveNewProcessor(); + + // Expect form error as "field" is required parameter + expect(form.getErrorsMessages()).toEqual(['A field value is required.']); + }); + + test('saves with default parameter values', async () => { + const { + actions: { saveNewProcessor }, + form, + } = testBed; + + // Add "field" value (required) + form.setInputValue('fieldNameField.input', 'field_1'); + // Save the field + await saveNewProcessor(); + + const processors = getProcessorValue(onUpdate, REGISTERED_DOMAIN_TYPE); + expect(processors[0][REGISTERED_DOMAIN_TYPE]).toEqual({ + field: 'field_1', + ...defaultRegisteredDomainParameters, + }); + }); + + test('should still send ignore_missing:false when the toggle is disabled', async () => { + const { + actions: { saveNewProcessor }, + form, + } = testBed; + + // Add "field" value (required) + form.setInputValue('fieldNameField.input', 'field_1'); + + // Disable ignore missing toggle + form.toggleEuiSwitch('ignoreMissingSwitch.input'); + + // Save the field with new changes + await saveNewProcessor(); + + const processors = getProcessorValue(onUpdate, REGISTERED_DOMAIN_TYPE); + expect(processors[0][REGISTERED_DOMAIN_TYPE]).toEqual({ + ...defaultRegisteredDomainParameters, + field: 'field_1', + ignore_missing: false, + }); + }); + + test('allows optional parameters to be set', async () => { + const { + actions: { saveNewProcessor }, + form, + } = testBed; + + // Add "field" value (required) + form.setInputValue('fieldNameField.input', 'field_1'); + + // Set optional parameteres + form.setInputValue('targetField.input', 'target_field'); + + // Save the field with new changes + await saveNewProcessor(); + + const processors = getProcessorValue(onUpdate, REGISTERED_DOMAIN_TYPE); + expect(processors[0][REGISTERED_DOMAIN_TYPE]).toEqual({ + field: 'field_1', + target_field: 'target_field', + ...defaultRegisteredDomainParameters, + }); + }); +}); diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/index.ts index 9dec9d3f0384f..4fb4365c477b5 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/index.ts @@ -28,6 +28,7 @@ export { Json } from './json'; export { Kv } from './kv'; export { Lowercase } from './lowercase'; export { Pipeline } from './pipeline'; +export { RegisteredDomain } from './registered_domain'; export { Remove } from './remove'; export { Rename } from './rename'; export { Script } from './script'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/registered_domain.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/registered_domain.tsx new file mode 100644 index 0000000000000..4118a125914b2 --- /dev/null +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/registered_domain.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { FunctionComponent } from 'react'; +import { i18n } from '@kbn/i18n'; + +import { from } from './shared'; +import { FieldNameField } from './common_fields/field_name_field'; +import { TargetField } from './common_fields/target_field'; +import { IgnoreMissingField } from './common_fields/ignore_missing_field'; +import { SerializerFunc } from '../../../../../../shared_imports'; + +export const RegisteredDomain: FunctionComponent = () => { + return ( + <> + + + + + } + /> + + ); +}; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/shared/map_processor_type_to_form.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/shared/map_processor_type_to_form.tsx index 5ab2d68aa193f..b5e42ea56bdf8 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/shared/map_processor_type_to_form.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/shared/map_processor_type_to_form.tsx @@ -34,6 +34,7 @@ import { Kv, Lowercase, Pipeline, + RegisteredDomain, Remove, Rename, Script, @@ -518,6 +519,28 @@ export const mapProcessorTypeToDescriptor: MapProcessorTypeToDescriptor = { }, }), }, + registered_domain: { + FieldsComponent: RegisteredDomain, + docLinkPath: '/registered-domain-processor.html', + label: i18n.translate('xpack.ingestPipelines.processors.label.registeredDomain', { + defaultMessage: 'Registered domain', + }), + typeDescription: i18n.translate( + 'xpack.ingestPipelines.processors.description.registeredDomain', + { + defaultMessage: + 'Extracts the registered domain (effective top-level domain), sub-domain, and top-level domain from a fully qualified domain name.', + } + ), + getDefaultDescription: ({ field }) => + i18n.translate('xpack.ingestPipelines.processors.defaultDescription.registeredDomain', { + defaultMessage: + 'Extracts the registered domain, sub-domain, and top-level domain from "{field}"', + values: { + field, + }, + }), + }, remove: { FieldsComponent: Remove, docLinkPath: '/remove-processor.html', diff --git a/x-pack/plugins/ingest_pipelines/public/shared_imports.ts b/x-pack/plugins/ingest_pipelines/public/shared_imports.ts index 4afd434b89372..8ed57221a1395 100644 --- a/x-pack/plugins/ingest_pipelines/public/shared_imports.ts +++ b/x-pack/plugins/ingest_pipelines/public/shared_imports.ts @@ -52,6 +52,7 @@ export { ValidationConfig, useFormData, FormOptions, + SerializerFunc, } from '../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; export { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_editor.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_editor.tsx index d84d418ff231c..8e26713630281 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_editor.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_editor.tsx @@ -7,7 +7,7 @@ import './dimension_editor.scss'; import _ from 'lodash'; -import React, { useState, useMemo, useEffect, useRef } from 'react'; +import React, { useState, useMemo } from 'react'; import { i18n } from '@kbn/i18n'; import { EuiListGroup, @@ -44,6 +44,7 @@ import { ReferenceEditor } from './reference_editor'; import { setTimeScaling, TimeScaling } from './time_scaling'; import { defaultFilter, Filtering, setFilter } from './filtering'; import { AdvancedOptions } from './advanced_options'; +import { useDebouncedValue } from '../../shared_components'; const operationPanels = getOperationDisplay(); @@ -53,39 +54,8 @@ export interface DimensionEditorProps extends IndexPatternDimensionEditorProps { currentIndexPattern: IndexPattern; } -/** - * This component shows a debounced input for the label of a dimension. It will update on root state changes - * if no debounced changes are in flight because the user is currently typing into the input. - */ const LabelInput = ({ value, onChange }: { value: string; onChange: (value: string) => void }) => { - const [inputValue, setInputValue] = useState(value); - const unflushedChanges = useRef(false); - - // Save the initial value - const initialValue = useRef(value); - - const onChangeDebounced = useMemo(() => { - const callback = _.debounce((val: string) => { - onChange(val); - unflushedChanges.current = false; - }, 256); - return (val: string) => { - unflushedChanges.current = true; - callback(val); - }; - }, [onChange]); - - useEffect(() => { - if (!unflushedChanges.current && value !== inputValue) { - setInputValue(value); - } - }, [value, inputValue]); - - const handleInputChange = (e: React.ChangeEvent) => { - const val = String(e.target.value); - setInputValue(val); - onChangeDebounced(val || initialValue.current); - }; + const { inputValue, handleInputChange, initialValue } = useDebouncedValue({ onChange, value }); return ( { + handleInputChange(e.target.value); + }} + placeholder={initialValue} /> ); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/ranges/ranges.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/ranges/ranges.test.tsx index 08bcfcb2e93be..cfbe0f8903daf 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/ranges/ranges.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/ranges/ranges.test.tsx @@ -46,6 +46,17 @@ jest.mock('@elastic/eui', () => { }; }); +jest.mock('react-use/lib/useDebounce', () => (fn: () => void) => fn()); + +jest.mock('lodash', () => { + const original = jest.requireActual('lodash'); + + return { + ...original, + debounce: (fn: unknown) => fn, + }; +}); + const dataPluginMockValue = dataPluginMock.createStartContract(); // need to overwrite the formatter field first dataPluginMockValue.fieldFormats.deserialize = jest.fn().mockImplementation(({ params }) => { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/shared_components/label_input.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/shared_components/label_input.tsx index b9870dc8bfec3..81f1b669a53a2 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/shared_components/label_input.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/shared_components/label_input.tsx @@ -5,10 +5,10 @@ * 2.0. */ -import React, { useState } from 'react'; -import useDebounce from 'react-use/lib/useDebounce'; +import React from 'react'; import { EuiFieldText, keys } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; +import { useDebouncedValue } from '../../../../shared_components'; export const LabelInput = ({ value, @@ -27,20 +27,13 @@ export const LabelInput = ({ dataTestSubj?: string; compressed?: boolean; }) => { - const [inputValue, setInputValue] = useState(value); - - useDebounce(() => onChange(inputValue), 256, [inputValue]); - - const handleInputChange = (e: React.ChangeEvent) => { - const val = String(e.target.value); - setInputValue(val); - }; + const { inputValue, handleInputChange } = useDebouncedValue({ value, onChange }); return ( handleInputChange(e.target.value)} fullWidth placeholder={placeholder || ''} inputRef={(node) => { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/query_input.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/query_input.tsx index 50941148342c3..6c2b62f96eaec 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/query_input.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/query_input.tsx @@ -5,11 +5,11 @@ * 2.0. */ -import React, { useState } from 'react'; -import useDebounce from 'react-use/lib/useDebounce'; +import React from 'react'; import { i18n } from '@kbn/i18n'; import { IndexPattern } from './types'; import { QueryStringInput, Query } from '../../../../../src/plugins/data/public'; +import { useDebouncedValue } from '../shared_components'; export const QueryInput = ({ value, @@ -26,13 +26,7 @@ export const QueryInput = ({ onSubmit: () => void; disableAutoFocus?: boolean; }) => { - const [inputValue, setInputValue] = useState(value); - - useDebounce(() => onChange(inputValue), 256, [inputValue]); - - const handleInputChange = (input: Query) => { - setInputValue(input); - }; + const { inputValue, handleInputChange } = useDebouncedValue({ value, onChange }); return ( void; }) => { - const [localValue, setLocalValue] = useState(value); - useDebounce(() => setValue(localValue), 256, [localValue]); - + const { inputValue, handleInputChange } = useDebouncedValue({ value, onChange: setValue }); return ( { - setLocalValue(Number(e.currentTarget.value)); + handleInputChange(Number(e.currentTarget.value)); }} /> ); diff --git a/x-pack/plugins/lens/public/shared_components/debounced_value.ts b/x-pack/plugins/lens/public/shared_components/debounced_value.ts new file mode 100644 index 0000000000000..5447384ce38ea --- /dev/null +++ b/x-pack/plugins/lens/public/shared_components/debounced_value.ts @@ -0,0 +1,52 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { useState, useMemo, useEffect, useRef } from 'react'; +import _ from 'lodash'; + +/** + * Debounces value changes and updates inputValue on root state changes if no debounced changes + * are in flight because the user is currently modifying the value. + */ + +export const useDebouncedValue = ({ + onChange, + value, +}: { + onChange: (val: T) => void; + value: T; +}) => { + const [inputValue, setInputValue] = useState(value); + const unflushedChanges = useRef(false); + + // Save the initial value + const initialValue = useRef(value); + + const onChangeDebounced = useMemo(() => { + const callback = _.debounce((val: T) => { + onChange(val); + unflushedChanges.current = false; + }, 256); + return (val: T) => { + unflushedChanges.current = true; + callback(val); + }; + }, [onChange]); + + useEffect(() => { + if (!unflushedChanges.current && value !== inputValue) { + setInputValue(value); + } + }, [value, inputValue]); + + const handleInputChange = (val: T) => { + setInputValue(val); + onChangeDebounced(val || initialValue.current); + }; + + return { inputValue, handleInputChange, initialValue: initialValue.current }; +}; diff --git a/x-pack/plugins/lens/public/shared_components/index.ts b/x-pack/plugins/lens/public/shared_components/index.ts index 482571696a4d3..ae57da976a881 100644 --- a/x-pack/plugins/lens/public/shared_components/index.ts +++ b/x-pack/plugins/lens/public/shared_components/index.ts @@ -9,3 +9,4 @@ export * from './empty_placeholder'; export { ToolbarPopoverProps, ToolbarPopover } from './toolbar_popover'; export { LegendSettingsPopover } from './legend_settings_popover'; export { PalettePicker } from './palette_picker'; +export { useDebouncedValue } from './debounced_value'; diff --git a/x-pack/plugins/lens/public/xy_visualization/__snapshots__/expression.test.tsx.snap b/x-pack/plugins/lens/public/xy_visualization/__snapshots__/expression.test.tsx.snap index aa22bbb0c15c6..f9b4e33072c81 100644 --- a/x-pack/plugins/lens/public/xy_visualization/__snapshots__/expression.test.tsx.snap +++ b/x-pack/plugins/lens/public/xy_visualization/__snapshots__/expression.test.tsx.snap @@ -52,6 +52,13 @@ exports[`xy_expression XYChart component it renders area 1`] = ` title="c" /> 0) || + (extent.upperBound !== undefined && extent.upperBound) < 0); + const boundaryError = + extent && + extent.lowerBound !== undefined && + extent.upperBound !== undefined && + extent.upperBound <= extent.lowerBound; + return { inclusiveZeroError, boundaryError }; +} diff --git a/x-pack/plugins/lens/public/xy_visualization/axis_settings_popover.test.tsx b/x-pack/plugins/lens/public/xy_visualization/axis_settings_popover.test.tsx index 48cc45dfacdca..047c95846cd27 100644 --- a/x-pack/plugins/lens/public/xy_visualization/axis_settings_popover.test.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/axis_settings_popover.test.tsx @@ -32,6 +32,7 @@ describe('Axes Settings', () => { toggleAxisTitleVisibility: jest.fn(), toggleTickLabelsVisibility: jest.fn(), toggleGridlinesVisibility: jest.fn(), + hasBarOrAreaOnAxis: false, }; }); @@ -91,4 +92,26 @@ describe('Axes Settings', () => { ); expect(component.find('[data-test-subj="lnsshowEndzones"]').prop('checked')).toBe(true); }); + + describe('axis extent', () => { + it('hides the extent section if no extent is passed in', () => { + const component = shallow(); + expect(component.find('[data-test-subj="lnsXY_axisBounds_groups"]').length).toBe(0); + }); + + it('renders bound inputs if mode is custom', () => { + const setSpy = jest.fn(); + const component = shallow( + + ); + const lower = component.find('[data-test-subj="lnsXY_axisExtent_lowerBound"]'); + const upper = component.find('[data-test-subj="lnsXY_axisExtent_upperBound"]'); + expect(lower.prop('value')).toEqual(123); + expect(upper.prop('value')).toEqual(456); + }); + }); }); diff --git a/x-pack/plugins/lens/public/xy_visualization/axis_settings_popover.tsx b/x-pack/plugins/lens/public/xy_visualization/axis_settings_popover.tsx index d9c60ae666484..43ebc91f533a4 100644 --- a/x-pack/plugins/lens/public/xy_visualization/axis_settings_popover.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/axis_settings_popover.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import React, { useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { EuiFlexGroup, EuiFlexItem, @@ -14,16 +14,21 @@ import { EuiSpacer, EuiFieldText, IconType, + EuiFormRow, + EuiButtonGroup, + htmlIdGenerator, + EuiFieldNumber, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { XYLayerConfig, AxesSettingsConfig } from './types'; -import { ToolbarPopover } from '../shared_components'; +import { XYLayerConfig, AxesSettingsConfig, AxisExtentConfig } from './types'; +import { ToolbarPopover, useDebouncedValue } from '../shared_components'; import { isHorizontalChart } from './state_helpers'; import { EuiIconAxisBottom } from '../assets/axis_bottom'; import { EuiIconAxisLeft } from '../assets/axis_left'; import { EuiIconAxisRight } from '../assets/axis_right'; import { EuiIconAxisTop } from '../assets/axis_top'; import { ToolbarButtonProps } from '../../../../../src/plugins/kibana_react/public'; +import { validateExtent } from './axes_configuration'; type AxesSettingsConfigKeys = keyof AxesSettingsConfig; export interface AxisSettingsPopoverProps { @@ -79,6 +84,16 @@ export interface AxisSettingsPopoverProps { * Flag whether endzones are visible */ endzonesVisible?: boolean; + /** + * axis extent + */ + extent?: AxisExtentConfig; + /** + * set axis extent + */ + setExtent?: (extent: AxisExtentConfig | undefined) => void; + hasBarOrAreaOnAxis: boolean; + dataBounds?: { min: number; max: number }; } const popoverConfig = ( axis: AxesSettingsConfigKeys, @@ -134,6 +149,8 @@ const popoverConfig = ( } }; +const noop = () => {}; +const idPrefix = htmlIdGenerator()(); export const AxisSettingsPopover: React.FunctionComponent = ({ layers, axis, @@ -148,16 +165,49 @@ export const AxisSettingsPopover: React.FunctionComponent { - const [title, setTitle] = useState(axisTitle); - const isHorizontal = layers?.length ? isHorizontalChart(layers) : false; const config = popoverConfig(axis, isHorizontal); - const onTitleChange = (value: string): void => { - setTitle(value); - updateTitleState(value); - }; + const { inputValue: debouncedExtent, handleInputChange: setDebouncedExtent } = useDebouncedValue< + AxisExtentConfig | undefined + >({ + value: extent, + onChange: setExtent || noop, + }); + + const [localExtent, setLocalExtent] = useState(debouncedExtent); + + const { inclusiveZeroError, boundaryError } = validateExtent(hasBarOrAreaOnAxis, localExtent); + + useEffect(() => { + // set global extent if local extent is not invalid + if ( + setExtent && + !inclusiveZeroError && + !boundaryError && + localExtent && + localExtent !== debouncedExtent + ) { + setDebouncedExtent(localExtent); + } + }, [ + localExtent, + inclusiveZeroError, + boundaryError, + setDebouncedExtent, + debouncedExtent, + setExtent, + ]); + + const { inputValue: title, handleInputChange: onTitleChange } = useDebouncedValue({ + value: axisTitle || '', + onChange: updateTitleState, + }); return ( )} + {localExtent && setExtent && ( + <> + + + { + const newMode = id.replace(idPrefix, '') as AxisExtentConfig['mode']; + setLocalExtent({ + ...localExtent, + mode: newMode, + lowerBound: + newMode === 'custom' && dataBounds ? Math.min(0, dataBounds.min) : undefined, + upperBound: newMode === 'custom' && dataBounds ? dataBounds.max : undefined, + }); + }} + /> + + {localExtent.mode === 'custom' && ( + <> + + + + + { + const val = Number(e.target.value); + if (e.target.value === '' || Number.isNaN(Number(val))) { + setLocalExtent({ + ...localExtent, + lowerBound: undefined, + }); + } else { + setLocalExtent({ + ...localExtent, + lowerBound: val, + }); + } + }} + onBlur={() => { + if (localExtent.lowerBound === undefined && dataBounds) { + setLocalExtent({ + ...localExtent, + lowerBound: Math.min(0, dataBounds.min), + }); + } + }} + /> + + + + + { + const val = Number(e.target.value); + if (e.target.value === '' || Number.isNaN(Number(val))) { + setLocalExtent({ + ...localExtent, + upperBound: undefined, + }); + } else { + setLocalExtent({ + ...localExtent, + upperBound: val, + }); + } + }} + onBlur={() => { + if (localExtent.upperBound === undefined && dataBounds) { + setLocalExtent({ + ...localExtent, + upperBound: dataBounds.max, + }); + } + }} + /> + + + + + )} + + )} ); }; diff --git a/x-pack/plugins/lens/public/xy_visualization/expression.test.tsx b/x-pack/plugins/lens/public/xy_visualization/expression.test.tsx index fe0513caa08a8..3fab88248d4a5 100644 --- a/x-pack/plugins/lens/public/xy_visualization/expression.test.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/expression.test.tsx @@ -283,6 +283,14 @@ const createArgsWithLayers = (layers: LayerArgs[] = [sampleLayer]): XYArgs => ({ yLeft: false, yRight: false, }, + yLeftExtent: { + mode: 'full', + type: 'lens_xy_axisExtentConfig', + }, + yRightExtent: { + mode: 'full', + type: 'lens_xy_axisExtentConfig', + }, layers, }); @@ -681,6 +689,114 @@ describe('xy_expression', () => { }); }); + describe('y axis extents', () => { + test('it passes custom y axis extents to elastic-charts axis spec', () => { + const { data, args } = sampleArgs(); + + const component = shallow( + + ); + expect(component.find(Axis).find('[id="left"]').prop('domain')).toEqual({ + fit: false, + min: 123, + max: 456, + }); + }); + + test('it passes fit to bounds y axis extents to elastic-charts axis spec', () => { + const { data, args } = sampleArgs(); + + const component = shallow( + + ); + expect(component.find(Axis).find('[id="left"]').prop('domain')).toEqual({ + fit: true, + min: undefined, + max: undefined, + }); + }); + + test('it does not allow fit for area chart', () => { + const { data, args } = sampleArgs(); + + const component = shallow( + + ); + expect(component.find(Axis).find('[id="left"]').prop('domain')).toEqual({ + fit: false, + }); + }); + + test('it does not allow positive lower bound for bar', () => { + const { data, args } = sampleArgs(); + + const component = shallow( + + ); + expect(component.find(Axis).find('[id="left"]').prop('domain')).toEqual({ + fit: false, + min: undefined, + max: undefined, + }); + }); + }); + test('it has xDomain undefined if the x is not a time scale or a histogram', () => { const { data, args } = sampleArgs(); @@ -1761,6 +1877,14 @@ describe('xy_expression', () => { yLeft: false, yRight: false, }, + yLeftExtent: { + mode: 'full', + type: 'lens_xy_axisExtentConfig', + }, + yRightExtent: { + mode: 'full', + type: 'lens_xy_axisExtentConfig', + }, layers: [ { layerId: 'first', @@ -1835,6 +1959,14 @@ describe('xy_expression', () => { yLeft: false, yRight: false, }, + yLeftExtent: { + mode: 'full', + type: 'lens_xy_axisExtentConfig', + }, + yRightExtent: { + mode: 'full', + type: 'lens_xy_axisExtentConfig', + }, layers: [ { layerId: 'first', @@ -1895,6 +2027,14 @@ describe('xy_expression', () => { yLeft: false, yRight: false, }, + yLeftExtent: { + mode: 'full', + type: 'lens_xy_axisExtentConfig', + }, + yRightExtent: { + mode: 'full', + type: 'lens_xy_axisExtentConfig', + }, layers: [ { layerId: 'first', diff --git a/x-pack/plugins/lens/public/xy_visualization/expression.tsx b/x-pack/plugins/lens/public/xy_visualization/expression.tsx index 5416c8eda0aa9..006727b05b905 100644 --- a/x-pack/plugins/lens/public/xy_visualization/expression.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/expression.tsx @@ -55,7 +55,7 @@ import { import { EmptyPlaceholder } from '../shared_components'; import { desanitizeFilterContext } from '../utils'; import { fittingFunctionDefinitions, getFitOptions } from './fitting_functions'; -import { getAxesConfiguration } from './axes_configuration'; +import { getAxesConfiguration, GroupsConfiguration, validateExtent } from './axes_configuration'; import { getColorAssignments } from './color_assignment'; import { getXDomain, XyEndzones } from './x_domain'; @@ -135,6 +135,18 @@ export const xyChart: ExpressionFunctionDefinition< defaultMessage: 'Y right axis title', }), }, + yLeftExtent: { + types: ['lens_xy_axisExtentConfig'], + help: i18n.translate('xpack.lens.xyChart.yLeftExtent.help', { + defaultMessage: 'Y left axis extents', + }), + }, + yRightExtent: { + types: ['lens_xy_axisExtentConfig'], + help: i18n.translate('xpack.lens.xyChart.yRightExtent.help', { + defaultMessage: 'Y right axis extents', + }), + }, legend: { types: ['lens_xy_legendConfig'], help: i18n.translate('xpack.lens.xyChart.legend.help', { @@ -345,6 +357,8 @@ export function XYChart({ gridlinesVisibilitySettings, valueLabels, hideEndzones, + yLeftExtent, + yRightExtent, } = args; const chartTheme = chartsThemeService.useChartsTheme(); const chartBaseTheme = chartsThemeService.useChartsBaseTheme(); @@ -445,6 +459,33 @@ export function XYChart({ return style; }; + const getYAxisDomain = (axis: GroupsConfiguration[number]) => { + const extent = axis.groupId === 'left' ? yLeftExtent : yRightExtent; + const hasBarOrArea = Boolean( + axis.series.some((series) => { + const seriesType = filteredLayers.find((l) => l.layerId === series.layer)?.seriesType; + return seriesType?.includes('bar') || seriesType?.includes('area'); + }) + ); + const fit = !hasBarOrArea && extent.mode === 'dataBounds'; + let min: undefined | number; + let max: undefined | number; + + if (extent.mode === 'custom') { + const { inclusiveZeroError, boundaryError } = validateExtent(hasBarOrArea, extent); + if (!inclusiveZeroError && !boundaryError) { + min = extent.lowerBound; + max = extent.upperBound; + } + } + + return { + fit, + min, + max, + }; + }; + const shouldShowValueLabels = // No stacked bar charts filteredLayers.every((layer) => !layer.seriesType.includes('stacked')) && @@ -597,24 +638,27 @@ export function XYChart({ }} /> - {yAxesConfiguration.map((axis) => ( - axis.formatter?.convert(d) || ''} - style={getYAxesStyle(axis.groupId)} - /> - ))} + {yAxesConfiguration.map((axis) => { + return ( + axis.formatter?.convert(d) || ''} + style={getYAxesStyle(axis.groupId)} + domain={getYAxisDomain(axis)} + /> + ); + })} {!hideEndzones && ( legendConfig); expressions.registerFunction(() => yAxisConfig); expressions.registerFunction(() => tickLabelsConfig); + expressions.registerFunction(() => axisExtentConfig); expressions.registerFunction(() => gridlinesConfig); expressions.registerFunction(() => axisTitlesVisibilityConfig); expressions.registerFunction(() => layerConfig); diff --git a/x-pack/plugins/lens/public/xy_visualization/to_expression.test.ts b/x-pack/plugins/lens/public/xy_visualization/to_expression.test.ts index 89dca6e8a3944..b88d38e18329c 100644 --- a/x-pack/plugins/lens/public/xy_visualization/to_expression.test.ts +++ b/x-pack/plugins/lens/public/xy_visualization/to_expression.test.ts @@ -52,6 +52,11 @@ describe('#toExpression', () => { tickLabelsVisibilitySettings: { x: false, yLeft: true, yRight: true }, gridlinesVisibilitySettings: { x: false, yLeft: true, yRight: true }, hideEndzones: true, + yRightExtent: { + mode: 'custom', + lowerBound: 123, + upperBound: 456, + }, layers: [ { layerId: 'first', 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 02c5f3773d813..dea6b1a7be0c5 100644 --- a/x-pack/plugins/lens/public/xy_visualization/to_expression.ts +++ b/x-pack/plugins/lens/public/xy_visualization/to_expression.ts @@ -149,6 +149,50 @@ export const buildExpression = ( ], fittingFunction: [state.fittingFunction || 'None'], curveType: [state.curveType || 'LINEAR'], + yLeftExtent: [ + { + type: 'expression', + chain: [ + { + type: 'function', + function: 'lens_xy_axisExtentConfig', + arguments: { + mode: [state?.yLeftExtent?.mode || 'full'], + lowerBound: + state?.yLeftExtent?.lowerBound !== undefined + ? [state?.yLeftExtent?.lowerBound] + : [], + upperBound: + state?.yLeftExtent?.upperBound !== undefined + ? [state?.yLeftExtent?.upperBound] + : [], + }, + }, + ], + }, + ], + yRightExtent: [ + { + type: 'expression', + chain: [ + { + type: 'function', + function: 'lens_xy_axisExtentConfig', + arguments: { + mode: [state?.yRightExtent?.mode || 'full'], + lowerBound: + state?.yRightExtent?.lowerBound !== undefined + ? [state?.yRightExtent?.lowerBound] + : [], + upperBound: + state?.yRightExtent?.upperBound !== undefined + ? [state?.yRightExtent?.upperBound] + : [], + }, + }, + ], + }, + ], axisTitlesVisibilitySettings: [ { type: 'expression', diff --git a/x-pack/plugins/lens/public/xy_visualization/types.ts b/x-pack/plugins/lens/public/xy_visualization/types.ts index 0622f1c43f1c3..ea28b492477c1 100644 --- a/x-pack/plugins/lens/public/xy_visualization/types.ts +++ b/x-pack/plugins/lens/public/xy_visualization/types.ts @@ -211,6 +211,54 @@ export const axisTitlesVisibilityConfig: ExpressionFunctionDefinition< }, }; +export interface AxisExtentConfig { + mode: 'full' | 'dataBounds' | 'custom'; + lowerBound?: number; + upperBound?: number; +} + +export const axisExtentConfig: ExpressionFunctionDefinition< + 'lens_xy_axisExtentConfig', + null, + AxisExtentConfig, + AxisExtentConfigResult +> = { + name: 'lens_xy_axisExtentConfig', + aliases: [], + type: 'lens_xy_axisExtentConfig', + help: `Configure the xy chart's axis extents`, + inputTypes: ['null'], + args: { + mode: { + types: ['string'], + options: ['full', 'dataBounds', 'custom'], + help: i18n.translate('xpack.lens.xyChart.extentMode.help', { + defaultMessage: 'The extent mode', + }), + }, + lowerBound: { + types: ['number'], + help: i18n.translate('xpack.lens.xyChart.extentMode.help', { + defaultMessage: 'The extent mode', + }), + }, + upperBound: { + types: ['number'], + help: i18n.translate('xpack.lens.xyChart.extentMode.help', { + defaultMessage: 'The extent mode', + }), + }, + }, + fn: function fn(input: unknown, args: AxisExtentConfig) { + return { + type: 'lens_xy_axisExtentConfig', + ...args, + }; + }, +}; + +export type AxisExtentConfigResult = AxisExtentConfig & { type: 'lens_xy_axisExtentConfig' }; + interface AxisConfig { title: string; hide?: boolean; @@ -404,6 +452,8 @@ export interface XYArgs { xTitle: string; yTitle: string; yRightTitle: string; + yLeftExtent: AxisExtentConfigResult; + yRightExtent: AxisExtentConfigResult; legend: LegendConfig & { type: 'lens_xy_legendConfig' }; valueLabels: ValueLabelConfig; layers: LayerArgs[]; @@ -425,6 +475,8 @@ export interface XYState { legend: LegendConfig; valueLabels?: ValueLabelConfig; fittingFunction?: FittingFunction; + yLeftExtent?: AxisExtentConfig; + yRightExtent?: AxisExtentConfig; layers: XYLayerConfig[]; xTitle?: string; yTitle?: string; diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.test.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.test.tsx index e3e8c6e93e3aa..0bafbead7d543 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.test.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.test.tsx @@ -161,6 +161,90 @@ describe('XY Config panels', () => { expect(component.find(AxisSettingsPopover).at(1).prop('endzonesVisible')).toBe(false); expect(component.find(AxisSettingsPopover).at(2).prop('setEndzoneVisibility')).toBeFalsy(); }); + + it('should pass in information about current data bounds', () => { + const state = testState(); + frame.activeData = { + first: { + type: 'datatable', + rows: [{ bar: -5 }, { bar: 50 }], + columns: [ + { + id: 'baz', + meta: { + type: 'number', + }, + name: 'baz', + }, + { + id: 'foo', + meta: { + type: 'number', + }, + name: 'foo', + }, + { + id: 'bar', + meta: { + type: 'number', + }, + name: 'bar', + }, + ], + }, + }; + const component = shallow( + + ); + + expect(component.find(AxisSettingsPopover).at(0).prop('dataBounds')).toEqual({ + min: -5, + max: 50, + }); + }); + + it('should pass in extent information', () => { + const state = testState(); + const component = shallow( + + ); + + expect(component.find(AxisSettingsPopover).at(0).prop('extent')).toEqual({ + mode: 'custom', + lowerBound: 123, + upperBound: 456, + }); + expect(component.find(AxisSettingsPopover).at(0).prop('setExtent')).toBeTruthy(); + expect(component.find(AxisSettingsPopover).at(1).prop('extent')).toBeFalsy(); + expect(component.find(AxisSettingsPopover).at(1).prop('setExtent')).toBeFalsy(); + // default extent + expect(component.find(AxisSettingsPopover).at(2).prop('extent')).toEqual({ + mode: 'full', + }); + expect(component.find(AxisSettingsPopover).at(2).prop('setExtent')).toBeTruthy(); + }); }); describe('Dimension Editor', () => { 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 eccf4d9b64345..3037513ccd56e 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 @@ -6,7 +6,7 @@ */ import './xy_config_panel.scss'; -import React, { useMemo, useState, memo } from 'react'; +import React, { useMemo, useState, memo, useCallback } from 'react'; import { i18n } from '@kbn/i18n'; import { Position, ScaleType } from '@elastic/charts'; import { debounce } from 'lodash'; @@ -27,14 +27,22 @@ import { VisualizationToolbarProps, VisualizationDimensionEditorProps, FormatFactory, + FramePublicAPI, } from '../types'; -import { State, SeriesType, visualizationTypes, YAxisMode, AxesSettingsConfig } from './types'; +import { + State, + SeriesType, + visualizationTypes, + YAxisMode, + AxesSettingsConfig, + AxisExtentConfig, +} from './types'; import { isHorizontalChart, isHorizontalSeries, getSeriesColor } from './state_helpers'; import { trackUiEvent } from '../lens_ui_telemetry'; import { LegendSettingsPopover } from '../shared_components'; import { AxisSettingsPopover } from './axis_settings_popover'; import { TooltipWrapper } from './tooltip_wrapper'; -import { getAxesConfiguration } from './axes_configuration'; +import { getAxesConfiguration, GroupsConfiguration } from './axes_configuration'; import { PalettePicker } from '../shared_components'; import { getAccessorColorConfig, getColorAssignments } from './color_assignment'; import { getScaleType, getSortedAccessors } from './to_expression'; @@ -123,11 +131,44 @@ export function LayerContextMenu(props: VisualizationLayerWidgetProps) { ); } +const getDataBounds = function ( + activeData: FramePublicAPI['activeData'], + axes: GroupsConfiguration +) { + const groups: Partial> = {}; + axes.forEach((axis) => { + let min = Number.MAX_VALUE; + let max = Number.MIN_VALUE; + axis.series.forEach((series) => { + activeData?.[series.layer].rows.forEach((row) => { + const value = row[series.accessor]; + if (!Number.isNaN(value)) { + if (value < min) { + min = value; + } + if (value > max) { + max = value; + } + } + }); + }); + if (min !== Number.MAX_VALUE && max !== Number.MIN_VALUE) { + groups[axis.groupId] = { + min: Math.round((min + Number.EPSILON) * 100) / 100, + max: Math.round((max + Number.EPSILON) * 100) / 100, + }; + } + }); + + return groups; +}; + export const XyToolbar = memo(function XyToolbar(props: VisualizationToolbarProps) { const { state, setState, frame } = props; const shouldRotate = state?.layers.length ? isHorizontalChart(state.layers) : false; - const axisGroups = getAxesConfiguration(state?.layers, shouldRotate); + const axisGroups = getAxesConfiguration(state?.layers, shouldRotate, frame.activeData); + const dataBounds = getDataBounds(frame.activeData, axisGroups); const tickLabelsVisibilitySettings = { x: state?.tickLabelsVisibilitySettings?.x ?? true, @@ -210,6 +251,40 @@ export const XyToolbar = memo(function XyToolbar(props: VisualizationToolbarProp : !state?.legend.isVisible ? 'hide' : 'show'; + const hasBarOrAreaOnLeftAxis = Boolean( + axisGroups + .find((group) => group.groupId === 'left') + ?.series?.some((series) => { + const seriesType = state.layers.find((l) => l.layerId === series.layer)?.seriesType; + return seriesType?.includes('bar') || seriesType?.includes('area'); + }) + ); + const setLeftExtent = useCallback( + (extent: AxisExtentConfig | undefined) => { + setState({ + ...state, + yLeftExtent: extent, + }); + }, + [setState, state] + ); + const hasBarOrAreaOnRightAxis = Boolean( + axisGroups + .find((group) => group.groupId === 'left') + ?.series?.some((series) => { + const seriesType = state.layers.find((l) => l.layerId === series.layer)?.seriesType; + return seriesType?.includes('bar') || seriesType?.includes('area'); + }) + ); + const setRightExtent = useCallback( + (extent: AxisExtentConfig | undefined) => { + setState({ + ...state, + yRightExtent: extent, + }); + }, + [setState, state] + ); return ( @@ -282,6 +357,10 @@ export const XyToolbar = memo(function XyToolbar(props: VisualizationToolbarProp } isAxisTitleVisible={axisTitlesVisibilitySettings.yLeft} toggleAxisTitleVisibility={onAxisTitlesVisibilitySettingsChange} + extent={state?.yLeftExtent || { mode: 'full' }} + setExtent={setLeftExtent} + hasBarOrAreaOnAxis={hasBarOrAreaOnLeftAxis} + dataBounds={dataBounds.left} /> 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 d5120cfae973c..4554c34b97c55 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts +++ b/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts @@ -527,6 +527,9 @@ function buildSuggestion({ xTitle: currentState?.xTitle, yTitle: currentState?.yTitle, yRightTitle: currentState?.yRightTitle, + hideEndzones: currentState?.hideEndzones, + yLeftExtent: currentState?.yLeftExtent, + yRightExtent: currentState?.yRightExtent, axisTitlesVisibilitySettings: currentState?.axisTitlesVisibilitySettings || { x: true, yLeft: true, diff --git a/x-pack/plugins/lists/common/exceptions/build_exceptions_filter.ts b/x-pack/plugins/lists/common/exceptions/build_exceptions_filter.ts index eda81f91cd983..6e76076bc63ef 100644 --- a/x-pack/plugins/lists/common/exceptions/build_exceptions_filter.ts +++ b/x-pack/plugins/lists/common/exceptions/build_exceptions_filter.ts @@ -17,10 +17,10 @@ import { entriesNested, } from '@kbn/securitysolution-io-ts-list-types'; -import { Filter } from '../../../../../src/plugins/data/common'; -import { CreateExceptionListItemSchema, ExceptionListItemSchema } from '../schemas'; +import type { Filter } from '../../../../../src/plugins/data/common'; +import type { CreateExceptionListItemSchema, ExceptionListItemSchema } from '../schemas'; -import { BooleanFilter, NestedFilter } from './types'; +import type { BooleanFilter, NestedFilter } from './types'; import { hasLargeValueList } from './utils'; type NonListEntry = EntryMatch | EntryMatchAny | EntryNested | EntryExists; diff --git a/x-pack/plugins/lists/common/exceptions/utils.ts b/x-pack/plugins/lists/common/exceptions/utils.ts index f5881c1d3cbf4..350cb581153b5 100644 --- a/x-pack/plugins/lists/common/exceptions/utils.ts +++ b/x-pack/plugins/lists/common/exceptions/utils.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { EntriesArray } from '@kbn/securitysolution-io-ts-list-types'; +import type { EntriesArray } from '@kbn/securitysolution-io-ts-list-types'; export const hasLargeValueList = (entries: EntriesArray): boolean => { const found = entries.filter(({ type }) => type === 'list'); diff --git a/x-pack/plugins/lists/common/schemas/common/schemas.ts b/x-pack/plugins/lists/common/schemas/common/schemas.ts index 612b7ea559e4a..83ec27d60b76c 100644 --- a/x-pack/plugins/lists/common/schemas/common/schemas.ts +++ b/x-pack/plugins/lists/common/schemas/common/schemas.ts @@ -11,18 +11,6 @@ import * as t from 'io-ts'; import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; import { DefaultNamespace } from '@kbn/securitysolution-io-ts-list-types'; -/** - * @deprecated Directly use the type from the package and not from here - */ -export { - DefaultNamespace, - Type, - OsType, - OsTypeArray, - listOperator as operator, - NonEmptyEntriesArray, -} from '@kbn/securitysolution-io-ts-list-types'; - export const list_id = NonEmptyString; export type ListId = t.TypeOf; export const list_idOrUndefined = t.union([list_id, t.undefined]); @@ -91,12 +79,6 @@ export const _version = t.string; export const _versionOrUndefined = t.union([_version, t.undefined]); export type _VersionOrUndefined = t.TypeOf; -export const version = t.number; -export type Version = t.TypeOf; - -export const versionOrUndefined = t.union([version, t.undefined]); -export type VersionOrUndefined = t.TypeOf; - export const immutable = t.boolean; export type Immutable = t.TypeOf; diff --git a/x-pack/plugins/lists/common/schemas/request/create_exception_list_schema.ts b/x-pack/plugins/lists/common/schemas/request/create_exception_list_schema.ts index 91b3a98bdd5ac..30e4ff908ee80 100644 --- a/x-pack/plugins/lists/common/schemas/request/create_exception_list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/create_exception_list_schema.ts @@ -7,8 +7,6 @@ import * as t from 'io-ts'; import { - DefaultVersionNumber, - DefaultVersionNumberDecoded, NamespaceType, OsTypeArray, Tags, @@ -19,7 +17,11 @@ import { osTypeArrayOrUndefined, tags, } from '@kbn/securitysolution-io-ts-list-types'; -import { DefaultUuid } from '@kbn/securitysolution-io-ts-types'; +import { + DefaultUuid, + DefaultVersionNumber, + DefaultVersionNumberDecoded, +} from '@kbn/securitysolution-io-ts-types'; import { ListId, namespace_type } from '../common/schemas'; import { RequiredKeepUndefined } from '../../types'; diff --git a/x-pack/plugins/lists/common/schemas/request/create_list_schema.ts b/x-pack/plugins/lists/common/schemas/request/create_list_schema.ts index 5fa9da0cdc597..1c197a37c0cbd 100644 --- a/x-pack/plugins/lists/common/schemas/request/create_list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/create_list_schema.ts @@ -9,12 +9,8 @@ import * as t from 'io-ts'; import { DefaultVersionNumber, DefaultVersionNumberDecoded, - description, - id, - meta, - name, - type, -} from '@kbn/securitysolution-io-ts-list-types'; +} from '@kbn/securitysolution-io-ts-types'; +import { description, id, meta, name, type } from '@kbn/securitysolution-io-ts-list-types'; import { deserializer, serializer } from '../common/schemas'; import { RequiredKeepUndefined } from '../../types'; diff --git a/x-pack/plugins/lists/common/schemas/request/patch_list_schema.ts b/x-pack/plugins/lists/common/schemas/request/patch_list_schema.ts index eea4ba9fc87d7..2cd41584ef9ff 100644 --- a/x-pack/plugins/lists/common/schemas/request/patch_list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/patch_list_schema.ts @@ -7,8 +7,9 @@ import * as t from 'io-ts'; import { description, id, meta, name } from '@kbn/securitysolution-io-ts-list-types'; +import { version } from '@kbn/securitysolution-io-ts-types'; -import { _version, version } from '../common/schemas'; +import { _version } from '../common/schemas'; import { RequiredKeepUndefined } from '../../types'; export const patchListSchema = t.intersection([ diff --git a/x-pack/plugins/lists/common/schemas/request/update_exception_list_schema.ts b/x-pack/plugins/lists/common/schemas/request/update_exception_list_schema.ts index c58c1c253a8c4..08f15f52977fd 100644 --- a/x-pack/plugins/lists/common/schemas/request/update_exception_list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/update_exception_list_schema.ts @@ -18,8 +18,9 @@ import { osTypeArrayOrUndefined, tags, } from '@kbn/securitysolution-io-ts-list-types'; +import { version } from '@kbn/securitysolution-io-ts-types'; -import { _version, list_id, namespace_type, version } from '../common/schemas'; +import { _version, list_id, namespace_type } from '../common/schemas'; import { RequiredKeepUndefined } from '../../types'; export const updateExceptionListSchema = t.intersection([ diff --git a/x-pack/plugins/lists/common/schemas/request/update_list_schema.ts b/x-pack/plugins/lists/common/schemas/request/update_list_schema.ts index 230853e69fae4..253c4cec566f4 100644 --- a/x-pack/plugins/lists/common/schemas/request/update_list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/update_list_schema.ts @@ -6,7 +6,8 @@ */ import * as t from 'io-ts'; -import { description, id, meta, name, version } from '@kbn/securitysolution-io-ts-list-types'; +import { description, id, meta, name } from '@kbn/securitysolution-io-ts-list-types'; +import { version } from '@kbn/securitysolution-io-ts-types'; import { _version } from '../common/schemas'; import { RequiredKeepUndefined } from '../../types'; diff --git a/x-pack/plugins/lists/common/schemas/response/exception_list_schema.ts b/x-pack/plugins/lists/common/schemas/response/exception_list_schema.ts index 7bfc2af9863e2..f96496343fb7e 100644 --- a/x-pack/plugins/lists/common/schemas/response/exception_list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/response/exception_list_schema.ts @@ -19,6 +19,7 @@ import { updated_at, updated_by, } from '@kbn/securitysolution-io-ts-list-types'; +import { version } from '@kbn/securitysolution-io-ts-types'; import { _versionOrUndefined, @@ -26,7 +27,6 @@ import { list_id, namespace_type, tie_breaker_id, - version, } from '../common/schemas'; export const exceptionListSchema = t.exact( diff --git a/x-pack/plugins/lists/common/schemas/response/list_schema.ts b/x-pack/plugins/lists/common/schemas/response/list_schema.ts index 21504d64fdeaa..5b478cd25daa6 100644 --- a/x-pack/plugins/lists/common/schemas/response/list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/response/list_schema.ts @@ -17,6 +17,7 @@ import { updated_at, updated_by, } from '@kbn/securitysolution-io-ts-list-types'; +import { version } from '@kbn/securitysolution-io-ts-types'; import { _versionOrUndefined, @@ -24,7 +25,6 @@ import { immutable, serializerOrUndefined, tie_breaker_id, - version, } from '../common/schemas'; export const listSchema = t.exact( diff --git a/x-pack/plugins/lists/common/shared_exports.ts b/x-pack/plugins/lists/common/shared_exports.ts index f00afb7ac810d..3f1dc01644e21 100644 --- a/x-pack/plugins/lists/common/shared_exports.ts +++ b/x-pack/plugins/lists/common/shared_exports.ts @@ -5,16 +5,13 @@ * 2.0. */ -export { +export type { ListSchema, ExceptionListSchema, ExceptionListItemSchema, CreateExceptionListSchema, CreateExceptionListItemSchema, UpdateExceptionListItemSchema, - exceptionListItemSchema, - createExceptionListItemSchema, - listSchema, } from './schemas'; export { buildExceptionFilter } from './exceptions'; diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/exception_items_renderer.tsx b/x-pack/plugins/lists/public/exceptions/components/builder/exception_items_renderer.tsx index f771969a92025..6058d4f7b725b 100644 --- a/x-pack/plugins/lists/public/exceptions/components/builder/exception_items_renderer.tsx +++ b/x-pack/plugins/lists/public/exceptions/components/builder/exception_items_renderer.tsx @@ -23,7 +23,7 @@ import { CreateExceptionListItemSchema, ExceptionListItemSchema, exceptionListItemSchema, -} from '../../../../common'; +} from '../../../../common/schemas'; import { AutocompleteStart, IIndexPattern } from '../../../../../../../src/plugins/data/public'; import { AndOrBadge } from '../and_or_badge'; diff --git a/x-pack/plugins/lists/public/exceptions/components/builder/helpers.ts b/x-pack/plugins/lists/public/exceptions/components/builder/helpers.ts index 6cd9dec0dc7a1..c4052acda6045 100644 --- a/x-pack/plugins/lists/public/exceptions/components/builder/helpers.ts +++ b/x-pack/plugins/lists/public/exceptions/components/builder/helpers.ts @@ -29,7 +29,7 @@ import { ListSchema, createExceptionListItemSchema, exceptionListItemSchema, -} from '../../../../common'; +} from '../../../../common/schemas'; import { IFieldType, IIndexPattern } from '../../../../../../../src/plugins/data/public'; import { EXCEPTION_OPERATORS, diff --git a/x-pack/plugins/lists/public/index.ts b/x-pack/plugins/lists/public/index.ts index f940bbe02b8fb..0b67ab05f5bd4 100644 --- a/x-pack/plugins/lists/public/index.ts +++ b/x-pack/plugins/lists/public/index.ts @@ -7,11 +7,11 @@ export * from './shared_exports'; -import { PluginInitializerContext } from '../../../../src/core/public'; +import type { PluginInitializerContext } from '../../../../src/core/public'; import { Plugin } from './plugin'; -import { PluginSetup, PluginStart } from './types'; +import type { PluginSetup, PluginStart } from './types'; export const plugin = (context: PluginInitializerContext): Plugin => new Plugin(context); -export { Plugin, PluginSetup, PluginStart }; +export type { Plugin, PluginSetup, PluginStart }; diff --git a/x-pack/plugins/lists/server/schemas/elastic_query/index_es_list_schema.ts b/x-pack/plugins/lists/server/schemas/elastic_query/index_es_list_schema.ts index 4383e93346291..607535b68c1e5 100644 --- a/x-pack/plugins/lists/server/schemas/elastic_query/index_es_list_schema.ts +++ b/x-pack/plugins/lists/server/schemas/elastic_query/index_es_list_schema.ts @@ -16,13 +16,13 @@ import { updated_at, updated_by, } from '@kbn/securitysolution-io-ts-list-types'; +import { version } from '@kbn/securitysolution-io-ts-types'; import { deserializerOrUndefined, immutable, serializerOrUndefined, tie_breaker_id, - version, } from '../../../common/schemas'; export const indexEsListSchema = t.exact( diff --git a/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.ts b/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.ts index 536269b9c0ae2..f6d6ae4effe72 100644 --- a/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.ts +++ b/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.ts @@ -16,13 +16,13 @@ import { updated_at, updated_by, } from '@kbn/securitysolution-io-ts-list-types'; +import { version } from '@kbn/securitysolution-io-ts-types'; import { deserializerOrUndefined, immutable, serializerOrUndefined, tie_breaker_id, - version, } from '../../../common/schemas'; export const searchEsListSchema = t.exact( diff --git a/x-pack/plugins/lists/server/schemas/saved_objects/exceptions_list_so_schema.ts b/x-pack/plugins/lists/server/schemas/saved_objects/exceptions_list_so_schema.ts index c1f480e50c8f7..d815dbaae0432 100644 --- a/x-pack/plugins/lists/server/schemas/saved_objects/exceptions_list_so_schema.ts +++ b/x-pack/plugins/lists/server/schemas/saved_objects/exceptions_list_so_schema.ts @@ -20,6 +20,7 @@ import { tags, updated_by, } from '@kbn/securitysolution-io-ts-list-types'; +import { versionOrUndefined } from '@kbn/securitysolution-io-ts-types'; import { immutableOrUndefined, @@ -27,7 +28,6 @@ import { list_id, list_type, tie_breaker_id, - versionOrUndefined, } from '../../../common/schemas'; /** diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_endoint_event_filters_list.ts b/x-pack/plugins/lists/server/services/exception_lists/create_endoint_event_filters_list.ts index dba729437b814..9bcf6c63d065d 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/create_endoint_event_filters_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/create_endoint_event_filters_list.ts @@ -7,13 +7,14 @@ import { SavedObjectsClientContract } from 'kibana/server'; import uuid from 'uuid'; +import { Version } from '@kbn/securitysolution-io-ts-types'; import { ENDPOINT_EVENT_FILTERS_LIST_DESCRIPTION, ENDPOINT_EVENT_FILTERS_LIST_ID, ENDPOINT_EVENT_FILTERS_LIST_NAME, } from '../../../common/constants'; -import { ExceptionListSchema, Version } from '../../../common/schemas'; +import { ExceptionListSchema } from '../../../common/schemas'; import { ExceptionListSoSchema } from '../../schemas/saved_objects'; import { getSavedObjectType, transformSavedObjectToExceptionList } from './utils'; 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 de2be0cb72735..86891e5f83955 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 @@ -7,13 +7,14 @@ import { SavedObjectsClientContract } from 'kibana/server'; import uuid from 'uuid'; +import { Version } from '@kbn/securitysolution-io-ts-types'; import { ENDPOINT_LIST_DESCRIPTION, ENDPOINT_LIST_ID, ENDPOINT_LIST_NAME, } from '../../../common/constants'; -import { ExceptionListSchema, Version } from '../../../common/schemas'; +import { ExceptionListSchema } from '../../../common/schemas'; import { ExceptionListSoSchema } from '../../schemas/saved_objects'; import { getSavedObjectType, transformSavedObjectToExceptionList } from './utils'; diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_trusted_apps_list.ts b/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_trusted_apps_list.ts index 6f6ad7c357f14..ada043403f248 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_trusted_apps_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_trusted_apps_list.ts @@ -7,13 +7,14 @@ import { SavedObjectsClientContract } from 'kibana/server'; import uuid from 'uuid'; +import { Version } from '@kbn/securitysolution-io-ts-types'; import { ENDPOINT_TRUSTED_APPS_LIST_DESCRIPTION, ENDPOINT_TRUSTED_APPS_LIST_ID, ENDPOINT_TRUSTED_APPS_LIST_NAME, } from '../../../common/constants'; -import { ExceptionListSchema, Version } from '../../../common/schemas'; +import { ExceptionListSchema } from '../../../common/schemas'; import { ExceptionListSoSchema } from '../../schemas/saved_objects'; import { getSavedObjectType, transformSavedObjectToExceptionList } from './utils'; diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_exception_list.ts b/x-pack/plugins/lists/server/services/exception_lists/create_exception_list.ts index 5f2587fc1e986..c6110dc4f470c 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/create_exception_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/create_exception_list.ts @@ -15,8 +15,9 @@ import { NamespaceType, Tags, } from '@kbn/securitysolution-io-ts-list-types'; +import { Version } from '@kbn/securitysolution-io-ts-types'; -import { ExceptionListSchema, Immutable, ListId, Version } from '../../../common/schemas'; +import { ExceptionListSchema, Immutable, ListId } from '../../../common/schemas'; import { ExceptionListSoSchema } from '../../schemas/saved_objects'; import { getSavedObjectType, transformSavedObjectToExceptionList } from './utils'; 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 576b0c4d25aa0..c6f5e3a3bc166 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 @@ -30,6 +30,8 @@ import { import { EmptyStringArrayDecoded, NonEmptyStringArrayDecoded, + Version, + VersionOrUndefined, } from '@kbn/securitysolution-io-ts-types'; import { @@ -43,8 +45,6 @@ import { PerPageOrUndefined, SortFieldOrUndefined, SortOrderOrUndefined, - Version, - VersionOrUndefined, _VersionOrUndefined, } from '../../../common/schemas'; diff --git a/x-pack/plugins/lists/server/services/exception_lists/update_exception_list.ts b/x-pack/plugins/lists/server/services/exception_lists/update_exception_list.ts index 3daa2e9157b5d..43c319cca0005 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/update_exception_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/update_exception_list.ts @@ -16,11 +16,11 @@ import { OsTypeArray, TagsOrUndefined, } from '@kbn/securitysolution-io-ts-list-types'; +import { VersionOrUndefined } from '@kbn/securitysolution-io-ts-types'; import { ExceptionListSchema, ListIdOrUndefined, - VersionOrUndefined, _VersionOrUndefined, } from '../../../common/schemas'; import { ExceptionListSoSchema } from '../../schemas/saved_objects'; diff --git a/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts b/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts index b3ce823f9ac29..392c44cf72b00 100644 --- a/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts +++ b/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts @@ -9,6 +9,7 @@ import { Readable } from 'stream'; import { ElasticsearchClient } from 'kibana/server'; import { MetaOrUndefined, Type } from '@kbn/securitysolution-io-ts-list-types'; +import { Version } from '@kbn/securitysolution-io-ts-types'; import { createListIfItDoesNotExist } from '../lists/create_list_if_it_does_not_exist'; import { @@ -16,7 +17,6 @@ import { ListIdOrUndefined, ListSchema, SerializerOrUndefined, - Version, } from '../../../common/schemas'; import { ConfigType } from '../../config'; diff --git a/x-pack/plugins/lists/server/services/lists/create_list.ts b/x-pack/plugins/lists/server/services/lists/create_list.ts index d139ef3ea4bb1..bd5b3c901fdc5 100644 --- a/x-pack/plugins/lists/server/services/lists/create_list.ts +++ b/x-pack/plugins/lists/server/services/lists/create_list.ts @@ -14,6 +14,7 @@ import { Name, Type, } from '@kbn/securitysolution-io-ts-list-types'; +import { Version } from '@kbn/securitysolution-io-ts-types'; import { encodeHitVersion } from '../utils/encode_hit_version'; import { @@ -21,7 +22,6 @@ import { Immutable, ListSchema, SerializerOrUndefined, - Version, } from '../../../common/schemas'; import { IndexEsListSchema } from '../../schemas/elastic_query'; diff --git a/x-pack/plugins/lists/server/services/lists/create_list_if_it_does_not_exist.ts b/x-pack/plugins/lists/server/services/lists/create_list_if_it_does_not_exist.ts index 71094a5ab49de..4d4e634a465a7 100644 --- a/x-pack/plugins/lists/server/services/lists/create_list_if_it_does_not_exist.ts +++ b/x-pack/plugins/lists/server/services/lists/create_list_if_it_does_not_exist.ts @@ -13,13 +13,13 @@ import { Name, Type, } from '@kbn/securitysolution-io-ts-list-types'; +import { Version } from '@kbn/securitysolution-io-ts-types'; import { DeserializerOrUndefined, Immutable, ListSchema, SerializerOrUndefined, - Version, } from '../../../common/schemas'; import { getList } from './get_list'; diff --git a/x-pack/plugins/lists/server/services/lists/list_client_types.ts b/x-pack/plugins/lists/server/services/lists/list_client_types.ts index b4fe52019ec7b..28732090342cd 100644 --- a/x-pack/plugins/lists/server/services/lists/list_client_types.ts +++ b/x-pack/plugins/lists/server/services/lists/list_client_types.ts @@ -18,6 +18,7 @@ import { NameOrUndefined, Type, } from '@kbn/securitysolution-io-ts-list-types'; +import { Version, VersionOrUndefined } from '@kbn/securitysolution-io-ts-types'; import { DeserializerOrUndefined, @@ -30,8 +31,6 @@ import { SerializerOrUndefined, SortFieldOrUndefined, SortOrderOrUndefined, - Version, - VersionOrUndefined, _VersionOrUndefined, } from '../../../common/schemas'; import { ConfigType } from '../../config'; diff --git a/x-pack/plugins/lists/server/services/lists/update_list.ts b/x-pack/plugins/lists/server/services/lists/update_list.ts index 374c3cd0e2def..2e1cc43826817 100644 --- a/x-pack/plugins/lists/server/services/lists/update_list.ts +++ b/x-pack/plugins/lists/server/services/lists/update_list.ts @@ -12,10 +12,11 @@ import { MetaOrUndefined, NameOrUndefined, } from '@kbn/securitysolution-io-ts-list-types'; +import { VersionOrUndefined } from '@kbn/securitysolution-io-ts-types'; import { decodeVersion } from '../utils/decode_version'; import { encodeHitVersion } from '../utils/encode_hit_version'; -import { ListSchema, VersionOrUndefined, _VersionOrUndefined } from '../../../common/schemas'; +import { ListSchema, _VersionOrUndefined } from '../../../common/schemas'; import { UpdateEsListSchema } from '../../schemas/elastic_query'; import { getList } from '.'; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts index aac36f3e4f573..45b26226def8f 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts @@ -32,6 +32,7 @@ export interface RichDetector { excludeFrequent: estypes.ExcludeFrequent | null; description: string | null; customRules: CustomRule[] | null; + useNull: boolean | null; } export class AdvancedJobCreator extends JobCreator { @@ -58,7 +59,8 @@ export class AdvancedJobCreator extends JobCreator { overField: SplitField, partitionField: SplitField, excludeFrequent: estypes.ExcludeFrequent | null, - description: string | null + description: string | null, + useNull: boolean | null ) { // addDetector doesn't support adding new custom rules. // this will be added in the future once it's supported in the UI @@ -71,7 +73,8 @@ export class AdvancedJobCreator extends JobCreator { partitionField, excludeFrequent, description, - customRules + customRules, + useNull ); this._addDetector(detector, agg, field); @@ -86,7 +89,8 @@ export class AdvancedJobCreator extends JobCreator { partitionField: SplitField, excludeFrequent: estypes.ExcludeFrequent | null, description: string | null, - index: number + index: number, + useNull: boolean | null ) { const customRules = this._detectors[index] !== undefined ? this._detectors[index].custom_rules || null : null; @@ -99,7 +103,8 @@ export class AdvancedJobCreator extends JobCreator { partitionField, excludeFrequent, description, - customRules + customRules, + useNull ); this._editDetector(detector, agg, field, index); @@ -117,7 +122,8 @@ export class AdvancedJobCreator extends JobCreator { partitionField: SplitField, excludeFrequent: estypes.ExcludeFrequent | null, description: string | null, - customRules: CustomRule[] | null + customRules: CustomRule[] | null, + useNull: boolean | null ): { detector: Detector; richDetector: RichDetector } { const detector: Detector = createBasicDetector(agg, field); @@ -139,6 +145,9 @@ export class AdvancedJobCreator extends JobCreator { if (customRules !== null) { detector.custom_rules = customRules; } + if (useNull !== null) { + detector.use_null = useNull; + } const richDetector: RichDetector = { agg, @@ -149,6 +158,7 @@ export class AdvancedJobCreator extends JobCreator { excludeFrequent, description, customRules, + useNull, }; return { detector, richDetector }; @@ -209,7 +219,8 @@ export class AdvancedJobCreator extends JobCreator { dtr.overField, dtr.partitionField, dtr.excludeFrequent, - dtr.description + dtr.description, + dtr.useNull ); } }); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/general.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/general.ts index 3f306f9bcc996..bab6800c08335 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/general.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/general.ts @@ -79,8 +79,9 @@ export function getRichDetectors( byField, overField, partitionField, - excludeFrequent: d.exclude_frequent || null, - description: d.detector_description || null, + excludeFrequent: d.exclude_frequent ?? null, + description: d.detector_description ?? null, + useNull: d.use_null ?? null, }; }); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx index d3108eef04983..2b1a35bcb8c46 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx @@ -177,6 +177,7 @@ export const AdvancedDetectorModal: FC = ({ : null, description: descriptionOption !== '' ? descriptionOption : null, customRules: null, + useNull: null, }; setDetector(dtr); setDescriptionPlaceholder(dtr); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_view/metric_selection.tsx index b4508af7803dd..8f53e1283faa0 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_view/metric_selection.tsx @@ -29,6 +29,7 @@ const emptyRichDetector: RichDetector = { excludeFrequent: null, description: null, customRules: null, + useNull: null, }; export const AdvancedDetectors: FC = ({ setIsValid }) => { @@ -51,7 +52,8 @@ export const AdvancedDetectors: FC = ({ setIsValid }) => { dtr.overField, dtr.partitionField, dtr.excludeFrequent, - dtr.description + dtr.description, + dtr.useNull ); } else { jobCreator.editDetector( @@ -62,7 +64,8 @@ export const AdvancedDetectors: FC = ({ setIsValid }) => { dtr.partitionField, dtr.excludeFrequent, dtr.description, - index + index, + dtr.useNull ); } jobCreatorUpdate(); diff --git a/x-pack/plugins/reporting/public/components/__snapshots__/report_listing.test.tsx.snap b/x-pack/plugins/reporting/public/components/__snapshots__/report_listing.test.tsx.snap index ddba7842f1199..670d16ec11548 100644 --- a/x-pack/plugins/reporting/public/components/__snapshots__/report_listing.test.tsx.snap +++ b/x-pack/plugins/reporting/public/components/__snapshots__/report_listing.test.tsx.snap @@ -52,6 +52,7 @@ Array [ "onSelectionChange": [Function], } } + tableCaption="Reports generated in Kibana applications" tableLayout="fixed" >
{ return ( ({ - v4: jest.fn().mockReturnValue('123'), -})); - -describe('add_remove_id_to_item', () => { - afterEach(() => { - jest.clearAllMocks(); - }); - - describe('addIdToItem', () => { - test('it adds an id to an empty item', () => { - expect(addIdToItem({})).toEqual({ id: '123' }); - }); - - test('it adds a complex object', () => { - expect( - addIdToItem({ - field: '', - type: 'mapping', - value: '', - }) - ).toEqual({ - id: '123', - field: '', - type: 'mapping', - value: '', - }); - }); - - test('it adds an id to an existing item', () => { - expect(addIdToItem({ test: '456' })).toEqual({ id: '123', test: '456' }); - }); - - test('it does not change the id if it already exists', () => { - expect(addIdToItem({ id: '456' })).toEqual({ id: '456' }); - }); - - test('it returns the same reference if it has an id already', () => { - const obj = { id: '456' }; - expect(addIdToItem(obj)).toBe(obj); - }); - - test('it returns a new reference if it adds an id to an item', () => { - const obj = { test: '456' }; - expect(addIdToItem(obj)).not.toBe(obj); - }); - }); - - describe('removeIdFromItem', () => { - test('it removes an id from an item', () => { - expect(removeIdFromItem({ id: '456' })).toEqual({}); - }); - - test('it returns a new reference if it removes an id from an item', () => { - const obj = { id: '123', test: '456' }; - expect(removeIdFromItem(obj)).not.toBe(obj); - }); - - test('it does not effect an item without an id', () => { - expect(removeIdFromItem({ test: '456' })).toEqual({ test: '456' }); - }); - - test('it returns the same reference if it does not have an id already', () => { - const obj = { test: '456' }; - expect(removeIdFromItem(obj)).toBe(obj); - }); - }); -}); diff --git a/x-pack/plugins/security_solution/common/add_remove_id_to_item.ts b/x-pack/plugins/security_solution/common/add_remove_id_to_item.ts deleted file mode 100644 index 1f35574038fd7..0000000000000 --- a/x-pack/plugins/security_solution/common/add_remove_id_to_item.ts +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import uuid from 'uuid'; - -/** - * This is useful for when you have arrays without an ID and need to add one for - * ReactJS keys. I break the types slightly by introducing an id to an arbitrary item - * but then cast it back to the regular type T. - * Usage of this could be considered tech debt as I am adding an ID when the backend - * could be doing the same thing but it depends on how you want to model your data and - * if you view modeling your data with id's to please ReactJS a good or bad thing. - * @param item The item to add an id to. - */ -type NotArray = T extends unknown[] ? never : T; -export const addIdToItem = (item: NotArray): T => { - const maybeId: typeof item & { id?: string } = item; - if (maybeId.id != null) { - return item; - } else { - return { ...item, id: uuid.v4() }; - } -}; - -/** - * This is to reverse the id you added to your arrays for ReactJS keys. - * @param item The item to remove the id from. - */ -export const removeIdFromItem = ( - item: NotArray -): - | T - | Pick< - T & { - id?: string | undefined; - }, - Exclude - > => { - const maybeId: typeof item & { id?: string } = item; - if (maybeId.id != null) { - const { id, ...noId } = maybeId; - return noId; - } else { - return item; - } -}; 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 e562d186bc424..7d24c1e157e40 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 @@ -5,6 +5,7 @@ * 2.0. */ +import { Language } from '@kbn/securitysolution-io-ts-alerting-types'; import { Filter, IIndexPattern, @@ -17,7 +18,7 @@ import { } from '../../../lists/common/schemas'; import { ESBoolQuery } from '../typed_json'; import { buildExceptionFilter } from '../shared_imports'; -import { Query, Language, Index, TimestampOverrideOrUndefined } from './schemas/common/schemas'; +import { Query, Index, TimestampOverrideOrUndefined } from './schemas/common/schemas'; export const getQueryFilter = ( query: Query, 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 e085d500bee0a..7b49b68ab79a1 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 @@ -8,21 +8,14 @@ /* eslint-disable @typescript-eslint/naming-convention */ import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; import { - SavedObjectAttributes, - SavedObjectAttribute, - SavedObjectAttributeSingle, -} from 'src/core/types'; -import { RiskScore } from '../types/risk_score'; -import { UUID } from '../types/uuid'; -import { IsoDateString } from '../types/iso_date_string'; -import { PositiveIntegerGreaterThanZero } from '../types/positive_integer_greater_than_zero'; -import { PositiveInteger } from '../types/positive_integer'; -import { NonEmptyString } from '../types/non_empty_string'; -import { parseScheduleDates } from '../../parse_schedule_dates'; -import { machine_learning_job_id_normalized } from '../types/normalized_ml_job_id'; + UUID, + NonEmptyString, + IsoDateString, + PositiveIntegerGreaterThanZero, + PositiveInteger, +} from '@kbn/securitysolution-io-ts-types'; export const author = t.array(t.string); export type Author = t.TypeOf; @@ -76,79 +69,6 @@ export type Filters = t.TypeOf; // Filters are not easily type-a export const filtersOrUndefined = t.union([filters, t.undefined]); export type FiltersOrUndefined = t.TypeOf; -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const saved_object_attribute_single: t.Type = t.recursion( - 'saved_object_attribute_single', - () => t.union([t.string, t.number, t.boolean, t.null, t.undefined, saved_object_attributes]) -); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const saved_object_attribute: t.Type = t.recursion( - 'saved_object_attribute', - () => t.union([saved_object_attribute_single, t.array(saved_object_attribute_single)]) -); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const saved_object_attributes: t.Type = t.recursion( - 'saved_object_attributes', - () => t.record(t.string, saved_object_attribute) -); - -/** - * Params is an "object", since it is a type of AlertActionParams which is action templates. - * @see x-pack/plugins/alerting/common/alert.ts - */ -export const action_group = t.string; -export const action_id = t.string; -export const action_action_type_id = t.string; -export const action_params = saved_object_attributes; -export const action = t.exact( - t.type({ - group: action_group, - id: action_id, - action_type_id: action_action_type_id, - params: action_params, - }) -); - -export const actions = t.array(action); -export type Actions = t.TypeOf; - -export const actionsCamel = t.array( - t.exact( - t.type({ - group: action_group, - id: action_id, - actionTypeId: action_action_type_id, - params: action_params, - }) - ) -); -export type ActionsCamel = t.TypeOf; - -const stringValidator = (input: unknown): input is string => typeof input === 'string'; -export const from = new t.Type( - 'From', - t.string.is, - (input, context): Either => { - if (stringValidator(input) && parseScheduleDates(input) == null) { - return t.failure(input, context, 'Failed to parse "from" on rule param'); - } - return t.string.validate(input, context); - }, - t.identity -); -export type From = t.TypeOf; - -export const fromOrUndefined = t.union([from, t.undefined]); -export type FromOrUndefined = t.TypeOf; - export const immutable = t.boolean; export type Immutable = t.TypeOf; @@ -183,26 +103,6 @@ export type Query = t.TypeOf; export const queryOrUndefined = t.union([query, t.undefined]); export type QueryOrUndefined = t.TypeOf; -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const language = t.keyof({ eql: null, kuery: null, lucene: null }); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type Language = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const languageOrUndefined = t.union([language, t.undefined]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type LanguageOrUndefined = t.TypeOf; - export const license = t.string; export type License = t.TypeOf; @@ -241,27 +141,12 @@ export type TimestampOverride = t.TypeOf; export const timestampOverrideOrUndefined = t.union([timestamp_override, t.undefined]); export type TimestampOverrideOrUndefined = t.TypeOf; -export const throttle = t.string; -export type Throttle = t.TypeOf; - -export const throttleOrNull = t.union([throttle, t.null]); -export type ThrottleOrNull = t.TypeOf; - -export const throttleOrNullOrUndefined = t.union([throttle, t.null, t.undefined]); -export type ThrottleOrUndefinedOrNull = t.TypeOf; - export const anomaly_threshold = PositiveInteger; export type AnomalyThreshold = t.TypeOf; export const anomalyThresholdOrUndefined = t.union([anomaly_threshold, t.undefined]); export type AnomalyThresholdOrUndefined = t.TypeOf; -export const machine_learning_job_id = t.union([t.string, machine_learning_job_id_normalized]); -export type MachineLearningJobId = t.TypeOf; - -export const machineLearningJobIdOrUndefined = t.union([machine_learning_job_id, t.undefined]); -export type MachineLearningJobIdOrUndefined = t.TypeOf; - /** * Note that this is a non-exact io-ts type as we allow extra meta information * to be added to the meta object @@ -271,158 +156,18 @@ export type Meta = t.TypeOf; export const metaOrUndefined = t.union([meta, t.undefined]); export type MetaOrUndefined = t.TypeOf; -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const max_signals = PositiveIntegerGreaterThanZero; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type MaxSignals = t.TypeOf; - -export const maxSignalsOrUndefined = t.union([max_signals, t.undefined]); -export type MaxSignalsOrUndefined = t.TypeOf; - export const name = NonEmptyString; export type Name = t.TypeOf; export const nameOrUndefined = t.union([name, t.undefined]); export type NameOrUndefined = t.TypeOf; -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const operator = t.keyof({ - equals: null, -}); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type Operator = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export enum OperatorEnum { - EQUALS = 'equals', -} - -export const risk_score = RiskScore; -export type RiskScore = t.TypeOf; - -export const riskScoreOrUndefined = t.union([risk_score, t.undefined]); -export type RiskScoreOrUndefined = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const risk_score_mapping_field = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const risk_score_mapping_value = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const risk_score_mapping_item = t.exact( - t.type({ - field: risk_score_mapping_field, - value: risk_score_mapping_value, - operator, - risk_score: riskScoreOrUndefined, - }) -); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const risk_score_mapping = t.array(risk_score_mapping_item); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type RiskScoreMapping = t.TypeOf; - -export const riskScoreMappingOrUndefined = t.union([risk_score_mapping, t.undefined]); -export type RiskScoreMappingOrUndefined = t.TypeOf; - export const rule_name_override = t.string; export type RuleNameOverride = t.TypeOf; export const ruleNameOverrideOrUndefined = t.union([rule_name_override, t.undefined]); export type RuleNameOverrideOrUndefined = t.TypeOf; -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const severity = t.keyof({ low: null, medium: null, high: null, critical: null }); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type Severity = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const severityOrUndefined = t.union([severity, t.undefined]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type SeverityOrUndefined = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const severity_mapping_field = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const severity_mapping_value = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const severity_mapping_item = t.exact( - t.type({ - field: severity_mapping_field, - operator, - value: severity_mapping_value, - severity, - }) -); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type SeverityMappingItem = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const severity_mapping = t.array(severity_mapping_item); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type SeverityMapping = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const severityMappingOrUndefined = t.union([severity_mapping, t.undefined]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type SeverityMappingOrUndefined = t.TypeOf; - export const status = t.keyof({ open: null, closed: null, 'in-progress': null }); export type Status = t.TypeOf; @@ -445,19 +190,6 @@ export type To = t.TypeOf; export const toOrUndefined = t.union([to, t.undefined]); export type ToOrUndefined = t.TypeOf; -export const type = t.keyof({ - eql: null, - machine_learning: null, - query: null, - saved_query: null, - threshold: null, - threat_match: null, -}); -export type Type = t.TypeOf; - -export const typeOrUndefined = t.union([type, t.undefined]); -export type TypeOrUndefined = t.TypeOf; - export const queryFilter = t.string; export type QueryFilter = t.TypeOf; @@ -511,152 +243,6 @@ export type Fields = t.TypeOf; export const fieldsOrUndefined = t.union([fields, t.undefined]); export type FieldsOrUndefined = t.TypeOf; -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_framework = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_tactic_id = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_tactic_name = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_tactic_reference = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_tactic = t.type({ - id: threat_tactic_id, - name: threat_tactic_name, - reference: threat_tactic_reference, -}); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatTactic = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_subtechnique_id = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_subtechnique_name = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_subtechnique_reference = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_subtechnique = t.type({ - id: threat_subtechnique_id, - name: threat_subtechnique_name, - reference: threat_subtechnique_reference, -}); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatSubtechnique = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_subtechniques = t.array(threat_subtechnique); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_technique_id = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_technique_name = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_technique_reference = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_technique = t.intersection([ - t.exact( - t.type({ - id: threat_technique_id, - name: threat_technique_name, - reference: threat_technique_reference, - }) - ), - t.exact( - t.partial({ - subtechnique: threat_subtechniques, - }) - ), -]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatTechnique = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_techniques = t.array(threat_technique); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat = t.intersection([ - t.exact( - t.type({ - framework: threat_framework, - tactic: threat_tactic, - }) - ), - t.exact( - t.partial({ - technique: threat_techniques, - }) - ), -]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type Threat = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threats = t.array(threat); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type Threats = t.TypeOf; - -export const threatsOrUndefined = t.union([threats, t.undefined]); -export type ThreatsOrUndefined = t.TypeOf; - export const thresholdField = t.exact( t.type({ field: t.union([t.string, t.array(t.string)]), // Covers pre- and post-7.12 @@ -707,43 +293,19 @@ export type ThresholdNormalized = t.TypeOf; export const thresholdNormalizedOrUndefined = t.union([thresholdNormalized, t.undefined]); export type ThresholdNormalizedOrUndefined = t.TypeOf; -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ export const created_at = IsoDateString; -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ export const updated_at = IsoDateString; -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ export const updated_by = t.string; -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ export const created_by = t.string; + export const updatedByOrNull = t.union([updated_by, t.null]); export type UpdatedByOrNull = t.TypeOf; export const createdByOrNull = t.union([created_by, t.null]); export type CreatedByOrNull = t.TypeOf; -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const version = PositiveIntegerGreaterThanZero; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type Version = t.TypeOf; - -export const versionOrUndefined = t.union([version, t.undefined]); -export type VersionOrUndefined = t.TypeOf; - export const last_success_at = IsoDateString; export type LastSuccessAt = t.TypeOf; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_schema.ts index 981a5422a0594..eed20951190b7 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_schema.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_schema.ts @@ -7,6 +7,44 @@ import * as t from 'io-ts'; +import { + Actions, + DefaultActionsArray, + DefaultFromString, + DefaultIntervalString, + DefaultMaxSignalsNumber, + DefaultRiskScoreMappingArray, + DefaultSeverityMappingArray, + DefaultThreatArray, + DefaultThrottleNull, + DefaultToString, + From, + RiskScoreMapping, + machine_learning_job_id, + risk_score, + threat_index, + concurrent_searches, + items_per_search, + threat_query, + threat_filters, + threat_mapping, + threat_language, + threat_indicator_path, + Threats, + type, + language, + severity, + SeverityMapping, + ThrottleOrNull, + MaxSignals, +} from '@kbn/securitysolution-io-ts-alerting-types'; +import { + version, + DefaultStringArray, + DefaultBooleanFalse, +} from '@kbn/securitysolution-io-ts-types'; + +import { DefaultListArray, ListArray } from '@kbn/securitysolution-io-ts-list-types'; import { description, anomaly_threshold, @@ -16,63 +54,24 @@ import { timeline_id, timeline_title, meta, - machine_learning_job_id, - risk_score, - MaxSignals, name, - severity, Tags, To, - type, - Threats, threshold, - ThrottleOrNull, note, References, - Actions, Enabled, FalsePositives, - From, Interval, - language, query, rule_id, - version, building_block_type, license, rule_name_override, timestamp_override, Author, - RiskScoreMapping, - SeverityMapping, event_category_override, } from '../common/schemas'; -import { - threat_index, - concurrent_searches, - items_per_search, - threat_query, - threat_filters, - threat_mapping, - threat_language, - threat_indicator_path, -} from '../types/threat_mapping'; - -import { - DefaultStringArray, - DefaultActionsArray, - DefaultBooleanFalse, - DefaultFromString, - DefaultIntervalString, - DefaultMaxSignalsNumber, - DefaultToString, - DefaultThreatArray, - DefaultThrottleNull, - DefaultListArray, - ListArray, - DefaultRiskScoreMappingArray, - DefaultSeverityMappingArray, -} from '../types'; /** * Big differences between this schema and the createRulesSchema 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 f3bef5ad7445f..03c0947aaf50c 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 @@ -11,9 +11,8 @@ import { AddPrepackagedRulesSchema, } from './add_prepackaged_rules_schema'; -import { exactCheck } from '../../../exact_check'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; import { pipe } from 'fp-ts/lib/pipeable'; -import { foldLeftRight, getPaths } from '../../../test_utils'; import { left } from 'fp-ts/lib/Either'; import { getAddPrepackagedRulesSchemaMock, diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_bulk_schema.test.ts index 9fe602bca8de4..e606e1f77fc2b 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_bulk_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_bulk_schema.test.ts @@ -6,9 +6,7 @@ */ import { createRulesBulkSchema, CreateRulesBulkSchema } from './create_rules_bulk_schema'; -import { exactCheck } from '../../../exact_check'; -import { foldLeftRight } from '../../../test_utils'; -import { formatErrors } from '../../../format_errors'; +import { exactCheck, foldLeftRight, formatErrors } from '@kbn/securitysolution-io-ts-utils'; import { getCreateRulesSchemaMock } from './rule_schemas.mock'; // only the basics of testing are here. diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_signals_migration_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_signals_migration_schema.ts index f522448102405..55267c27ee37f 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_signals_migration_schema.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_signals_migration_schema.ts @@ -7,8 +7,8 @@ import * as t from 'io-ts'; +import { PositiveInteger, PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-types'; import { index } from '../common/schemas'; -import { PositiveInteger, PositiveIntegerGreaterThanZero } from '../types'; export const signalsReindexOptions = t.partial({ requests_per_second: t.number, diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.test.ts index f9c2d38ea4da2..186f170ad700f 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.test.ts @@ -12,9 +12,8 @@ import { ExportRulesQuerySchema, ExportRulesQuerySchemaDecoded, } from './export_rules_schema'; -import { exactCheck } from '../../../exact_check'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; import { pipe } from 'fp-ts/lib/pipeable'; -import { foldLeftRight, getPaths } from '../../../test_utils'; import { left } from 'fp-ts/lib/Either'; describe('create rules schema', () => { diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.ts index 4dcb7351aebd6..a83e1c2c0f462 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.ts @@ -7,11 +7,10 @@ import * as t from 'io-ts'; +import { DefaultExportFileName } from '@kbn/securitysolution-io-ts-alerting-types'; +import { DefaultStringBooleanFalse } from '@kbn/securitysolution-io-ts-types'; import { rule_id, FileName, ExcludeExportDetails } from '../common/schemas'; -import { DefaultExportFileName } from '../types/default_export_file_name'; -import { DefaultStringBooleanFalse } from '../types/default_string_boolean_false'; - const objects = t.array(t.exact(t.type({ rule_id }))); export const exportRulesSchema = t.union([t.exact(t.type({ objects })), t.null]); export type ExportRulesSchema = t.TypeOf; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.test.ts index 923d54e1d6fa7..cd221c9f0a4b5 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.test.ts @@ -5,9 +5,8 @@ * 2.0. */ -import { exactCheck } from '../../../exact_check'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; import { pipe } from 'fp-ts/lib/pipeable'; -import { foldLeftRight, getPaths } from '../../../test_utils'; import { left } from 'fp-ts/lib/Either'; import { FindRulesSchema, findRulesSchema } from './find_rules_schema'; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.ts index 25c880290454c..b04afd14375cc 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.ts @@ -7,9 +7,8 @@ import * as t from 'io-ts'; +import { DefaultPerPage, DefaultPage } from '@kbn/securitysolution-io-ts-alerting-types'; import { queryFilter, fields, sort_field, sort_order, PerPage, Page } from '../common/schemas'; -import { DefaultPerPage } from '../types/default_per_page'; -import { DefaultPage } from '../types/default_page'; export const findRulesSchema = t.exact( t.partial({ diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/get_signals_migration_status_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/get_signals_migration_status_schema.ts index 9441cabf73bac..c0969768d8be6 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/get_signals_migration_status_schema.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/get_signals_migration_status_schema.ts @@ -7,7 +7,7 @@ import * as t from 'io-ts'; -import { from } from '../common/schemas'; +import { from } from '@kbn/securitysolution-io-ts-alerting-types'; export const getSignalsMigrationStatusSchema = t.exact( t.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 2caedd2e01193..1a937473c4b11 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 @@ -5,9 +5,8 @@ * 2.0. */ -import { exactCheck } from '../../../exact_check'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; import { pipe } from 'fp-ts/lib/pipeable'; -import { foldLeftRight, getPaths } from '../../../test_utils'; import { left } from 'fp-ts/lib/Either'; import { ImportRulesSchema, diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.ts index 8fa5809abe68b..70a7b8245f176 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.ts @@ -7,6 +7,47 @@ import * as t from 'io-ts'; +import { + Actions, + DefaultActionsArray, + DefaultFromString, + DefaultIntervalString, + DefaultMaxSignalsNumber, + DefaultRiskScoreMappingArray, + DefaultSeverityMappingArray, + DefaultThreatArray, + DefaultThrottleNull, + DefaultToString, + From, + machine_learning_job_id, + risk_score, + RiskScoreMapping, + threat_index, + items_per_search, + concurrent_searches, + threat_query, + threat_filters, + threat_mapping, + threat_language, + threat_indicator_path, + Threats, + type, + language, + severity, + SeverityMapping, + ThrottleOrNull, + MaxSignals, +} from '@kbn/securitysolution-io-ts-alerting-types'; + +import { + DefaultVersionNumber, + Version, + DefaultStringArray, + DefaultBooleanTrue, + OnlyFalseAllowed, + DefaultStringBooleanFalse, +} from '@kbn/securitysolution-io-ts-types'; +import { DefaultListArray, ListArray } from '@kbn/securitysolution-io-ts-list-types'; import { description, anomaly_threshold, @@ -18,26 +59,15 @@ import { timeline_id, timeline_title, meta, - machine_learning_job_id, - risk_score, - MaxSignals, name, - severity, Tags, To, - type, - Threats, threshold, - ThrottleOrNull, note, - Version, References, - Actions, Enabled, FalsePositives, - From, Interval, - language, query, rule_id, id, @@ -50,39 +80,8 @@ import { rule_name_override, timestamp_override, Author, - RiskScoreMapping, - SeverityMapping, event_category_override, } from '../common/schemas'; -import { - threat_index, - items_per_search, - concurrent_searches, - threat_query, - threat_filters, - threat_mapping, - threat_language, - threat_indicator_path, -} from '../types/threat_mapping'; - -import { - DefaultStringArray, - DefaultActionsArray, - DefaultBooleanTrue, - DefaultFromString, - DefaultIntervalString, - DefaultMaxSignalsNumber, - DefaultToString, - DefaultThreatArray, - DefaultThrottleNull, - DefaultVersionNumber, - OnlyFalseAllowed, - DefaultStringBooleanFalse, - DefaultListArray, - ListArray, - DefaultRiskScoreMappingArray, - DefaultSeverityMappingArray, -} from '../types'; /** * Differences from this and the createRulesSchema are diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_bulk_schema.test.ts index caa57525ab349..290f190562fe2 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_bulk_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_bulk_schema.test.ts @@ -6,9 +6,7 @@ */ import { patchRulesBulkSchema, PatchRulesBulkSchema } from './patch_rules_bulk_schema'; -import { exactCheck } from '../../../exact_check'; -import { foldLeftRight } from '../../../test_utils'; -import { formatErrors } from '../../../format_errors'; +import { exactCheck, formatErrors, foldLeftRight } from '@kbn/securitysolution-io-ts-utils'; import { PatchRulesSchema } from './patch_rules_schema'; // only the basics of testing are here. 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 3dfa12acc29d5..5ac49deb32e0d 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 @@ -7,9 +7,8 @@ import { patchRulesSchema, PatchRulesSchema, PatchRulesSchemaDecoded } from './patch_rules_schema'; import { getPatchRulesSchemaMock, getPatchRulesSchemaDecodedMock } from './patch_rules_schema.mock'; -import { exactCheck } from '../../../exact_check'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; import { pipe } from 'fp-ts/lib/pipeable'; -import { foldLeftRight, getPaths } from '../../../test_utils'; import { left } from 'fp-ts/lib/Either'; import { getListArrayMock } from '../types/lists.mock'; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.ts index 920fbaf4915c5..8c801e75af08c 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.ts @@ -7,6 +7,32 @@ import * as t from 'io-ts'; +import { + actions, + from, + machine_learning_job_id, + risk_score, + risk_score_mapping, + threat_index, + concurrent_searches, + items_per_search, + threat_query, + threat_filters, + threat_mapping, + threat_language, + threat_indicator_path, + threats, + type, + language, + severity, + severity_mapping, + max_signals, + throttle, +} from '@kbn/securitysolution-io-ts-alerting-types'; + +import { version } from '@kbn/securitysolution-io-ts-types'; + +import { listArrayOrUndefined } from '@kbn/securitysolution-io-ts-list-types'; import { description, anomaly_threshold, @@ -17,27 +43,16 @@ import { timeline_id, timeline_title, meta, - machine_learning_job_id, - risk_score, rule_id, name, - severity, - type, note, - version, - actions, false_positives, interval, - max_signals, - from, enabled, tags, - threats, threshold, - throttle, references, to, - language, query, id, building_block_type, @@ -45,21 +60,8 @@ import { license, rule_name_override, timestamp_override, - risk_score_mapping, - severity_mapping, event_category_override, } from '../common/schemas'; -import { - threat_index, - concurrent_searches, - items_per_search, - threat_query, - threat_filters, - threat_mapping, - threat_language, - threat_indicator_path, -} from '../types/threat_mapping'; -import { listArrayOrUndefined } from '../types/lists'; /** * All of the patch elements should default to undefined if not set diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_bulk_schema.test.ts index 5c1ded9a6ec50..fa167090b2f3a 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_bulk_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_bulk_schema.test.ts @@ -6,9 +6,7 @@ */ import { queryRulesBulkSchema, QueryRulesBulkSchema } from './query_rules_bulk_schema'; -import { exactCheck } from '../../../exact_check'; -import { foldLeftRight } from '../../../test_utils'; -import { formatErrors } from '../../../format_errors'; +import { exactCheck, formatErrors, foldLeftRight } from '@kbn/securitysolution-io-ts-utils'; // only the basics of testing are here. // see: query_rules_schema.test.ts for the bulk of the validation tests diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_schema.test.ts index 95c045b90f800..566d752a8623e 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_schema.test.ts @@ -6,9 +6,8 @@ */ import { queryRulesSchema, QueryRulesSchema } from './query_rules_schema'; -import { exactCheck } from '../../../exact_check'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; import { pipe } from 'fp-ts/lib/pipeable'; -import { foldLeftRight, getPaths } from '../../../test_utils'; import { left } from 'fp-ts/lib/Either'; describe('query_rules_schema', () => { diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.test.ts index ef7dfb9496ec3..65107079c5800 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.test.ts @@ -6,9 +6,8 @@ */ import { QuerySignalsSchema, querySignalsSchema } from './query_signals_index_schema'; -import { exactCheck } from '../../../exact_check'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; import { pipe } from 'fp-ts/lib/pipeable'; -import { foldLeftRight, getPaths } from '../../../test_utils'; import { left } from 'fp-ts/lib/Either'; describe('query, aggs, size, _source and track_total_hits on signals index', () => { diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.ts index d7f17fd842b9f..81761dd085df6 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.ts @@ -6,7 +6,7 @@ */ import * as t from 'io-ts'; -import { PositiveIntegerGreaterThanZero } from '../types/positive_integer_greater_than_zero'; +import { PositiveIntegerGreaterThanZero } from '@kbn/securitysolution-io-ts-types'; export const querySignalsSchema = t.exact( t.partial({ diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/rule_schemas.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/rule_schemas.test.ts index 70ff921d3b334..2e4a53766448b 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/rule_schemas.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/rule_schemas.test.ts @@ -6,9 +6,8 @@ */ import { createRulesSchema, CreateRulesSchema, SavedQueryCreateSchema } from './rule_schemas'; -import { exactCheck } from '../../../exact_check'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; import { pipe } from 'fp-ts/lib/pipeable'; -import { foldLeftRight, getPaths } from '../../../test_utils'; import { left } from 'fp-ts/lib/Either'; import { getCreateSavedQueryRulesSchemaMock, diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/rule_schemas.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/rule_schemas.ts index c7b33372e5953..dbc40763a0c6c 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/rule_schemas.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/rule_schemas.ts @@ -7,8 +7,12 @@ import * as t from 'io-ts'; -import { listArray } from '../types/lists'; import { + actions, + from, + risk_score, + machine_learning_job_id, + risk_score_mapping, threat_filters, threat_query, threat_mapping, @@ -16,14 +20,20 @@ import { threat_indicator_path, concurrent_searches, items_per_search, -} from '../types/threat_mapping'; + threats, + severity_mapping, + severity, + max_signals, + throttle, +} from '@kbn/securitysolution-io-ts-alerting-types'; +import { listArray } from '@kbn/securitysolution-io-ts-list-types'; +import { version } from '@kbn/securitysolution-io-ts-types'; + import { id, index, filters, event_category_override, - risk_score_mapping, - severity_mapping, building_block_type, note, license, @@ -35,25 +45,17 @@ import { author, description, false_positives, - from, rule_id, immutable, output_index, query, - machine_learning_job_id, - max_signals, - risk_score, - severity, - threats, to, references, - version, saved_id, threshold, anomaly_threshold, name, tags, - actions, interval, enabled, updated_at, @@ -66,7 +68,6 @@ import { last_success_message, last_failure_at, last_failure_message, - throttle, } from '../common/schemas'; const createSchema = < diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_schema.test.ts index c189821090f5d..994691ecfa571 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_schema.test.ts @@ -6,9 +6,8 @@ */ import { setSignalsStatusSchema, SetSignalsStatusSchema } from './set_signal_status_schema'; -import { exactCheck } from '../../../exact_check'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; import { pipe } from 'fp-ts/lib/pipeable'; -import { foldLeftRight, getPaths } from '../../../test_utils'; import { left } from 'fp-ts/lib/Either'; describe('set signal status schema', () => { diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_bulk_schema.test.ts index 3d0c579e3c46f..63217186affe7 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_bulk_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_bulk_schema.test.ts @@ -6,9 +6,7 @@ */ import { updateRulesBulkSchema, UpdateRulesBulkSchema } from './update_rules_bulk_schema'; -import { exactCheck } from '../../../exact_check'; -import { foldLeftRight } from '../../../test_utils'; -import { formatErrors } from '../../../format_errors'; +import { exactCheck, formatErrors, foldLeftRight } from '@kbn/securitysolution-io-ts-utils'; import { getUpdateRulesSchemaMock } from './rule_schemas.mock'; import { UpdateRulesSchema } from './rule_schemas'; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/error_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/error_schema.test.ts index a584c9254b171..5ef7f80a09a2d 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/error_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/error_schema.test.ts @@ -9,8 +9,7 @@ import { left } from 'fp-ts/lib/Either'; import { pipe } from 'fp-ts/lib/pipeable'; import { errorSchema, ErrorSchema } from './error_schema'; -import { exactCheck } from '../../../exact_check'; -import { foldLeftRight, getPaths } from '../../../test_utils'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; import { getErrorSchemaMock } from './error_schema.mocks'; describe('error_schema', () => { diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/import_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/import_rules_schema.test.ts index cb9876b0a165a..4c8cdbdd427af 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/import_rules_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/import_rules_schema.test.ts @@ -10,8 +10,7 @@ import { left, Either } from 'fp-ts/lib/Either'; import { ImportRulesSchema, importRulesSchema } from './import_rules_schema'; import { ErrorSchema } from './error_schema'; import { Errors } from 'io-ts'; -import { exactCheck } from '../../../exact_check'; -import { foldLeftRight, getPaths } from '../../../test_utils'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; describe('import_rules_schema', () => { test('it should validate an empty import response with no errors', () => { diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/prepackaged_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/prepackaged_rules_schema.test.ts index 67f3da8459410..fbbc754f597a0 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/prepackaged_rules_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/prepackaged_rules_schema.test.ts @@ -11,8 +11,7 @@ import { PrePackagedRulesAndTimelinesSchema, prePackagedRulesAndTimelinesSchema, } from './prepackaged_rules_schema'; -import { exactCheck } from '../../../exact_check'; -import { foldLeftRight, getPaths } from '../../../test_utils'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; describe('prepackaged_rules_schema', () => { test('it should validate an empty prepackaged response with defaults', () => { diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/prepackaged_rules_status_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/prepackaged_rules_status_schema.test.ts index 5a7b1dd14c341..de44c7e5e37ad 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/prepackaged_rules_status_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/prepackaged_rules_status_schema.test.ts @@ -11,8 +11,7 @@ import { PrePackagedRulesAndTimelinesStatusSchema, prePackagedRulesAndTimelinesStatusSchema, } from './prepackaged_rules_status_schema'; -import { exactCheck } from '../../../exact_check'; -import { foldLeftRight, getPaths } from '../../../test_utils'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; describe('prepackaged_rules_schema', () => { test('it should validate an empty prepackaged response with defaults', () => { diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/rules_bulk_schema.test.ts index 3501ecfc0c1ba..55d5444bccf7e 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/rules_bulk_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/rules_bulk_schema.test.ts @@ -11,8 +11,7 @@ import { pipe } from 'fp-ts/lib/pipeable'; import { RulesBulkSchema, rulesBulkSchema } from './rules_bulk_schema'; import { RulesSchema } from './rules_schema'; import { ErrorSchema } from './error_schema'; -import { exactCheck } from '../../../exact_check'; -import { foldLeftRight, getPaths } from '../../../test_utils'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; import { getRulesSchemaMock } from './rules_schema.mocks'; import { getErrorSchemaMock } from './error_schema.mocks'; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/rules_schema.test.ts index 4865c0ee77d54..a8521c013f451 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/rules_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/rules_schema.test.ts @@ -21,8 +21,7 @@ import { addThreatMatchFields, addEqlFields, } from './rules_schema'; -import { exactCheck } from '../../../exact_check'; -import { foldLeftRight, getPaths } from '../../../test_utils'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; import { TypeAndTimelineOnly } from './type_timeline_only_schema'; import { getRulesSchemaMock, @@ -30,7 +29,7 @@ import { getThreatMatchingSchemaMock, getRulesEqlSchemaMock, } from './rules_schema.mocks'; -import { ListArray } from '../types/lists'; +import { ListArray } from '@kbn/securitysolution-io-ts-list-types'; export const ANCHOR_DATE = '2020-02-20T03:57:54.037Z'; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/rules_schema.ts index 6bd54973e064f..0924588600d38 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/rules_schema.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/rules_schema.ts @@ -10,50 +10,64 @@ import { isObject } from 'lodash/fp'; import { Either, left, fold } from 'fp-ts/lib/Either'; import { pipe } from 'fp-ts/lib/pipeable'; +import { + actions, + from, + machine_learning_job_id, + risk_score, + DefaultRiskScoreMappingArray, + DefaultSeverityMappingArray, + threat_index, + concurrent_searches, + items_per_search, + threat_query, + threat_filters, + threat_mapping, + threat_language, + threat_indicator_path, + threats, + type, + language, + severity, + throttle, + max_signals, +} from '@kbn/securitysolution-io-ts-alerting-types'; +import { DefaultStringArray, version } from '@kbn/securitysolution-io-ts-types'; + +import { DefaultListArray } from '@kbn/securitysolution-io-ts-list-types'; import { isMlRule } from '../../../machine_learning/helpers'; import { isThresholdRule } from '../../utils'; import { - actions, anomaly_threshold, description, enabled, event_category_override, false_positives, - from, id, immutable, index, interval, rule_id, - language, name, output_index, - max_signals, - machine_learning_job_id, query, references, - severity, updated_by, tags, to, - risk_score, created_at, created_by, updated_at, saved_id, timeline_id, timeline_title, - type, - threats, threshold, - throttle, job_status, status_date, last_success_at, last_success_message, last_failure_at, last_failure_message, - version, filters, meta, note, @@ -62,23 +76,7 @@ import { rule_name_override, timestamp_override, } from '../common/schemas'; -import { - threat_index, - concurrent_searches, - items_per_search, - threat_query, - threat_filters, - threat_mapping, - threat_language, - threat_indicator_path, -} from '../types/threat_mapping'; -import { DefaultListArray } from '../types/lists_default_array'; -import { - DefaultStringArray, - DefaultRiskScoreMappingArray, - DefaultSeverityMappingArray, -} from '../types'; import { typeAndTimelineOnlySchema, TypeAndTimelineOnly } from './type_timeline_only_schema'; /** diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/type_timeline_only_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/type_timeline_only_schema.test.ts index 7099b03de58b1..58612376760ba 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/type_timeline_only_schema.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/type_timeline_only_schema.test.ts @@ -9,8 +9,7 @@ import { left } from 'fp-ts/lib/Either'; import { pipe } from 'fp-ts/lib/pipeable'; import { TypeAndTimelineOnly, typeAndTimelineOnlySchema } from './type_timeline_only_schema'; -import { exactCheck } from '../../../exact_check'; -import { foldLeftRight, getPaths } from '../../../test_utils'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; describe('prepackaged_rule_schema', () => { test('it should validate a a type and timeline_id together', () => { diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/type_timeline_only_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/type_timeline_only_schema.ts index 3aff1b62dfb90..b164ab9b44e4f 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/type_timeline_only_schema.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/type_timeline_only_schema.ts @@ -7,7 +7,8 @@ import * as t from 'io-ts'; -import { timeline_id, type } from '../common/schemas'; +import { type } from '@kbn/securitysolution-io-ts-alerting-types'; +import { timeline_id } from '../common/schemas'; /** * Special schema type that is only the type and the timeline_id. diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_boolean_true.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_boolean_true.test.ts deleted file mode 100644 index 14b4f034358cd..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_boolean_true.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultBooleanTrue } from './default_boolean_true'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_boolean_true', () => { - test('it should validate a boolean false', () => { - const payload = false; - const decoded = DefaultBooleanTrue.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate a boolean true', () => { - const payload = true; - const decoded = DefaultBooleanTrue.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a number', () => { - const payload = 5; - const decoded = DefaultBooleanTrue.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultBooleanTrue"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default true', () => { - const payload = null; - const decoded = DefaultBooleanTrue.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(true); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_from_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_from_string.test.ts deleted file mode 100644 index ca3ecb2bfb904..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_from_string.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultFromString } from './default_from_string'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_from_string', () => { - test('it should validate a from string', () => { - const payload = 'now-20m'; - const decoded = DefaultFromString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a number', () => { - const payload = 5; - const decoded = DefaultFromString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultFromString"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default of "now-6m"', () => { - const payload = null; - const decoded = DefaultFromString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual('now-6m'); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.test.ts deleted file mode 100644 index 993e96f5d3191..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultActionsArray } from './default_actions_array'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; -import { Actions } from '../common/schemas'; - -describe('default_actions_array', () => { - test('it should validate an empty array', () => { - const payload: string[] = []; - const decoded = DefaultActionsArray.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 actions', () => { - const payload: Actions = [ - { id: '123', group: 'group', action_type_id: 'action_type_id', params: {} }, - ]; - const decoded = DefaultActionsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate an array with a number', () => { - const payload = [ - { id: '123', group: 'group', action_type_id: 'action_type_id', params: {} }, - 5, - ]; - const decoded = DefaultActionsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultActionsArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default array entry', () => { - const payload = null; - const decoded = DefaultActionsArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.ts deleted file mode 100644 index 49302102ddee9..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { actions, Actions } from '../common/schemas'; - -/** - * Types the DefaultStringArray as: - * - If undefined, then a default action array will be set - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultActionsArray = new t.Type( - 'DefaultActionsArray', - actions.is, - (input, context): Either => - input == null ? t.success([]) : actions.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_array.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_array.test.ts deleted file mode 100644 index 92c2669071f11..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_array.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; - -import { DefaultArray } from './default_array'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -const testSchema = t.keyof({ - valid: true, - also_valid: true, -}); -type TestSchema = t.TypeOf; - -const defaultArraySchema = DefaultArray(testSchema); - -describe('default_array', () => { - test('it should validate an empty array', () => { - const payload: string[] = []; - const decoded = defaultArraySchema.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 testSchema', () => { - const payload: TestSchema[] = ['valid']; - const decoded = defaultArraySchema.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 valid testSchema strings', () => { - const payload = ['valid', 'also_valid']; - const decoded = defaultArraySchema.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate an array with a number', () => { - const payload = ['valid', 123]; - const decoded = defaultArraySchema.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "123" supplied to "DefaultArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate an array with an invalid string', () => { - const payload = ['valid', 'invalid']; - const decoded = defaultArraySchema.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "invalid" supplied to "DefaultArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default array entry', () => { - const payload = null; - const decoded = defaultArraySchema.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_array.ts deleted file mode 100644 index a6397754b23d7..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_array.ts +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the DefaultArray as: - * - If undefined, then a default array will be set - * - If an array is sent in, then the array will be validated to ensure all elements are type C - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultArray = (codec: C) => { - const arrType = t.array(codec); - type ArrType = t.TypeOf; - return new t.Type( - 'DefaultArray', - arrType.is, - (input, context): Either => - input == null ? t.success([]) : arrType.validate(input, context), - t.identity - ); -}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.test.ts deleted file mode 100644 index c01efa6e55d4c..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultBooleanFalse } from './default_boolean_false'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_boolean_false', () => { - test('it should validate a boolean false', () => { - const payload = false; - const decoded = DefaultBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate a boolean true', () => { - const payload = true; - const decoded = DefaultBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a number', () => { - const payload = 5; - const decoded = DefaultBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultBooleanFalse"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default false', () => { - const payload = null; - const decoded = DefaultBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(false); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.ts deleted file mode 100644 index 46e7bde55638a..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the DefaultBooleanFalse as: - * - If null or undefined, then a default false will be set - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultBooleanFalse = new t.Type( - 'DefaultBooleanFalse', - t.boolean.is, - (input, context): Either => - input == null ? t.success(false) : t.boolean.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_true.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_true.ts deleted file mode 100644 index 3845150841c22..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_true.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the DefaultBooleanTrue as: - * - If null or undefined, then a default true will be set - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultBooleanTrue = new t.Type( - 'DefaultBooleanTrue', - t.boolean.is, - (input, context): Either => - input == null ? t.success(true) : t.boolean.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.test.ts deleted file mode 100644 index 08a5354dc74bd..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultEmptyString } from './default_empty_string'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_empty_string', () => { - test('it should validate a regular string', () => { - const payload = 'some string'; - const decoded = DefaultEmptyString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a number', () => { - const payload = 5; - const decoded = DefaultEmptyString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultEmptyString"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default of ""', () => { - const payload = null; - const decoded = DefaultEmptyString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(''); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.ts deleted file mode 100644 index 77a06a928a2e3..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the DefaultEmptyString as: - * - If null or undefined, then a default of an empty string "" will be used - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultEmptyString = new t.Type( - 'DefaultEmptyString', - t.string.is, - (input, context): Either => - input == null ? t.success('') : t.string.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.test.ts deleted file mode 100644 index f53c6d801dc53..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultExportFileName } from './default_export_file_name'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_export_file_name', () => { - test('it should validate a regular string', () => { - const payload = 'some string'; - const decoded = DefaultExportFileName.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a number', () => { - const payload = 5; - const decoded = DefaultExportFileName.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultExportFileName"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default of "export.ndjson"', () => { - const payload = null; - const decoded = DefaultExportFileName.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual('export.ndjson'); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.ts deleted file mode 100644 index a2b2fb6eaad31..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the DefaultExportFileName as: - * - If null or undefined, then a default of "export.ndjson" will be used - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultExportFileName = new t.Type( - 'DefaultExportFileName', - t.string.is, - (input, context): Either => - input == null ? t.success('export.ndjson') : t.string.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_from_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_from_string.ts deleted file mode 100644 index a2eb2a2b9f46f..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_from_string.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { from } from '../common/schemas'; -/** - * Types the DefaultFromString as: - * - If null or undefined, then a default of the string "now-6m" will be used - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultFromString = new t.Type( - 'DefaultFromString', - t.string.is, - (input, context): Either => { - if (input == null) { - return t.success('now-6m'); - } - return from.validate(input, context); - }, - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.test.ts deleted file mode 100644 index 99e15403ef3a2..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultIntervalString } from './default_interval_string'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_interval_string', () => { - test('it should validate a interval string', () => { - const payload = '20m'; - const decoded = DefaultIntervalString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a number', () => { - const payload = 5; - const decoded = DefaultIntervalString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultIntervalString"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default of "5m"', () => { - const payload = null; - const decoded = DefaultIntervalString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual('5m'); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.ts deleted file mode 100644 index fb3a5931199a1..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the DefaultIntervalString as: - * - If null or undefined, then a default of the string "5m" will be used - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultIntervalString = new t.Type( - 'DefaultIntervalString', - t.string.is, - (input, context): Either => - input == null ? t.success('5m') : t.string.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.test.ts deleted file mode 100644 index 615f27e08b197..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultLanguageString } from './default_language_string'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; -import { Language } from '../common/schemas'; - -describe('default_language_string', () => { - test('it should validate a string', () => { - const payload: Language = 'lucene'; - const decoded = DefaultLanguageString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a number', () => { - const payload = 5; - const decoded = DefaultLanguageString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultLanguageString"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default of "kuery"', () => { - const payload = null; - const decoded = DefaultLanguageString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual('kuery'); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.ts deleted file mode 100644 index a40b0d8eeacaa..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { language } from '../common/schemas'; - -/** - * Types the DefaultLanguageString as: - * - If null or undefined, then a default of the string "kuery" will be used - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultLanguageString = new t.Type( - 'DefaultLanguageString', - t.string.is, - (input, context): Either => - input == null ? t.success('kuery') : language.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.test.ts deleted file mode 100644 index bdfdc15150b9a..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultMaxSignalsNumber } from './default_max_signals_number'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; -import { DEFAULT_MAX_SIGNALS } from '../../../constants'; - -describe('default_from_string', () => { - test('it should validate a max signal number', () => { - const payload = 5; - const decoded = DefaultMaxSignalsNumber.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a string', () => { - const payload = '5'; - const decoded = DefaultMaxSignalsNumber.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultMaxSignals"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate a zero', () => { - const payload = 0; - const decoded = DefaultMaxSignalsNumber.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "0" supplied to "DefaultMaxSignals"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate a negative number', () => { - const payload = -1; - const decoded = DefaultMaxSignalsNumber.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "-1" supplied to "DefaultMaxSignals"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default of DEFAULT_MAX_SIGNALS', () => { - const payload = null; - const decoded = DefaultMaxSignalsNumber.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(DEFAULT_MAX_SIGNALS); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.ts deleted file mode 100644 index d9209cdba4d00..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.ts +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { max_signals } from '../common/schemas'; -import { DEFAULT_MAX_SIGNALS } from '../../../constants'; - -/** - * Types the default max signal: - * - Natural Number (positive integer and not a float), - * - greater than 1 - * - If undefined then it will use DEFAULT_MAX_SIGNALS (100) as the default - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultMaxSignalsNumber = new t.Type( - 'DefaultMaxSignals', - t.number.is, - (input, context): Either => { - return input == null ? t.success(DEFAULT_MAX_SIGNALS) : max_signals.validate(input, context); - }, - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.test.ts deleted file mode 100644 index 9392454127586..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultPage } from './default_page'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_page', () => { - test('it should validate a regular number greater than zero', () => { - const payload = 5; - const decoded = DefaultPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate a string of a number', () => { - const payload = '5'; - const decoded = DefaultPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(5); - }); - - test('it should not validate a junk string', () => { - const payload = 'invalid-string'; - const decoded = DefaultPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "NaN" supplied to "DefaultPerPage"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate an empty string', () => { - const payload = ''; - const decoded = DefaultPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "NaN" supplied to "DefaultPerPage"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate a zero', () => { - const payload = 0; - const decoded = DefaultPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "0" supplied to "DefaultPerPage"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate a negative number', () => { - const payload = -1; - const decoded = DefaultPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "-1" supplied to "DefaultPerPage"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default of 20', () => { - const payload = null; - const decoded = DefaultPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(1); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.ts deleted file mode 100644 index 2f2cdaf3b6cd2..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.ts +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { PositiveIntegerGreaterThanZero } from './positive_integer_greater_than_zero'; - -/** - * Types the DefaultPerPage as: - * - If a string this will convert the string to a number - * - If null or undefined, then a default of 1 will be used - * - If the number is 0 or less this will not validate as it has to be a positive number greater than zero - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultPage = new t.Type( - 'DefaultPerPage', - t.number.is, - (input, context): Either => { - if (input == null) { - return t.success(1); - } else if (typeof input === 'string') { - return PositiveIntegerGreaterThanZero.validate(parseInt(input, 10), context); - } else { - return PositiveIntegerGreaterThanZero.validate(input, context); - } - }, - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.test.ts deleted file mode 100644 index 5a550dca120e8..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultPerPage } from './default_per_page'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_per_page', () => { - test('it should validate a regular number greater than zero', () => { - const payload = 5; - const decoded = DefaultPerPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate a string of a number', () => { - const payload = '5'; - const decoded = DefaultPerPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(5); - }); - - test('it should not validate a junk string', () => { - const payload = 'invalid-string'; - const decoded = DefaultPerPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "NaN" supplied to "DefaultPerPage"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate an empty string', () => { - const payload = ''; - const decoded = DefaultPerPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "NaN" supplied to "DefaultPerPage"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate a zero', () => { - const payload = 0; - const decoded = DefaultPerPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "0" supplied to "DefaultPerPage"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate a negative number', () => { - const payload = -1; - const decoded = DefaultPerPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "-1" supplied to "DefaultPerPage"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default of 20', () => { - const payload = null; - const decoded = DefaultPerPage.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(20); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.ts deleted file mode 100644 index 124fdf25917fa..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.ts +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { PositiveIntegerGreaterThanZero } from './positive_integer_greater_than_zero'; - -/** - * Types the DefaultPerPage as: - * - If a string this will convert the string to a number - * - If null or undefined, then a default of 20 will be used - * - If the number is 0 or less this will not validate as it has to be a positive number greater than zero - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultPerPage = new t.Type( - 'DefaultPerPage', - t.number.is, - (input, context): Either => { - if (input == null) { - return t.success(20); - } else if (typeof input === 'string') { - return PositiveIntegerGreaterThanZero.validate(parseInt(input, 10), context); - } else { - return PositiveIntegerGreaterThanZero.validate(input, context); - } - }, - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_risk_score_mapping_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_risk_score_mapping_array.ts deleted file mode 100644 index 219b9d30b52ea..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_risk_score_mapping_array.ts +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { risk_score_mapping, RiskScoreMapping } from '../common/schemas'; - -/** - * Types the DefaultStringArray as: - * - If null or undefined, then a default risk_score_mapping array will be set - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultRiskScoreMappingArray = new t.Type< - RiskScoreMapping, - RiskScoreMapping | undefined, - unknown ->( - 'DefaultRiskScoreMappingArray', - risk_score_mapping.is, - (input, context): Either => - input == null ? t.success([]) : risk_score_mapping.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_severity_mapping_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_severity_mapping_array.ts deleted file mode 100644 index fe65574383294..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_severity_mapping_array.ts +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { severity_mapping, SeverityMapping } from '../common/schemas'; - -/** - * Types the DefaultStringArray as: - * - If null or undefined, then a default severity_mapping array will be set - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultSeverityMappingArray = new t.Type< - SeverityMapping, - SeverityMapping | undefined, - unknown ->( - 'DefaultSeverityMappingArray', - severity_mapping.is, - (input, context): Either => - input == null ? t.success([]) : severity_mapping.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.test.ts deleted file mode 100644 index c8995f6a7cef0..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultStringArray } from './default_string_array'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_string_array', () => { - test('it should validate an empty array', () => { - const payload: string[] = []; - const decoded = DefaultStringArray.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 strings', () => { - const payload = ['value 1', 'value 2']; - const decoded = DefaultStringArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate an array with a number', () => { - const payload = ['value 1', 5]; - const decoded = DefaultStringArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultStringArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default array entry', () => { - const payload = null; - const decoded = DefaultStringArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.ts deleted file mode 100644 index be4b5563ddb13..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the DefaultStringArray as: - * - If undefined, then a default array will be set - * - If an array is sent in, then the array will be validated to ensure all elements are a string - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultStringArray = new t.Type( - 'DefaultStringArray', - t.array(t.string).is, - (input, context): Either => - input == null ? t.success([]) : t.array(t.string).validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.test.ts deleted file mode 100644 index 2ee3e87e37e00..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; -import { DefaultStringBooleanFalse } from './default_string_boolean_false'; - -describe('default_string_boolean_false', () => { - test('it should validate a boolean false', () => { - const payload = false; - const decoded = DefaultStringBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate a boolean true', () => { - const payload = true; - const decoded = DefaultStringBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a number', () => { - const payload = 5; - const decoded = DefaultStringBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultStringBooleanFalse"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default false', () => { - const payload = null; - const decoded = DefaultStringBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(false); - }); - - test('it should return a default false when given a string of "false"', () => { - const payload = 'false'; - const decoded = DefaultStringBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(false); - }); - - test('it should return a default true when given a string of "true"', () => { - const payload = 'true'; - const decoded = DefaultStringBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(true); - }); - - test('it should return a default true when given a string of "TruE"', () => { - const payload = 'TruE'; - const decoded = DefaultStringBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(true); - }); - - test('it should not work with a string of junk "junk"', () => { - const payload = 'junk'; - const decoded = DefaultStringBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "junk" supplied to "DefaultStringBooleanFalse"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not work with an empty string', () => { - const payload = ''; - const decoded = DefaultStringBooleanFalse.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "" supplied to "DefaultStringBooleanFalse"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.ts deleted file mode 100644 index 69bd4564fd3bb..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.ts +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the DefaultStringBooleanFalse as: - * - If a string this will convert the string to a boolean - * - If null or undefined, then a default false will be set - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultStringBooleanFalse = new t.Type( - 'DefaultStringBooleanFalse', - t.boolean.is, - (input, context): Either => { - if (input == null) { - return t.success(false); - } else if (typeof input === 'string' && input.toLowerCase() === 'true') { - return t.success(true); - } else if (typeof input === 'string' && input.toLowerCase() === 'false') { - return t.success(false); - } else { - return t.boolean.validate(input, context); - } - }, - t.identity -); - -export type DefaultStringBooleanFalseC = typeof DefaultStringBooleanFalse; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.test.ts deleted file mode 100644 index d04338586371f..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultThreatArray } from './default_threat_array'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; -import { Threats } from '../common/schemas'; - -describe('default_threat_null', () => { - test('it should validate an empty array', () => { - const payload: Threats = []; - const decoded = DefaultThreatArray.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 threats', () => { - const payload: Threats = [ - { - framework: 'MITRE ATTACK', - technique: [{ reference: 'https://test.com', name: 'Audio Capture', id: 'T1123' }], - tactic: { reference: 'https://test.com', name: 'Collection', id: 'TA000999' }, - }, - ]; - const decoded = DefaultThreatArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate an array with a number', () => { - const payload = [ - { - framework: 'MITRE ATTACK', - technique: [{ reference: 'https://test.com', name: 'Audio Capture', id: 'T1123' }], - tactic: { reference: 'https://test.com', name: 'Collection', id: 'TA000999' }, - }, - 5, - ]; - const decoded = DefaultThreatArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultThreatArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default empty array if not provided a value', () => { - const payload = null; - const decoded = DefaultThreatArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.ts deleted file mode 100644 index 86c7ab245d6f3..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { Threats, threats } from '../common/schemas'; - -/** - * Types the DefaultThreatArray as: - * - If null or undefined, then an empty array will be set - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultThreatArray = new t.Type( - 'DefaultThreatArray', - threats.is, - (input, context): Either => - input == null ? t.success([]) : threats.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.test.ts deleted file mode 100644 index 1f29718533c13..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultThrottleNull } from './default_throttle_null'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; -import { Throttle } from '../common/schemas'; - -describe('default_throttle_null', () => { - test('it should validate a throttle string', () => { - const payload: Throttle = 'some string'; - const decoded = DefaultThrottleNull.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate an array with a number', () => { - const payload = 5; - const decoded = DefaultThrottleNull.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultThreatNull"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default "null" if not provided a value', () => { - const payload = undefined; - const decoded = DefaultThrottleNull.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(null); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.ts deleted file mode 100644 index db6eb5eab32ae..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { ThrottleOrNull, throttle } from '../common/schemas'; - -/** - * Types the DefaultThrottleNull as: - * - If null or undefined, then a null will be set - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultThrottleNull = new t.Type( - 'DefaultThreatNull', - throttle.is, - (input, context): Either => - input == null ? t.success(null) : throttle.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.test.ts deleted file mode 100644 index defb348b7e009..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultToString } from './default_to_string'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_to_string', () => { - test('it should validate a to string', () => { - const payload = 'now-5m'; - const decoded = DefaultToString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a number', () => { - const payload = 5; - const decoded = DefaultToString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultToString"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default of "now"', () => { - const payload = null; - const decoded = DefaultToString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual('now'); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.ts deleted file mode 100644 index 05c93951bfe1e..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the DefaultToString as: - * - If null or undefined, then a default of the string "now" will be used - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultToString = new t.Type( - 'DefaultToString', - t.string.is, - (input, context): Either => - input == null ? t.success('now') : t.string.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.test.ts deleted file mode 100644 index e2b2ac5015967..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultUuid } from './default_uuid'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_uuid', () => { - test('it should validate a regular string', () => { - const payload = '1'; - const decoded = DefaultUuid.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a number', () => { - const payload = 5; - const decoded = DefaultUuid.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to "DefaultUuid"']); - expect(message.schema).toEqual({}); - }); - - test('it should return a default of a uuid', () => { - const payload = null; - const decoded = DefaultUuid.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toMatch( - /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i - ); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.ts deleted file mode 100644 index ecb8cd00ff308..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import uuid from 'uuid'; - -import { NonEmptyString } from './non_empty_string'; - -/** - * Types the DefaultUuid as: - * - If null or undefined, then a default string uuid.v4() will be - * created otherwise it will be checked just against an empty string - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultUuid = new t.Type( - 'DefaultUuid', - t.string.is, - (input, context): Either => - input == null ? t.success(uuid.v4()) : NonEmptyString.validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.test.ts deleted file mode 100644 index a50a9ed7815b3..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultVersionNumber } from './default_version_number'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_version_number', () => { - test('it should validate a version number', () => { - const payload = 5; - const decoded = DefaultVersionNumber.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a 0', () => { - const payload = 0; - const decoded = DefaultVersionNumber.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "0" supplied to "DefaultVersionNumber"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate a -1', () => { - const payload = -1; - const decoded = DefaultVersionNumber.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "-1" supplied to "DefaultVersionNumber"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate a string', () => { - const payload = '5'; - const decoded = DefaultVersionNumber.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultVersionNumber"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default of 1', () => { - const payload = null; - const decoded = DefaultVersionNumber.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(1); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.ts deleted file mode 100644 index 625973694a244..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.ts +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; -import { version, Version } from '../common/schemas'; - -/** - * Types the DefaultVersionNumber as: - * - If null or undefined, then a default of the number 1 will be used - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultVersionNumber = new t.Type( - 'DefaultVersionNumber', - version.is, - (input, context): Either => - input == null ? t.success(1) : version.validate(input, context), - t.identity -); - -export type DefaultVersionNumberDecoded = t.TypeOf; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/index.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/index.ts deleted file mode 100644 index ff69075580ad9..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/index.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export * from './default_actions_array'; -export * from './default_array'; -export * from './default_boolean_false'; -export * from './default_boolean_true'; -export * from './default_empty_string'; -export * from './default_export_file_name'; -export * from './default_from_string'; -export * from './default_interval_string'; -export * from './default_language_string'; -export * from './default_max_signals_number'; -export * from './default_page'; -export * from './default_per_page'; -export * from './default_risk_score_mapping_array'; -export * from './default_severity_mapping_array'; -export * from './default_string_array'; -export * from './default_string_boolean_false'; -export * from './default_threat_array'; -export * from './default_throttle_null'; -export * from './default_to_string'; -export * from './default_uuid'; -export * from './default_version_number'; -export * from './iso_date_string'; -export * from './lists'; -export * from './lists_default_array'; -export * from './non_empty_array'; -export * from './non_empty_string'; -export * from './only_false_allowed'; -export * from './positive_integer'; -export * from './positive_integer_greater_than_zero'; -export * from './references_default_array'; -export * from './risk_score'; -export * from './threat_mapping'; -export * from './uuid'; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/iso_date_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/iso_date_string.test.ts deleted file mode 100644 index ff45aef21f837..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/iso_date_string.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { IsoDateString } from './iso_date_string'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('ios_date_string', () => { - test('it should validate a iso string', () => { - const payload = '2020-02-26T00:32:34.541Z'; - const decoded = IsoDateString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate an epoch number', () => { - const payload = '1582677283067'; - const decoded = IsoDateString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1582677283067" supplied to "IsoDateString"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate a number such as 2000', () => { - const payload = '2000'; - const decoded = IsoDateString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "2000" supplied to "IsoDateString"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate a UTC', () => { - const payload = 'Wed, 26 Feb 2020 00:36:20 GMT'; - const decoded = IsoDateString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "Wed, 26 Feb 2020 00:36:20 GMT" supplied to "IsoDateString"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/iso_date_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/iso_date_string.ts deleted file mode 100644 index 9c8f490d2d59a..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/iso_date_string.ts +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the IsoDateString as: - * - A string that is an ISOString - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const IsoDateString = new t.Type( - 'IsoDateString', - t.string.is, - (input, context): Either => { - if (typeof input === 'string') { - try { - const parsed = new Date(input); - if (parsed.toISOString() === input) { - return t.success(input); - } else { - return t.failure(input, context); - } - } catch (err) { - return t.failure(input, context); - } - } else { - return t.failure(input, context); - } - }, - t.identity -); - -export type IsoDateStringC = typeof IsoDateString; 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 62a3c51b31bd0..70f41539e8466 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 @@ -5,7 +5,7 @@ * 2.0. */ -import { List, ListArray } from './lists'; +import { List, ListArray } from '@kbn/securitysolution-io-ts-list-types'; import { ENDPOINT_LIST_ID } from '../../../shared_imports'; export const getListMock = (): List => ({ 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 deleted file mode 100644 index 28b70f51742a7..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; - -import { foldLeftRight, getPaths } from '../../../test_utils'; - -import { getEndpointListMock, getListMock, getListArrayMock } from './lists.mock'; -import { - List, - ListArray, - ListArrayOrUndefined, - list, - listArray, - listArrayOrUndefined, -} from './lists'; - -describe('Lists', () => { - describe('list', () => { - test('it should validate a list', () => { - const payload = getListMock(); - const decoded = list.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate a list with "namespace_type" of "agnostic"', () => { - const payload = getEndpointListMock(); - const decoded = list.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should NOT validate a list without an "id"', () => { - const payload = getListMock(); - // @ts-expect-error - delete payload.id; - const decoded = list.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 should NOT validate a list without "namespace_type"', () => { - const payload = getListMock(); - // @ts-expect-error - delete payload.namespace_type; - const decoded = list.decode(payload); - const message = pipe(decoded, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "undefined" supplied to "namespace_type"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should strip out extra keys', () => { - const payload: List & { - extraKey?: string; - } = getListMock(); - payload.extraKey = 'some value'; - const decoded = list.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(getListMock()); - }); - }); - - describe('listArray', () => { - test('it should validate an array of lists', () => { - const payload = getListArrayMock(); - const decoded = listArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate when unexpected type found in array', () => { - const payload = ([1] as unknown) as ListArray; - const decoded = listArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "Array<{| id: NonEmptyString, list_id: NonEmptyString, type: "detection" | "endpoint" | "endpoint_events", namespace_type: "agnostic" | "single" |}>"', - ]); - expect(message.schema).toEqual({}); - }); - }); - - describe('listArrayOrUndefined', () => { - test('it should validate an array of lists', () => { - const payload = getListArrayMock(); - const decoded = listArrayOrUndefined.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 = listArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not allow an item that is not of type "list" in array', () => { - const payload = ([1] as unknown) as ListArrayOrUndefined; - const decoded = listArrayOrUndefined.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "(Array<{| id: NonEmptyString, list_id: NonEmptyString, type: "detection" | "endpoint" | "endpoint_events", namespace_type: "agnostic" | "single" |}> | undefined)"', - 'Invalid value "[1]" supplied to "(Array<{| id: NonEmptyString, list_id: NonEmptyString, type: "detection" | "endpoint" | "endpoint_events", 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 deleted file mode 100644 index e2c3ee88f6a65..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.ts +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; - -import { exceptionListType, namespaceType } from '@kbn/securitysolution-io-ts-list-types'; - -import { NonEmptyString } from './non_empty_string'; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const list = t.exact( - t.type({ - id: NonEmptyString, - list_id: NonEmptyString, - type: exceptionListType, - namespace_type: namespaceType, - }) -); - -export type List = t.TypeOf; -export const listArray = t.array(list); -export type ListArray = t.TypeOf; -export const listArrayOrUndefined = t.union([listArray, t.undefined]); -export type ListArrayOrUndefined = t.TypeOf; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists_default_array.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists_default_array.test.ts deleted file mode 100644 index 0d989b4de0b28..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists_default_array.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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; - -import { foldLeftRight, getPaths } from '../../../test_utils'; - -import { DefaultListArray } from './lists_default_array'; -import { getListArrayMock } from './lists.mock'; - -describe('lists_default_array', () => { - test('it should return a default array when null', () => { - const payload = null; - const decoded = DefaultListArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); - - test('it should return a default array when undefined', () => { - const payload = undefined; - const decoded = DefaultListArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); - - test('it should validate an empty array', () => { - const payload: string[] = []; - const decoded = DefaultListArray.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 lists', () => { - const payload = getListArrayMock(); - const decoded = DefaultListArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate an array of non accepted types', () => { - // Terrible casting for purpose of tests - const payload = [1] as unknown; - const decoded = DefaultListArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "1" supplied to "DefaultListArray"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists_default_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists_default_array.ts deleted file mode 100644 index eba48c0419ec2..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists_default_array.ts +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -import { ListArray, list } from './lists'; - -/** - * Types the DefaultListArray as: - * - If null or undefined, then a default array of type list will be set - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const DefaultListArray = new t.Type( - 'DefaultListArray', - t.array(list).is, - (input, context): Either => - input == null ? t.success([]) : t.array(list).validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_array.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_array.test.ts deleted file mode 100644 index c08cb70f544ee..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_array.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; - -import { NonEmptyArray } from './non_empty_array'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -const testSchema = t.keyof({ - valid: true, - also_valid: true, -}); -type TestSchema = t.TypeOf; - -const nonEmptyArraySchema = NonEmptyArray(testSchema, 'TestSchemaArray'); - -describe('non empty array', () => { - test('it should generate the correct name for non empty array', () => { - const newTestSchema = NonEmptyArray(testSchema); - expect(newTestSchema.name).toEqual('NonEmptyArray<"valid" | "also_valid">'); - }); - - test('it should use a supplied name override', () => { - const newTestSchema = NonEmptyArray(testSchema, 'someName'); - expect(newTestSchema.name).toEqual('someName'); - }); - - test('it should NOT validate an empty array', () => { - const payload: string[] = []; - const decoded = nonEmptyArraySchema.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "[]" supplied to "TestSchemaArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should validate an array of testSchema', () => { - const payload: TestSchema[] = ['valid']; - const decoded = nonEmptyArraySchema.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 valid testSchema strings', () => { - const payload: TestSchema[] = ['valid', 'also_valid']; - const decoded = nonEmptyArraySchema.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate an array with a number', () => { - const payload = ['valid', 123]; - const decoded = nonEmptyArraySchema.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "123" supplied to "TestSchemaArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate an array with an invalid string', () => { - const payload = ['valid', 'invalid']; - const decoded = nonEmptyArraySchema.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "invalid" supplied to "TestSchemaArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate a null value', () => { - const payload = null; - const decoded = nonEmptyArraySchema.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "null" supplied to "TestSchemaArray"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_array.ts deleted file mode 100644 index 1b5261931230d..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_array.ts +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const NonEmptyArray = ( - codec: C, - name: string = `NonEmptyArray<${codec.name}>` -) => { - const arrType = t.array(codec); - type ArrType = t.TypeOf; - return new t.Type( - name, - arrType.is, - (input, context): Either => { - if (Array.isArray(input) && input.length === 0) { - return t.failure(input, context); - } else { - return arrType.validate(input, context); - } - }, - t.identity - ); -}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.test.ts deleted file mode 100644 index 470f8bc81c5d6..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { NonEmptyString } from './non_empty_string'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('non_empty_string', () => { - test('it should validate a regular string', () => { - const payload = '1'; - const decoded = NonEmptyString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a number', () => { - const payload = 5; - const decoded = NonEmptyString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "NonEmptyString"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate an empty string', () => { - const payload = ''; - const decoded = NonEmptyString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "" supplied to "NonEmptyString"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate empty spaces', () => { - const payload = ' '; - const decoded = NonEmptyString.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value " " supplied to "NonEmptyString"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.ts deleted file mode 100644 index e01eabd4c434e..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.ts +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the NonEmptyString as: - * - A string that is not empty - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const NonEmptyString = new t.Type( - 'NonEmptyString', - t.string.is, - (input, context): Either => { - if (typeof input === 'string' && input.trim() !== '') { - return t.success(input); - } else { - return t.failure(input, context); - } - }, - t.identity -); - -export type NonEmptyStringC = typeof NonEmptyString; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/normalized_ml_job_id.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/normalized_ml_job_id.ts deleted file mode 100644 index 7001cb8254d2b..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/normalized_ml_job_id.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; - -import { NonEmptyArray } from './non_empty_array'; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const machine_learning_job_id_normalized = NonEmptyArray(t.string); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type MachineLearningJobIdNormalized = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const machineLearningJobIdNormalizedOrUndefined = t.union([ - machine_learning_job_id_normalized, - t.undefined, -]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type MachineLearningJobIdNormalizedOrUndefined = t.TypeOf< - typeof machineLearningJobIdNormalizedOrUndefined ->; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/only_false_allowed.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/only_false_allowed.test.ts deleted file mode 100644 index a22266fb04f6a..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/only_false_allowed.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; -import { OnlyFalseAllowed } from './only_false_allowed'; - -describe('only_false_allowed', () => { - test('it should validate a boolean false as false', () => { - const payload = false; - const decoded = OnlyFalseAllowed.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a boolean true', () => { - const payload = true; - const decoded = OnlyFalseAllowed.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "true" supplied to "DefaultBooleanTrue"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate a number', () => { - const payload = 5; - const decoded = OnlyFalseAllowed.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultBooleanTrue"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default false', () => { - const payload = null; - const decoded = OnlyFalseAllowed.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(false); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/only_false_allowed.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/only_false_allowed.ts deleted file mode 100644 index 8150979cf2947..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/only_false_allowed.ts +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the OnlyFalseAllowed as: - * - If null or undefined, then a default false will be set - * - If true is sent in then this will return an error - * - If false is sent in then this will allow it only false - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const OnlyFalseAllowed = new t.Type( - 'DefaultBooleanTrue', - t.boolean.is, - (input, context): Either => { - if (input == null) { - return t.success(false); - } else { - if (typeof input === 'boolean' && input === false) { - return t.success(false); - } else { - return t.failure(input, context); - } - } - }, - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer.ts deleted file mode 100644 index 1771d0515fa20..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the positive integer are: - * - Natural Number (positive integer and not a float), - * - zero or greater - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const PositiveInteger = new t.Type( - 'PositiveInteger', - t.number.is, - (input, context): Either => { - return typeof input === 'number' && Number.isSafeInteger(input) && input >= 0 - ? t.success(input) - : t.failure(input, context); - }, - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer_greater_than_zero.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer_greater_than_zero.test.ts deleted file mode 100644 index dfb8b90633c83..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer_greater_than_zero.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { PositiveIntegerGreaterThanZero } from './positive_integer_greater_than_zero'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('positive_integer_greater_than_zero', () => { - test('it should validate a positive number', () => { - const payload = 1; - const decoded = PositiveIntegerGreaterThanZero.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should NOT validate a zero', () => { - const payload = 0; - const decoded = PositiveIntegerGreaterThanZero.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "0" supplied to "PositiveIntegerGreaterThanZero"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT validate a negative number', () => { - const payload = -1; - const decoded = PositiveIntegerGreaterThanZero.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "-1" supplied to "PositiveIntegerGreaterThanZero"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT validate a string', () => { - const payload = 'some string'; - const decoded = PositiveIntegerGreaterThanZero.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some string" supplied to "PositiveIntegerGreaterThanZero"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer_greater_than_zero.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer_greater_than_zero.ts deleted file mode 100644 index ddfb82b748ee3..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer_greater_than_zero.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the positive integer greater than zero is: - * - Natural Number (positive integer and not a float), - * - 1 or greater - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const PositiveIntegerGreaterThanZero = new t.Type( - 'PositiveIntegerGreaterThanZero', - t.number.is, - (input, context): Either => { - return typeof input === 'number' && Number.isSafeInteger(input) && input >= 1 - ? t.success(input) - : t.failure(input, context); - }, - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/postive_integer.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/postive_integer.test.ts deleted file mode 100644 index b0c64e70787af..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/postive_integer.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { PositiveInteger } from './positive_integer'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('positive_integer_greater_than_zero', () => { - test('it should validate a positive number', () => { - const payload = 1; - const decoded = PositiveInteger.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate a zero', () => { - const payload = 0; - const decoded = PositiveInteger.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should NOT validate a negative number', () => { - const payload = -1; - const decoded = PositiveInteger.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "-1" supplied to "PositiveInteger"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT validate a string', () => { - const payload = 'some string'; - const decoded = PositiveInteger.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some string" supplied to "PositiveInteger"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.test.ts deleted file mode 100644 index c8995f6a7cef0..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { DefaultStringArray } from './default_string_array'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('default_string_array', () => { - test('it should validate an empty array', () => { - const payload: string[] = []; - const decoded = DefaultStringArray.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 strings', () => { - const payload = ['value 1', 'value 2']; - const decoded = DefaultStringArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate an array with a number', () => { - const payload = ['value 1', 5]; - const decoded = DefaultStringArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "DefaultStringArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should return a default array entry', () => { - const payload = null; - const decoded = DefaultStringArray.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual([]); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.ts deleted file mode 100644 index a76606911f4ae..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the ReferencesDefaultArray as: - * - If null or undefined, then a default array will be set - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const ReferencesDefaultArray = new t.Type( - 'referencesWithDefaultArray', - t.array(t.string).is, - (input, context): Either => - input == null ? t.success([]) : t.array(t.string).validate(input, context), - t.identity -); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/risk_score.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/risk_score.test.ts deleted file mode 100644 index 67e8c801391ce..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/risk_score.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { RiskScore } from './risk_score'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('risk_score', () => { - test('it should validate a positive number', () => { - const payload = 1; - const decoded = RiskScore.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should validate a zero', () => { - const payload = 0; - const decoded = RiskScore.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should NOT validate a negative number', () => { - const payload = -1; - const decoded = RiskScore.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to "RiskScore"']); - expect(message.schema).toEqual({}); - }); - - test('it should NOT validate a string', () => { - const payload = 'some string'; - const decoded = RiskScore.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "some string" supplied to "RiskScore"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should NOT validate a risk score greater than 100', () => { - const payload = 101; - const decoded = RiskScore.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "101" supplied to "RiskScore"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/risk_score.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/risk_score.ts deleted file mode 100644 index e518bf13fd181..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/risk_score.ts +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -/** - * Types the risk score as: - * - Natural Number (positive integer and not a float), - * - Between the values [0 and 100] inclusive. - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const RiskScore = new t.Type( - 'RiskScore', - t.number.is, - (input, context): Either => { - return typeof input === 'number' && Number.isSafeInteger(input) && input >= 0 && input <= 100 - ? t.success(input) - : t.failure(input, context); - }, - t.identity -); - -export type RiskScoreC = typeof RiskScore; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/threat.mock.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/threat.mock.ts index e8a62822bfe5a..fb063a130e83f 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/threat.mock.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/threat.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Threats } from '../common/schemas'; +import { Threats } from '@kbn/securitysolution-io-ts-alerting-types'; export const getThreatMock = (): Threats => [ { diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/threat_mapping.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/threat_mapping.test.ts deleted file mode 100644 index c89c1059eedf0..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/threat_mapping.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { - concurrent_searches, - items_per_search, - ThreatMapping, - threatMappingEntries, - ThreatMappingEntries, - threat_mapping, -} from './threat_mapping'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; -import { exactCheck } from '../../../exact_check'; - -describe('threat_mapping', () => { - describe('threatMappingEntries', () => { - test('it should validate an entry', () => { - const payload: ThreatMappingEntries = [ - { - field: 'field.one', - type: 'mapping', - value: 'field.one', - }, - ]; - const decoded = threatMappingEntries.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should fail validation with an extra entry item', () => { - const payload: ThreatMappingEntries & Array<{ extra: string }> = [ - { - field: 'field.one', - type: 'mapping', - value: 'field.one', - extra: 'blah', - }, - ]; - const decoded = threatMappingEntries.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extra"']); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation with a non string', () => { - const payload = ([ - { - field: 5, - type: 'mapping', - value: 'field.one', - }, - ] as unknown) as ThreatMappingEntries[]; - const decoded = threatMappingEntries.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to "field"']); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation with a wrong type', () => { - const payload = ([ - { - field: 'field.one', - type: 'invalid', - value: 'field.one', - }, - ] as unknown) as ThreatMappingEntries[]; - const decoded = threatMappingEntries.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "invalid" supplied to "type"', - ]); - expect(message.schema).toEqual({}); - }); - }); - - describe('threat_mapping', () => { - test('it should validate a threat mapping', () => { - const payload: ThreatMapping = [ - { - entries: [ - { - field: 'field.one', - type: 'mapping', - value: 'field.one', - }, - ], - }, - ]; - const decoded = threat_mapping.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - }); - - test('it should fail validate with an extra key', () => { - const payload: ThreatMapping & Array<{ extra: string }> = [ - { - entries: [ - { - field: 'field.one', - type: 'mapping', - value: 'field.one', - }, - ], - extra: 'invalid', - }, - ]; - - const decoded = threat_mapping.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extra"']); - expect(message.schema).toEqual({}); - }); - - test('it should fail validate with an extra inner entry', () => { - const payload: ThreatMapping & Array<{ entries: Array<{ extra: string }> }> = [ - { - entries: [ - { - field: 'field.one', - type: 'mapping', - value: 'field.one', - extra: 'blah', - }, - ], - }, - ]; - - const decoded = threat_mapping.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['invalid keys "extra"']); - expect(message.schema).toEqual({}); - }); - - test('it should fail validate with an extra inner entry with the wrong data type', () => { - const payload = ([ - { - entries: [ - { - field: 5, - type: 'mapping', - value: 'field.one', - }, - ], - }, - ] as unknown) as ThreatMapping; - - const decoded = threat_mapping.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "5" supplied to "entries,field"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validate with empty array', () => { - const payload: string[] = []; - - const decoded = threat_mapping.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "[]" supplied to "NonEmptyArray"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when concurrent_searches is < 0', () => { - const payload = -1; - const decoded = concurrent_searches.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "-1" supplied to "PositiveIntegerGreaterThanZero"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when concurrent_searches is 0', () => { - const payload = 0; - const decoded = concurrent_searches.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "0" supplied to "PositiveIntegerGreaterThanZero"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when items_per_search is 0', () => { - const payload = 0; - const decoded = items_per_search.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "0" supplied to "PositiveIntegerGreaterThanZero"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should fail validation when items_per_search is < 0', () => { - const payload = -1; - const decoded = items_per_search.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "-1" supplied to "PositiveIntegerGreaterThanZero"', - ]); - expect(message.schema).toEqual({}); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/threat_mapping.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/threat_mapping.ts deleted file mode 100644 index 707b51e6b8965..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/threat_mapping.ts +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/* eslint-disable @typescript-eslint/naming-convention */ - -import * as t from 'io-ts'; -import { language } from '../common/schemas'; -import { NonEmptyArray } from './non_empty_array'; -import { NonEmptyString } from './non_empty_string'; -import { PositiveIntegerGreaterThanZero } from './positive_integer_greater_than_zero'; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_query = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatQuery = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threatQueryOrUndefined = t.union([threat_query, t.undefined]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatQueryOrUndefined = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_indicator_path = t.string; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatIndicatorPath = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threatIndicatorPathOrUndefined = t.union([threat_indicator_path, t.undefined]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatIndicatorPathOrUndefined = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_filters = t.array(t.unknown); // Filters are not easily type-able yet - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatFilters = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threatFiltersOrUndefined = t.union([threat_filters, t.undefined]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatFiltersOrUndefined = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threatMapEntry = t.exact( - t.type({ - field: NonEmptyString, - type: t.keyof({ mapping: null }), - value: NonEmptyString, - }) -); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatMapEntry = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threatMappingEntries = t.array(threatMapEntry); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatMappingEntries = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threatMap = t.exact( - t.type({ - entries: threatMappingEntries, - }) -); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatMap = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_mapping = NonEmptyArray(threatMap, 'NonEmptyArray'); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatMapping = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threatMappingOrUndefined = t.union([threat_mapping, t.undefined]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatMappingOrUndefined = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_index = t.array(t.string); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatIndex = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threatIndexOrUndefined = t.union([threat_index, t.undefined]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatIndexOrUndefined = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threat_language = t.union([language, t.undefined]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatLanguage = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const threatLanguageOrUndefined = t.union([threat_language, t.undefined]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ThreatLanguageOrUndefined = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const concurrent_searches = PositiveIntegerGreaterThanZero; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ConcurrentSearches = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const concurrentSearchesOrUndefined = t.union([concurrent_searches, t.undefined]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ConcurrentSearchesOrUndefined = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const items_per_search = PositiveIntegerGreaterThanZero; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ItemsPerSearch = t.TypeOf; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const itemsPerSearchOrUndefined = t.union([items_per_search, t.undefined]); - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export type ItemsPerSearchOrUndefined = t.TypeOf; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/uuid.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/uuid.test.ts deleted file mode 100644 index 2a98fd16c7107..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/uuid.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { UUID } from './uuid'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { left } from 'fp-ts/lib/Either'; -import { foldLeftRight, getPaths } from '../../../test_utils'; - -describe('uuid', () => { - test('it should validate a uuid', () => { - const payload = '4656dc92-5832-11ea-8e2d-0242ac130003'; - const decoded = UUID.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it should not validate a non uuid', () => { - const payload = '4656dc92-5832-11ea-8e2d'; - const decoded = UUID.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual([ - 'Invalid value "4656dc92-5832-11ea-8e2d" supplied to "UUID"', - ]); - expect(message.schema).toEqual({}); - }); - - test('it should not validate an empty string', () => { - const payload = ''; - const decoded = UUID.decode(payload); - const message = pipe(decoded, foldLeftRight); - - expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to "UUID"']); - expect(message.schema).toEqual({}); - }); -}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/uuid.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/uuid.ts deleted file mode 100644 index 79a130b26a6fd..0000000000000 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/uuid.ts +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { Either } from 'fp-ts/lib/Either'; - -const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - -/** - * Types the risk score as: - * - Natural Number (positive integer and not a float), - * - Between the values [0 and 100] inclusive. - * @deprecated Use packages/kbn-securitysolution-io-ts-utils - */ -export const UUID = new t.Type( - 'UUID', - t.string.is, - (input, context): Either => { - return typeof input === 'string' && regex.test(input) - ? t.success(input) - : t.failure(input, context); - }, - t.identity -); - -export type UUIDC = typeof UUID; diff --git a/x-pack/plugins/security_solution/common/detection_engine/utils.ts b/x-pack/plugins/security_solution/common/detection_engine/utils.ts index 611d23fd1ce22..6aa672881ff70 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/utils.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/utils.ts @@ -9,9 +9,10 @@ import { isEmpty } from 'lodash'; import type { EntriesArray } from '@kbn/securitysolution-io-ts-list-types'; +import { Type } from '@kbn/securitysolution-io-ts-alerting-types'; import { CreateExceptionListItemSchema, ExceptionListItemSchema } from '../shared_imports'; -import { Type, JobStatus, Threshold, ThresholdNormalized } from './schemas/common/schemas'; +import { JobStatus, Threshold, ThresholdNormalized } from './schemas/common/schemas'; export const hasLargeValueItem = ( exceptionItems: Array diff --git a/x-pack/plugins/security_solution/common/exact_check.test.ts b/x-pack/plugins/security_solution/common/exact_check.test.ts deleted file mode 100644 index d4a4ad4ce76ce..0000000000000 --- a/x-pack/plugins/security_solution/common/exact_check.test.ts +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { left, right, Either } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; - -import { exactCheck, findDifferencesRecursive } from './exact_check'; -import { foldLeftRight, getPaths } from './test_utils'; - -describe('exact_check', () => { - test('it returns an error if given extra object properties', () => { - const someType = t.exact( - t.type({ - a: t.string, - }) - ); - const payload = { a: 'test', b: 'test' }; - const decoded = someType.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['invalid keys "b"']); - expect(message.schema).toEqual({}); - }); - - test('it returns an error if the data type is not as expected', () => { - type UnsafeCastForTest = Either< - t.Errors, - { - a: number; - } - >; - - const someType = t.exact( - t.type({ - a: t.string, - }) - ); - - const payload = { a: 1 }; - const decoded = someType.decode(payload); - const checked = exactCheck(payload, decoded as UnsafeCastForTest); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['Invalid value "1" supplied to "a"']); - expect(message.schema).toEqual({}); - }); - - test('it does NOT return an error if given normal object properties', () => { - const someType = t.exact( - t.type({ - a: t.string, - }) - ); - const payload = { a: 'test' }; - const decoded = someType.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(payload); - }); - - test('it will return an existing error and not validate', () => { - const payload = { a: 'test' }; - const validationError: t.ValidationError = { - value: 'Some existing error', - context: [], - message: 'some error', - }; - const error: t.Errors = [validationError]; - const leftValue = left(error); - const checked = exactCheck(payload, leftValue); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual(['some error']); - expect(message.schema).toEqual({}); - }); - - test('it will work with a regular "right" payload without any decoding', () => { - const payload = { a: 'test' }; - const rightValue = right(payload); - const checked = exactCheck(payload, rightValue); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual({ a: 'test' }); - }); - - test('it will work with decoding a null payload when the schema expects a null', () => { - const someType = t.union([ - t.exact( - t.type({ - a: t.string, - }) - ), - t.null, - ]); - const payload = null; - const decoded = someType.decode(payload); - const checked = exactCheck(payload, decoded); - const message = pipe(checked, foldLeftRight); - expect(getPaths(left(message.errors))).toEqual([]); - expect(message.schema).toEqual(null); - }); - - test('it should find no differences recursively with two empty objects', () => { - const difference = findDifferencesRecursive({}, {}); - expect(difference).toEqual([]); - }); - - test('it should find a single difference with two objects with different keys', () => { - const difference = findDifferencesRecursive({ a: 1 }, { b: 1 }); - expect(difference).toEqual(['a']); - }); - - test('it should find a two differences with two objects with multiple different keys', () => { - const difference = findDifferencesRecursive({ a: 1, c: 1 }, { b: 1 }); - expect(difference).toEqual(['a', 'c']); - }); - - test('it should find no differences with two objects with the same keys', () => { - const difference = findDifferencesRecursive({ a: 1, b: 1 }, { a: 1, b: 1 }); - expect(difference).toEqual([]); - }); - - test('it should find a difference with two deep objects with different same keys', () => { - const difference = findDifferencesRecursive({ a: 1, b: { c: 1 } }, { a: 1, b: { d: 1 } }); - expect(difference).toEqual(['c']); - }); - - test('it should find a difference within an array', () => { - const difference = findDifferencesRecursive({ a: 1, b: [{ c: 1 }] }, { a: 1, b: [{ a: 1 }] }); - expect(difference).toEqual(['c']); - }); - - test('it should find a no difference when using arrays that are identical', () => { - const difference = findDifferencesRecursive({ a: 1, b: [{ c: 1 }] }, { a: 1, b: [{ c: 1 }] }); - expect(difference).toEqual([]); - }); - - test('it should find differences when one has an array and the other does not', () => { - const difference = findDifferencesRecursive({ a: 1, b: [{ c: 1 }] }, { a: 1 }); - expect(difference).toEqual(['b', '[{"c":1}]']); - }); - - test('it should find differences when one has an deep object and the other does not', () => { - const difference = findDifferencesRecursive({ a: 1, b: { c: 1 } }, { a: 1 }); - expect(difference).toEqual(['b', '{"c":1}']); - }); - - test('it should find differences when one has a deep object with multiple levels and the other does not', () => { - const difference = findDifferencesRecursive({ a: 1, b: { c: { d: 1 } } }, { a: 1 }); - expect(difference).toEqual(['b', '{"c":{"d":1}}']); - }); - - test('it tests two deep objects as the same with no key differences', () => { - const difference = findDifferencesRecursive( - { a: 1, b: { c: { d: 1 } } }, - { a: 1, b: { c: { d: 1 } } } - ); - expect(difference).toEqual([]); - }); - - test('it tests two deep objects with just one deep key difference', () => { - const difference = findDifferencesRecursive( - { a: 1, b: { c: { d: 1 } } }, - { a: 1, b: { c: { e: 1 } } } - ); - expect(difference).toEqual(['d']); - }); - - test('it should not find any differences when the original and decoded are both null', () => { - const difference = findDifferencesRecursive(null, null); - expect(difference).toEqual([]); - }); -}); diff --git a/x-pack/plugins/security_solution/common/exact_check.ts b/x-pack/plugins/security_solution/common/exact_check.ts deleted file mode 100644 index 5334989ea085b..0000000000000 --- a/x-pack/plugins/security_solution/common/exact_check.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { left, Either, fold, right } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { isObject, get } from 'lodash/fp'; - -/** - * Given an original object and a decoded object this will return an error - * if and only if the original object has additional keys that the decoded - * object does not have. If the original decoded already has an error, then - * this will return the error as is and not continue. - * - * NOTE: You MUST use t.exact(...) for this to operate correctly as your schema - * needs to remove additional keys before the compare - * - * You might not need this in the future if the below issue is solved: - * https://github.com/gcanti/io-ts/issues/322 - * - * @param original The original to check if it has additional keys - * @param decoded The decoded either which has either an existing error or the - * decoded object which could have additional keys stripped from it. - * @deprecated Use packages/kbn-securitysolution-io-ts-utils/src/exact_check/index.ts - */ -export const exactCheck = ( - original: unknown, - decoded: Either -): Either => { - const onLeft = (errors: t.Errors): Either => left(errors); - const onRight = (decodedValue: T): Either => { - const differences = findDifferencesRecursive(original, decodedValue); - if (differences.length !== 0) { - const validationError: t.ValidationError = { - value: differences, - context: [], - message: `invalid keys "${differences.join(',')}"`, - }; - const error: t.Errors = [validationError]; - return left(error); - } else { - return right(decodedValue); - } - }; - return pipe(decoded, fold(onLeft, onRight)); -}; - -export const findDifferencesRecursive = (original: unknown, decodedValue: T): string[] => { - if (decodedValue === null && original === null) { - // both the decodedValue and the original are null which indicates that they are equal - // so do not report differences - return []; - } else if (decodedValue == null) { - try { - // It is null and painful when the original contains an object or an array - // the the decoded value does not have. - return [JSON.stringify(original)]; - } catch (err) { - return ['circular reference']; - } - } else if (typeof original !== 'object' || original == null) { - // We are not an object or null so do not report differences - return []; - } else { - const decodedKeys = Object.keys(decodedValue); - const differences = Object.keys(original).flatMap((originalKey) => { - const foundKey = decodedKeys.some((key) => key === originalKey); - const topLevelKey = foundKey ? [] : [originalKey]; - // I use lodash to cheat and get an any (not going to lie ;-)) - const valueObjectOrArrayOriginal = get(originalKey, original); - const valueObjectOrArrayDecoded = get(originalKey, decodedValue); - if (isObject(valueObjectOrArrayOriginal)) { - return [ - ...topLevelKey, - ...findDifferencesRecursive(valueObjectOrArrayOriginal, valueObjectOrArrayDecoded), - ]; - } else if (Array.isArray(valueObjectOrArrayOriginal)) { - return [ - ...topLevelKey, - ...valueObjectOrArrayOriginal.flatMap((arrayElement, index) => - findDifferencesRecursive(arrayElement, get(index, valueObjectOrArrayDecoded)) - ), - ]; - } else { - return topLevelKey; - } - }); - return differences; - } -}; diff --git a/x-pack/plugins/security_solution/common/format_errors.test.ts b/x-pack/plugins/security_solution/common/format_errors.test.ts deleted file mode 100644 index 149bae85fec8a..0000000000000 --- a/x-pack/plugins/security_solution/common/format_errors.test.ts +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { formatErrors } from './format_errors'; - -describe('utils', () => { - test('returns an empty error message string if there are no errors', () => { - const errors: t.Errors = []; - const output = formatErrors(errors); - expect(output).toEqual([]); - }); - - test('returns a single error message if given one', () => { - const validationError: t.ValidationError = { - value: 'Some existing error', - context: [], - message: 'some error', - }; - const errors: t.Errors = [validationError]; - const output = formatErrors(errors); - expect(output).toEqual(['some error']); - }); - - test('returns a two error messages if given two', () => { - const validationError1: t.ValidationError = { - value: 'Some existing error 1', - context: [], - message: 'some error 1', - }; - const validationError2: t.ValidationError = { - value: 'Some existing error 2', - context: [], - message: 'some error 2', - }; - const errors: t.Errors = [validationError1, validationError2]; - const output = formatErrors(errors); - expect(output).toEqual(['some error 1', 'some error 2']); - }); - - test('it filters out duplicate error messages', () => { - const validationError1: t.ValidationError = { - value: 'Some existing error 1', - context: [], - message: 'some error 1', - }; - const validationError2: t.ValidationError = { - value: 'Some existing error 1', - context: [], - message: 'some error 1', - }; - const errors: t.Errors = [validationError1, validationError2]; - const output = formatErrors(errors); - expect(output).toEqual(['some error 1']); - }); - - test('will use message before context if it is set', () => { - const context: t.Context = ([{ key: 'some string key' }] as unknown) as t.Context; - const validationError1: t.ValidationError = { - value: 'Some existing error 1', - context, - message: 'I should be used first', - }; - const errors: t.Errors = [validationError1]; - const output = formatErrors(errors); - expect(output).toEqual(['I should be used first']); - }); - - test('will use context entry of a single string', () => { - const context: t.Context = ([{ key: 'some string key' }] as unknown) as t.Context; - const validationError1: t.ValidationError = { - value: 'Some existing error 1', - context, - }; - const errors: t.Errors = [validationError1]; - const output = formatErrors(errors); - expect(output).toEqual(['Invalid value "Some existing error 1" supplied to "some string key"']); - }); - - test('will use two context entries of two strings', () => { - const context: t.Context = ([ - { key: 'some string key 1' }, - { key: 'some string key 2' }, - ] as unknown) as t.Context; - const validationError1: t.ValidationError = { - value: 'Some existing error 1', - context, - }; - const errors: t.Errors = [validationError1]; - const output = formatErrors(errors); - expect(output).toEqual([ - 'Invalid value "Some existing error 1" supplied to "some string key 1,some string key 2"', - ]); - }); - - test('will filter out and not use any strings of numbers', () => { - const context: t.Context = ([ - { key: '5' }, - { key: 'some string key 2' }, - ] as unknown) as t.Context; - const validationError1: t.ValidationError = { - value: 'Some existing error 1', - context, - }; - const errors: t.Errors = [validationError1]; - const output = formatErrors(errors); - expect(output).toEqual([ - 'Invalid value "Some existing error 1" supplied to "some string key 2"', - ]); - }); - - test('will filter out and not use null', () => { - const context: t.Context = ([ - { key: null }, - { key: 'some string key 2' }, - ] as unknown) as t.Context; - const validationError1: t.ValidationError = { - value: 'Some existing error 1', - context, - }; - const errors: t.Errors = [validationError1]; - const output = formatErrors(errors); - expect(output).toEqual([ - 'Invalid value "Some existing error 1" supplied to "some string key 2"', - ]); - }); - - test('will filter out and not use empty strings', () => { - const context: t.Context = ([ - { key: '' }, - { key: 'some string key 2' }, - ] as unknown) as t.Context; - const validationError1: t.ValidationError = { - value: 'Some existing error 1', - context, - }; - const errors: t.Errors = [validationError1]; - const output = formatErrors(errors); - expect(output).toEqual([ - 'Invalid value "Some existing error 1" supplied to "some string key 2"', - ]); - }); - - test('will use a name context if it cannot find a keyContext', () => { - const context: t.Context = ([ - { key: '' }, - { key: '', type: { name: 'someName' } }, - ] as unknown) as t.Context; - const validationError1: t.ValidationError = { - value: 'Some existing error 1', - context, - }; - const errors: t.Errors = [validationError1]; - const output = formatErrors(errors); - expect(output).toEqual(['Invalid value "Some existing error 1" supplied to "someName"']); - }); - - test('will return an empty string if name does not exist but type does', () => { - const context: t.Context = ([{ key: '' }, { key: '', type: {} }] as unknown) as t.Context; - const validationError1: t.ValidationError = { - value: 'Some existing error 1', - context, - }; - const errors: t.Errors = [validationError1]; - const output = formatErrors(errors); - expect(output).toEqual(['Invalid value "Some existing error 1" supplied to ""']); - }); - - test('will stringify an error value', () => { - const context: t.Context = ([ - { key: '' }, - { key: 'some string key 2' }, - ] as unknown) as t.Context; - const validationError1: t.ValidationError = { - value: { foo: 'some error' }, - context, - }; - const errors: t.Errors = [validationError1]; - const output = formatErrors(errors); - expect(output).toEqual([ - 'Invalid value "{"foo":"some error"}" supplied to "some string key 2"', - ]); - }); -}); diff --git a/x-pack/plugins/security_solution/common/format_errors.ts b/x-pack/plugins/security_solution/common/format_errors.ts deleted file mode 100644 index 16925699b0fcf..0000000000000 --- a/x-pack/plugins/security_solution/common/format_errors.ts +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { isObject } from 'lodash/fp'; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.ts - */ -export const formatErrors = (errors: t.Errors): string[] => { - const err = errors.map((error) => { - if (error.message != null) { - return error.message; - } else { - const keyContext = error.context - .filter( - (entry) => entry.key != null && !Number.isInteger(+entry.key) && entry.key.trim() !== '' - ) - .map((entry) => entry.key) - .join(','); - - const nameContext = error.context.find((entry) => entry.type?.name?.length > 0); - const suppliedValue = - keyContext !== '' ? keyContext : nameContext != null ? nameContext.type.name : ''; - const value = isObject(error.value) ? JSON.stringify(error.value) : error.value; - return `Invalid value "${value}" supplied to "${suppliedValue}"`; - } - }); - - return [...new Set(err)]; -}; diff --git a/x-pack/plugins/security_solution/common/index.ts b/x-pack/plugins/security_solution/common/index.ts index 9f4af059632c4..1fec1c76430eb 100644 --- a/x-pack/plugins/security_solution/common/index.ts +++ b/x-pack/plugins/security_solution/common/index.ts @@ -4,5 +4,3 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ - -export * from './shared_exports'; diff --git a/x-pack/plugins/security_solution/common/machine_learning/helpers.ts b/x-pack/plugins/security_solution/common/machine_learning/helpers.ts index 60477d3685db7..819337d8b715a 100644 --- a/x-pack/plugins/security_solution/common/machine_learning/helpers.ts +++ b/x-pack/plugins/security_solution/common/machine_learning/helpers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Type } from '../detection_engine/schemas/common/schemas'; +import { Type } from '@kbn/securitysolution-io-ts-alerting-types'; // Based on ML Job/Datafeed States from x-pack/legacy/plugins/ml/common/constants/states.js const enabledStates = ['started', 'opened']; diff --git a/x-pack/plugins/security_solution/common/shared_exports.ts b/x-pack/plugins/security_solution/common/shared_exports.ts deleted file mode 100644 index bf740ddce9fd6..0000000000000 --- a/x-pack/plugins/security_solution/common/shared_exports.ts +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export { NonEmptyString } from './detection_engine/schemas/types/non_empty_string'; -export { DefaultArray } from './detection_engine/schemas/types/default_array'; -export { DefaultUuid } from './detection_engine/schemas/types/default_uuid'; -export { DefaultStringArray } from './detection_engine/schemas/types/default_string_array'; -export { - DefaultVersionNumber, - DefaultVersionNumberDecoded, -} from './detection_engine/schemas/types/default_version_number'; -export { exactCheck } from './exact_check'; -export { getPaths, foldLeftRight, removeExternalLinkText } from './test_utils'; -export { validate, validateEither } from './validate'; -export { formatErrors } from './format_errors'; -export { addIdToItem, removeIdFromItem } from './add_remove_id_to_item'; diff --git a/x-pack/plugins/security_solution/common/shared_imports.ts b/x-pack/plugins/security_solution/common/shared_imports.ts index a6bad0347e641..8f858e724394b 100644 --- a/x-pack/plugins/security_solution/common/shared_imports.ts +++ b/x-pack/plugins/security_solution/common/shared_imports.ts @@ -12,9 +12,6 @@ export { CreateExceptionListSchema, CreateExceptionListItemSchema, UpdateExceptionListItemSchema, - exceptionListItemSchema, - createExceptionListItemSchema, - listSchema, ENDPOINT_LIST_ID, ENDPOINT_TRUSTED_APPS_LIST_ID, EXCEPTION_LIST_URL, diff --git a/x-pack/plugins/security_solution/common/test_utils.ts b/x-pack/plugins/security_solution/common/test_utils.ts deleted file mode 100644 index df9e9e12fc1d9..0000000000000 --- a/x-pack/plugins/security_solution/common/test_utils.ts +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import * as t from 'io-ts'; -import { fold } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { formatErrors } from './format_errors'; - -interface Message { - errors: t.Errors; - schema: T | {}; -} - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils/src/test_utils/index.ts - */ -const onLeft = (errors: t.Errors): Message => { - return { schema: {}, errors }; -}; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils/src/test_utils/index.ts - */ -const onRight = (schema: T): Message => { - return { - schema, - errors: [], - }; -}; - -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils/src/test_utils/index.ts - */ -export const foldLeftRight = fold(onLeft, onRight); - -/** - * Convenience utility to keep the error message handling within tests to be - * very concise. - * @deprecated Use packages/kbn-securitysolution-io-ts-utils/src/test_utils/index.ts - * @param validation The validation to get the errors from - */ -export const getPaths = (validation: t.Validation): string[] => { - return pipe( - validation, - fold( - (errors) => formatErrors(errors), - () => ['no errors'] - ) - ); -}; - -/** - * Convenience utility to remove text appended to links by EUI - * @deprecated Use packages/kbn-securitysolution-io-ts-utils/src/test_utils/index.ts - */ -export const removeExternalLinkText = (str: string) => - str.replace(/\(opens in a new tab or window\)/g, ''); diff --git a/x-pack/plugins/security_solution/common/types/timeline/index.ts b/x-pack/plugins/security_solution/common/types/timeline/index.ts index 5b6c9c532ba7c..7ae52a3990ff7 100644 --- a/x-pack/plugins/security_solution/common/types/timeline/index.ts +++ b/x-pack/plugins/security_solution/common/types/timeline/index.ts @@ -7,6 +7,7 @@ import * as runtimeTypes from 'io-ts'; +import { PositiveInteger } from '@kbn/securitysolution-io-ts-types'; import { stringEnum, unionWithNullType } from '../../utility_types'; import { NoteResult, NoteSavedObject, NoteSavedObjectToReturnRuntimeType } from './note'; import { @@ -19,7 +20,6 @@ import { success_count as successCount, } from '../../detection_engine/schemas/common/schemas'; import { FlowTarget } from '../../search_strategy/security_solution/network'; -import { PositiveInteger } from '../../detection_engine/schemas/types'; import { errorSchema } from '../../detection_engine/schemas/response/error_schema'; import { Direction, Maybe } from '../../search_strategy'; diff --git a/x-pack/plugins/security_solution/common/validate.test.ts b/x-pack/plugins/security_solution/common/validate.test.ts deleted file mode 100644 index e3fe5c55288a3..0000000000000 --- a/x-pack/plugins/security_solution/common/validate.test.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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { left, right } from 'fp-ts/lib/Either'; -import * as t from 'io-ts'; - -import { validate, validateEither } from './validate'; - -describe('validate', () => { - test('it should do a validation correctly', () => { - const schema = t.exact(t.type({ a: t.number })); - const payload = { a: 1 }; - const [validated, errors] = validate(payload, schema); - - expect(validated).toEqual(payload); - expect(errors).toEqual(null); - }); - - test('it should do an in-validation correctly', () => { - const schema = t.exact(t.type({ a: t.number })); - const payload = { a: 'some other value' }; - const [validated, errors] = validate(payload, schema); - - expect(validated).toEqual(null); - expect(errors).toEqual('Invalid value "some other value" supplied to "a"'); - }); -}); - -describe('validateEither', () => { - it('returns the ORIGINAL payload as right if valid', () => { - const schema = t.exact(t.type({ a: t.number })); - const payload = { a: 1 }; - const result = validateEither(schema, payload); - - expect(result).toEqual(right(payload)); - }); - - it('returns an error string if invalid', () => { - const schema = t.exact(t.type({ a: t.number })); - const payload = { a: 'some other value' }; - const result = validateEither(schema, payload); - - expect(result).toEqual(left(new Error('Invalid value "some other value" supplied to "a"'))); - }); -}); diff --git a/x-pack/plugins/security_solution/common/validate.ts b/x-pack/plugins/security_solution/common/validate.ts deleted file mode 100644 index 1ac41ecbfb88b..0000000000000 --- a/x-pack/plugins/security_solution/common/validate.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { fold, Either, mapLeft } from 'fp-ts/lib/Either'; -import { pipe } from 'fp-ts/lib/pipeable'; -import { fromEither, TaskEither } from 'fp-ts/lib/TaskEither'; -import * as t from 'io-ts'; -import { exactCheck } from './exact_check'; -import { formatErrors } from './format_errors'; - -export const validate = ( - obj: object, - schema: T -): [t.TypeOf | null, string | null] => { - const decoded = schema.decode(obj); - const checked = exactCheck(obj, decoded); - const left = (errors: t.Errors): [T | null, string | null] => [ - null, - formatErrors(errors).join(','), - ]; - const right = (output: T): [T | null, string | null] => [output, null]; - return pipe(checked, fold(left, right)); -}; - -export const validateNonExact = ( - obj: unknown, - schema: T -): [t.TypeOf | null, string | null] => { - const decoded = schema.decode(obj); - const left = (errors: t.Errors): [T | null, string | null] => [ - null, - formatErrors(errors).join(','), - ]; - const right = (output: T): [T | null, string | null] => [output, null]; - return pipe(decoded, fold(left, right)); -}; - -export const validateEither = ( - schema: T, - obj: A -): Either => - pipe( - obj, - (a) => schema.validate(a, t.getDefaultContext(schema.asDecoder())), - mapLeft((errors) => new Error(formatErrors(errors).join(','))) - ); - -export const validateTaskEither = ( - schema: T, - obj: A -): TaskEither => fromEither(validateEither(schema, obj)); 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 c605a71c50e33..45d4137f8c5b0 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 @@ -11,7 +11,7 @@ import { EuiComboBox, EuiComboBoxOptionOption } from '@elastic/eui'; import { waitFor } from '@testing-library/react'; import { getField } from '../../../../../../../src/plugins/data/common/index_patterns/fields/fields.mocks'; -import { ListSchema } from '../../../lists_plugin_deps'; +import { ListSchema } from '../../../shared_imports'; import { getFoundListSchemaMock } from '../../../../../lists/common/schemas/response/found_list_schema.mock'; import { getListResponseMock } from '../../../../../lists/common/schemas/response/list_schema.mock'; import { DATE_NOW, VERSION, IMMUTABLE } from '../../../../../lists/common/constants.mock'; @@ -28,8 +28,8 @@ const mockKeywordList: ListSchema = { }; const mockResult = { ...getFoundListSchemaMock() }; mockResult.data = [...mockResult.data, mockKeywordList]; -jest.mock('../../../lists_plugin_deps', () => { - const originalModule = jest.requireActual('../../../lists_plugin_deps'); +jest.mock('../../../shared_imports', () => { + const originalModule = jest.requireActual('../../../shared_imports'); return { ...originalModule, 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 3efa8c4c2d605..37e5961c8cd7e 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 React, { useState, useEffect, useCallback, useMemo } from 'react'; import { EuiFormRow, EuiComboBoxOptionOption, EuiComboBox } from '@elastic/eui'; import { IFieldType } from '../../../../../../../src/plugins/data/common'; -import { useFindLists, ListSchema } from '../../../lists_plugin_deps'; +import { useFindLists, ListSchema } from '../../../shared_imports'; import { useKibana } from '../../../common/lib/kibana'; import { filterFieldToList, getGenericComboBoxProps } from './helpers'; import * as i18n from './translations'; 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 bd79bb0fcc8e8..13f4e5e6fd6f9 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 @@ -9,7 +9,7 @@ import dateMath from '@elastic/datemath'; import { EuiComboBoxOptionOption } from '@elastic/eui'; import type { Type } from '@kbn/securitysolution-io-ts-list-types'; -import type { ListSchema } from '../../../lists_plugin_deps'; +import type { ListSchema } from '../../../shared_imports'; import { IFieldType } from '../../../../../../../src/plugins/data/common'; import { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/errors/bad_request_error.ts b/x-pack/plugins/security_solution/public/common/components/endpoint/host_isolation/index.ts similarity index 79% rename from x-pack/plugins/security_solution/server/lib/detection_engine/errors/bad_request_error.ts rename to x-pack/plugins/security_solution/public/common/components/endpoint/host_isolation/index.ts index c68e7845953f6..de51df283251d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/errors/bad_request_error.ts +++ b/x-pack/plugins/security_solution/public/common/components/endpoint/host_isolation/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export class BadRequestError extends Error {} +export * from './isolate_success'; +export * from './isolate_form'; diff --git a/x-pack/plugins/security_solution/public/common/components/endpoint/host_isolation/isolate_form.tsx b/x-pack/plugins/security_solution/public/common/components/endpoint/host_isolation/isolate_form.tsx new file mode 100644 index 0000000000000..dd26f676c1fe3 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/endpoint/host_isolation/isolate_form.tsx @@ -0,0 +1,88 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { ChangeEventHandler, memo, ReactNode, useCallback } from 'react'; +import { + EuiButton, + EuiButtonEmpty, + EuiFlexGroup, + EuiFlexItem, + EuiSpacer, + EuiText, + EuiTextArea, + EuiTitle, +} from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { CANCEL, COMMENT, COMMENT_PLACEHOLDER, CONFIRM } from './translations'; + +export interface EndpointIsolatedFormProps { + hostName: string; + onCancel: () => void; + onConfirm: () => void; + onChange: (changes: { comment: string }) => void; + comment?: string; + /** Any additional message to be appended to the default one */ + messageAppend?: ReactNode; + /** If true, then `Confirm` and `Cancel` buttons will be disabled, and `Confirm` button will loading loading style */ + isLoading?: boolean; +} + +export const EndpointIsolateForm = memo( + ({ hostName, onCancel, onConfirm, onChange, comment = '', messageAppend, isLoading = false }) => { + const handleCommentChange: ChangeEventHandler = useCallback( + (event) => { + onChange({ comment: event.target.value }); + }, + [onChange] + ); + + return ( + <> + +

+ {hostName} }} + />{' '} + {messageAppend} +

+
+ + + + +

{COMMENT}

+
+ + + + + + + + {CANCEL} + + + + + {CONFIRM} + + + + + ); + } +); + +EndpointIsolateForm.displayName = 'EndpointIsolateForm'; diff --git a/x-pack/plugins/security_solution/public/common/components/endpoint/host_isolation/isolate_success.tsx b/x-pack/plugins/security_solution/public/common/components/endpoint/host_isolation/isolate_success.tsx new file mode 100644 index 0000000000000..ee70a4526f5ac --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/endpoint/host_isolation/isolate_success.tsx @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { memo, ReactNode } from 'react'; +import { EuiButtonEmpty, EuiCallOut, EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; +import { GET_SUCCESS_MESSAGE } from './translations'; + +export interface EndpointIsolateSuccessProps { + hostName: string; + completeButtonLabel: string; + onComplete: () => void; + additionalInfo?: ReactNode; +} + +export const EndpointIsolateSuccess = memo( + ({ hostName, onComplete, completeButtonLabel, additionalInfo }) => { + return ( + <> + + {additionalInfo} + + + + + + +

{completeButtonLabel}

+
+
+
+
+ + ); + } +); + +EndpointIsolateSuccess.displayName = 'EndpointIsolateSuccess'; diff --git a/x-pack/plugins/security_solution/public/common/components/endpoint/host_isolation/translations.ts b/x-pack/plugins/security_solution/public/common/components/endpoint/host_isolation/translations.ts new file mode 100644 index 0000000000000..baeced2a7a69f --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/endpoint/host_isolation/translations.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { i18n } from '@kbn/i18n'; + +export const CANCEL = i18n.translate('xpack.securitySolution.endpoint.hostIsolation.cancel', { + defaultMessage: 'Cancel', +}); + +export const CONFIRM = i18n.translate('xpack.securitySolution.endpoint.hostIsolation.confirm', { + defaultMessage: 'Confirm', +}); + +export const COMMENT = i18n.translate('xpack.securitySolution.endpoint.hostIsolation.comment', { + defaultMessage: 'Comment', +}); + +export const COMMENT_PLACEHOLDER = i18n.translate( + 'xpack.securitySolution.endpoint.hostIsolation.comment.placeholder', + { defaultMessage: 'You may leave an optional note here.' } +); + +export const GET_SUCCESS_MESSAGE = (hostName: string) => + i18n.translate('xpack.securitySolution.endpoint.hostIsolation.successfulMessage', { + defaultMessage: 'Host Isolation on {hostName} successfully submitted', + values: { hostName }, + }); 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 6efbbcf64406b..3216a020c3b04 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 @@ -25,7 +25,11 @@ import { EuiComboBox, EuiComboBoxOptionOption, } from '@elastic/eui'; -import type { ExceptionListType } from '@kbn/securitysolution-io-ts-list-types'; +import type { + ExceptionListType, + OsTypeArray, + OsType, +} from '@kbn/securitysolution-io-ts-list-types'; import { hasEqlSequenceQuery, isEqlRule, @@ -63,7 +67,6 @@ import { ErrorInfo, ErrorCallout } from '../error_callout'; import { AlertData, ExceptionsBuilderExceptionItem } from '../types'; import { useFetchIndex } from '../../../containers/source'; import { useGetInstalledJob } from '../../ml/hooks/use_get_jobs'; -import { OsTypeArray, OsType } from '../../../../../../lists/common/schemas'; export interface AddExceptionModalProps { ruleName: string; 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 6c68dcf934b71..ed050574c3994 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 @@ -22,7 +22,11 @@ import { EuiCallOut, } from '@elastic/eui'; -import type { ExceptionListType } from '@kbn/securitysolution-io-ts-list-types'; +import type { + ExceptionListType, + OsTypeArray, + OsType, +} from '@kbn/securitysolution-io-ts-list-types'; import { hasEqlSequenceQuery, isEqlRule, @@ -54,7 +58,6 @@ import { import { Loader } from '../../loader'; import { ErrorInfo, ErrorCallout } from '../error_callout'; import { useGetInstalledJob } from '../../ml/hooks/use_get_jobs'; -import { OsTypeArray, OsType } from '../../../../../../lists/common/schemas'; interface EditExceptionModalProps { ruleName: string; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/error_callout.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/error_callout.tsx index 2317ec353a3bf..ba8b5b522f0a7 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/error_callout.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/error_callout.tsx @@ -16,8 +16,8 @@ import { EuiSpacer, } from '@elastic/eui'; +import { List } from '@kbn/securitysolution-io-ts-list-types'; import { HttpSetup } from '../../../../../../../src/core/public'; -import { List } from '../../../../common/detection_engine/schemas/types/lists'; import { Rule } from '../../../detections/containers/detection_engine/rules/types'; import * as i18n from './translations'; import { useDissasociateExceptionList } from '../../../detections/containers/detection_engine/rules/use_dissasociate_exception_list'; 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 49cdd7103c48b..bbf83a58e3679 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 @@ -17,11 +17,14 @@ import type { ListOperatorTypeEnum as OperatorTypeEnum, ListOperatorEnum as OperatorEnum, } from '@kbn/securitysolution-io-ts-list-types'; -import { Ecs } from '../../../../common/ecs'; -import { CodeSignature } from '../../../../common/ecs/file'; -import { IFieldType } from '../../../../../../../src/plugins/data/common'; -import { OperatorOption } from '../autocomplete/types'; -import { ExceptionListItemSchema, CreateExceptionListItemSchema } from '../../../lists_plugin_deps'; +import type { Ecs } from '../../../../common/ecs'; +import type { CodeSignature } from '../../../../common/ecs/file'; +import type { IFieldType } from '../../../../../../../src/plugins/data/common'; +import type { OperatorOption } from '../autocomplete/types'; +import type { + ExceptionListItemSchema, + CreateExceptionListItemSchema, +} from '../../../shared_imports'; export interface FormattedEntry { fieldName: string; 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 f609acf9c6c63..c8a624b009c43 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 @@ -16,11 +16,11 @@ import * as buildFilterHelpers from '../../../detections/components/alerts_table import { getExceptionListItemSchemaMock } from '../../../../../lists/common/schemas/response/exception_list_item_schema.mock'; import { getCreateExceptionListItemSchemaMock } from '../../../../../lists/common/schemas/request/create_exception_list_item_schema.mock'; import { getUpdateExceptionListItemSchemaMock } from '../../../../../lists/common/schemas/request/update_exception_list_item_schema.mock'; -import { +import type { ExceptionListItemSchema, CreateExceptionListItemSchema, UpdateExceptionListItemSchema, -} from '../../../lists_plugin_deps'; +} from '../../../shared_imports'; import { useAddOrUpdateException, UseAddOrUpdateExceptionProps, 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 614f5301c82e2..6aa68373d5eb5 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 @@ -13,7 +13,7 @@ import { ExceptionListItemSchema, CreateExceptionListItemSchema, useApi, -} from '../../../lists_plugin_deps'; +} from '../../../shared_imports'; import { updateAlertStatus } from '../../../detections/containers/detection_engine/alerts/api'; import { getUpdateAlertsQuery } from '../../../detections/components/alerts_table/actions'; import { 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 17237f4f94c61..d38d920eee188 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 @@ -12,8 +12,7 @@ import * as rulesApi from '../../../detections/containers/detection_engine/rules import * as listsApi from '../../../../../lists/public/exceptions/api'; import { getExceptionListSchemaMock } from '../../../../../lists/common/schemas/response/exception_list_schema.mock'; import { savedRuleMock } from '../../../detections/containers/detection_engine/rules/mock'; -import type { ExceptionListType } from '@kbn/securitysolution-io-ts-list-types'; -import { ListArray } from '../../../../common/detection_engine/schemas/types'; +import type { ExceptionListType, ListArray } from '@kbn/securitysolution-io-ts-list-types'; import { getListArrayMock } from '../../../../common/detection_engine/schemas/types/lists.mock'; import { useFetchOrCreateRuleExceptionList, 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 9b970e2caab15..98c207f47a45b 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 @@ -6,10 +6,10 @@ */ import { useEffect, useState } from 'react'; +import { List, ListArray } from '@kbn/securitysolution-io-ts-list-types'; import { HttpStart } from '../../../../../../../src/core/public'; import { Rule } from '../../../detections/containers/detection_engine/rules/types'; -import { List, ListArray } from '../../../../common/detection_engine/schemas/types'; import { fetchRuleById, patchRule, @@ -18,7 +18,7 @@ import { fetchExceptionListById, addExceptionList, addEndpointExceptionList, -} from '../../../lists_plugin_deps'; +} from '../../../shared_imports'; import { ExceptionListSchema, CreateExceptionListSchema, 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 86eca688ef082..ff242506927f1 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,10 +16,10 @@ import { import React, { useMemo, Fragment } from 'react'; import styled, { css } from 'styled-components'; -import { DescriptionListItem } from '../../types'; +import type { DescriptionListItem } from '../../types'; import { getDescriptionListContent } from '../helpers'; import * as i18n from '../../translations'; -import { ExceptionListItemSchema } from '../../../../../../public/lists_plugin_deps'; +import type { ExceptionListItemSchema } from '../../../../../../public/shared_imports'; const MyExceptionDetails = styled(EuiFlexItem)` ${({ theme }) => css` 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 caff2be29ab2d..7909366e7a32e 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 @@ -20,8 +20,8 @@ import { ExceptionDetails } from './exception_details'; import { ExceptionEntries } from './exception_entries'; import { getFormattedComments } from '../../helpers'; import { getFormattedEntries } from '../helpers'; -import { FormattedEntry, ExceptionListItemIdentifiers } from '../../types'; -import { ExceptionListItemSchema } from '../../../../../../public/lists_plugin_deps'; +import type { FormattedEntry, ExceptionListItemIdentifiers } from '../../types'; +import type { ExceptionListItemSchema } from '../../../../../../public/shared_imports'; const MyFlexItem = styled(EuiFlexItem)` &.comments--show { diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_items.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_items.tsx index 825bbf5f6f050..1e4cd306c4661 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_items.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_items.tsx @@ -12,8 +12,8 @@ import styled from 'styled-components'; import * as i18n from '../translations'; import { ExceptionItem } from './exception_item'; import { AndOrBadge } from '../../and_or_badge'; -import { ExceptionListItemSchema } from '../../../../../public/lists_plugin_deps'; -import { ExceptionListItemIdentifiers } from '../types'; +import type { ExceptionListItemSchema } from '../../../../../public/shared_imports'; +import type { ExceptionListItemIdentifiers } from '../types'; const MyFlexItem = styled(EuiFlexItem)` margin: ${({ theme }) => `${theme.eui.euiSize} 0`}; 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 index abd45cf2945cb..936423d0c362b 100644 --- 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 @@ -12,10 +12,10 @@ import { ExceptionListItemSchema, getEntryValue, getExceptionOperatorSelect, -} from '../../../../lists_plugin_deps'; +} from '../../../../shared_imports'; import { formatOperatingSystems } from '../helpers'; -import { FormattedEntry, BuilderEntry, DescriptionListItem } from '../types'; +import type { FormattedEntry, BuilderEntry, DescriptionListItem } from '../types'; import * as i18n from '../translations'; /** 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 971b3fda47191..45db39d6a03ac 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 @@ -11,7 +11,7 @@ import { ThemeProvider } from 'styled-components'; import { ExceptionsViewer } from './'; import { useKibana } from '../../../../common/lib/kibana'; -import { useExceptionListItems, useApi } from '../../../../../public/lists_plugin_deps'; +import { useExceptionListItems, useApi } from '../../../../../public/shared_imports'; import { ExceptionListTypeEnum } from '@kbn/securitysolution-io-ts-list-types'; import { getExceptionListSchemaMock } from '../../../../../../lists/common/schemas/response/exception_list_schema.mock'; @@ -31,7 +31,7 @@ const mockTheme = getMockTheme({ }); jest.mock('../../../../common/lib/kibana'); -jest.mock('../../../../../public/lists_plugin_deps'); +jest.mock('../../../../../public/shared_imports'); describe('ExceptionsViewer', () => { const ruleName = 'test rule'; 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 da7607f40ab72..8055e771a1647 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 @@ -24,7 +24,7 @@ import { ExceptionListItemSchema, UseExceptionListItemsSuccess, useApi, -} from '../../../../../public/lists_plugin_deps'; +} from '../../../../../public/shared_imports'; import { ExceptionsViewerPagination } from './exceptions_pagination'; import { ExceptionsViewerUtility } from './exceptions_utility'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts index bf8e454e9971f..4908a88b72526 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts @@ -6,17 +6,17 @@ */ import type { ExceptionListType } from '@kbn/securitysolution-io-ts-list-types'; -import { +import type { FilterOptions, ExceptionsPagination, ExceptionListItemIdentifiers, Filter, } from '../types'; -import { +import type { ExceptionListItemSchema, ExceptionListIdentifiers, Pagination, -} from '../../../../../public/lists_plugin_deps'; +} from '../../../../../public/shared_imports'; export type ViewerModalName = 'addModal' | 'editModal' | null; diff --git a/x-pack/plugins/security_solution/public/common/components/links/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/links/index.test.tsx index cd19eb5a27d7b..965167f2c945e 100644 --- a/x-pack/plugins/security_solution/public/common/components/links/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/links/index.test.tsx @@ -7,7 +7,7 @@ import { mount, shallow, ReactWrapper, ShallowWrapper } from 'enzyme'; import React from 'react'; -import { removeExternalLinkText } from '../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import { mountWithIntl } from '@kbn/test/jest'; import { encodeIpv6 } from '../../lib/helpers'; diff --git a/x-pack/plugins/security_solution/public/common/components/markdown_editor/renderer.test.tsx b/x-pack/plugins/security_solution/public/common/components/markdown_editor/renderer.test.tsx index 490392c237e19..da3785648de62 100644 --- a/x-pack/plugins/security_solution/public/common/components/markdown_editor/renderer.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/markdown_editor/renderer.test.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { mount } from 'enzyme'; -import { removeExternalLinkText } from '../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import { MarkdownRenderer } from './renderer'; describe('Markdown', () => { diff --git a/x-pack/plugins/security_solution/public/common/components/threat_match/entry_delete_button.test.tsx b/x-pack/plugins/security_solution/public/common/components/threat_match/entry_delete_button.test.tsx index 9c30564699311..0e8edbf047528 100644 --- a/x-pack/plugins/security_solution/public/common/components/threat_match/entry_delete_button.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/threat_match/entry_delete_button.test.tsx @@ -7,7 +7,7 @@ import { mount } from 'enzyme'; import React from 'react'; -import { ThreatMappingEntries } from '../../../../common/detection_engine/schemas/types'; +import { ThreatMappingEntries } from '@kbn/securitysolution-io-ts-alerting-types'; import { EntryDeleteButtonComponent } from './entry_delete_button'; diff --git a/x-pack/plugins/security_solution/public/common/components/threat_match/helpers.test.tsx b/x-pack/plugins/security_solution/public/common/components/threat_match/helpers.test.tsx index 1d576dc6da32c..cf9407a6bf463 100644 --- a/x-pack/plugins/security_solution/public/common/components/threat_match/helpers.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/threat_match/helpers.test.tsx @@ -20,7 +20,7 @@ import { getFormattedEntry, getUpdatedEntriesOnDelete, } from './helpers'; -import { ThreatMapEntry } from '../../../../common/detection_engine/schemas/types'; +import { ThreatMapEntry } from '@kbn/securitysolution-io-ts-alerting-types'; jest.mock('uuid', () => ({ v4: jest.fn().mockReturnValue('123'), diff --git a/x-pack/plugins/security_solution/public/common/components/threat_match/helpers.tsx b/x-pack/plugins/security_solution/public/common/components/threat_match/helpers.tsx index ef3e9280e6e6b..232fac4ad8433 100644 --- a/x-pack/plugins/security_solution/public/common/components/threat_match/helpers.tsx +++ b/x-pack/plugins/security_solution/public/common/components/threat_match/helpers.tsx @@ -6,15 +6,11 @@ */ import uuid from 'uuid'; -import { - ThreatMap, - threatMap, - ThreatMapping, -} from '../../../../common/detection_engine/schemas/types'; +import { addIdToItem } from '@kbn/securitysolution-utils'; +import { ThreatMap, threatMap, ThreatMapping } from '@kbn/securitysolution-io-ts-alerting-types'; import { IndexPattern, IFieldType } from '../../../../../../../src/plugins/data/common'; import { Entry, FormattedEntry, ThreatMapEntries, EmptyEntry } from './types'; -import { addIdToItem } from '../../../../common/add_remove_id_to_item'; /** * Formats the entry into one that is easily usable for the UI. diff --git a/x-pack/plugins/security_solution/public/common/components/threat_match/index.tsx b/x-pack/plugins/security_solution/public/common/components/threat_match/index.tsx index 8bdbe7b1a3db8..3e4f0283145e4 100644 --- a/x-pack/plugins/security_solution/public/common/components/threat_match/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/threat_match/index.tsx @@ -9,7 +9,7 @@ import React, { useCallback, useEffect, useReducer } from 'react'; import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import styled from 'styled-components'; -import { ThreatMapping } from '../../../../common/detection_engine/schemas/types'; +import { ThreatMapping } from '@kbn/securitysolution-io-ts-alerting-types'; import { ListItemComponent } from './list_item'; import { IndexPattern } from '../../../../../../../src/plugins/data/common'; import { AndOrBadge } from '../and_or_badge'; diff --git a/x-pack/plugins/security_solution/public/common/components/threat_match/reducer.test.ts b/x-pack/plugins/security_solution/public/common/components/threat_match/reducer.test.ts index 8d1ae27ec6f7e..7c19b61efff02 100644 --- a/x-pack/plugins/security_solution/public/common/components/threat_match/reducer.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/threat_match/reducer.test.ts @@ -8,7 +8,7 @@ import { ThreatMapEntries } from './types'; import { State, reducer } from './reducer'; import { getDefaultEmptyEntry } from './helpers'; -import { ThreatMapEntry } from '../../../../common/detection_engine/schemas/types'; +import { ThreatMapEntry } from '@kbn/securitysolution-io-ts-alerting-types'; jest.mock('uuid', () => ({ v4: jest.fn().mockReturnValue('123'), diff --git a/x-pack/plugins/security_solution/public/common/components/threat_match/types.ts b/x-pack/plugins/security_solution/public/common/components/threat_match/types.ts index 0ea7727f2282a..3d4fa19ac5794 100644 --- a/x-pack/plugins/security_solution/public/common/components/threat_match/types.ts +++ b/x-pack/plugins/security_solution/public/common/components/threat_match/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { ThreatMap, ThreatMapEntry } from '../../../../common/detection_engine/schemas/types'; +import { ThreatMap, ThreatMapEntry } from '@kbn/securitysolution-io-ts-alerting-types'; import { IFieldType } from '../../../../../../../src/plugins/data/common'; export interface FormattedEntry { diff --git a/x-pack/plugins/security_solution/public/detections/components/host_isolation/index.tsx b/x-pack/plugins/security_solution/public/detections/components/host_isolation/index.tsx index 3897458e8459c..e6fd3a8459f76 100644 --- a/x-pack/plugins/security_solution/public/detections/components/host_isolation/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/host_isolation/index.tsx @@ -7,32 +7,19 @@ import React, { useMemo, useState, useCallback } from 'react'; import { find } from 'lodash/fp'; -import { - EuiCallOut, - EuiTitle, - EuiText, - EuiTextArea, - EuiSpacer, - EuiFlexGroup, - EuiFlexItem, - EuiButton, - EuiButtonEmpty, -} from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; +import { EuiText, EuiSpacer } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { useHostIsolation } from '../../containers/detection_engine/alerts/use_host_isolation'; -import { - CANCEL, - CASES_ASSOCIATED_WITH_ALERT, - COMMENT, - COMMENT_PLACEHOLDER, - CONFIRM, - RETURN_TO_ALERT_DETAILS, -} from './translations'; +import { CASES_ASSOCIATED_WITH_ALERT, RETURN_TO_ALERT_DETAILS } from './translations'; import { Maybe } from '../../../../../observability/common/typings'; import { useCasesFromAlerts } from '../../containers/detection_engine/alerts/use_cases_from_alerts'; import { CaseDetailsLink } from '../../../common/components/links'; import { TimelineEventsDetailsItem } from '../../../../common/search_strategy'; +import { + EndpointIsolatedFormProps, + EndpointIsolateForm, + EndpointIsolateSuccess, +} from '../../../common/components/endpoint/host_isolation'; export const HostIsolationPanel = React.memo( ({ @@ -76,6 +63,11 @@ export const HostIsolationPanel = React.memo( const backToAlertDetails = useCallback(() => cancelCallback(), [cancelCallback]); + const handleIsolateFormChange: EndpointIsolatedFormProps['onChange'] = useCallback( + ({ comment: newComment }) => setComment(newComment), + [] + ); + const casesList = useMemo( () => caseIds.map((id, index) => { @@ -100,43 +92,29 @@ export const HostIsolationPanel = React.memo( return ( <> - - {caseCount > 0 && ( - <> - -

- -

-
- -
    {casesList}
-
- - )} -
- - - - -

{RETURN_TO_ALERT_DETAILS}

-
-
-
-
+ 0 && ( + <> + +

+ +

+
+ +
    {casesList}
+
+ + ) + } + /> ); }, [backToAlertDetails, hostName, caseCount, casesList]); @@ -145,13 +123,18 @@ export const HostIsolationPanel = React.memo( return ( <> - -

+ {hostName}, cases: ( {caseCount} @@ -161,42 +144,19 @@ export const HostIsolationPanel = React.memo( ), }} /> -

-
- - -

{COMMENT}

-
- ) => - setComment(event.target.value) } /> - - - - {CANCEL} - - - - {CONFIRM} - - - ); }, [ - alertRule, + hostName, backToAlertDetails, - comment, confirmHostIsolation, - hostName, + handleIsolateFormChange, + comment, loading, caseCount, + alertRule, ]); return isIsolated ? hostIsolated : hostNotIsolated; diff --git a/x-pack/plugins/security_solution/public/detections/components/host_isolation/translations.ts b/x-pack/plugins/security_solution/public/detections/components/host_isolation/translations.ts index 8d6334f6c340d..027a97cc3846e 100644 --- a/x-pack/plugins/security_solution/public/detections/components/host_isolation/translations.ts +++ b/x-pack/plugins/security_solution/public/detections/components/host_isolation/translations.ts @@ -14,23 +14,6 @@ export const ISOLATE_HOST = i18n.translate( } ); -export const COMMENT = i18n.translate('xpack.securitySolution.endpoint.hostIsolation.comment', { - defaultMessage: 'Comment', -}); - -export const COMMENT_PLACEHOLDER = i18n.translate( - 'xpack.securitySolution.endpoint.hostIsolation.comment.placeholder', - { defaultMessage: 'You may leave an optional note here.' } -); - -export const CANCEL = i18n.translate('xpack.securitySolution.endpoint.hostIsolation.cancel', { - defaultMessage: 'Cancel', -}); - -export const CONFIRM = i18n.translate('xpack.securitySolution.endpoint.hostIsolation.confirm', { - defaultMessage: 'Confirm', -}); - export const CASES_ASSOCIATED_WITH_ALERT = (caseCount: number): string => i18n.translate( 'xpack.securitySolution.endpoint.hostIsolation.isolateHost.casesAssociatedWithAlert', 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 7b9c3f35ef57b..17162a2206fc3 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 @@ -22,12 +22,12 @@ import { isEmpty } from 'lodash/fp'; import React from 'react'; import styled from 'styled-components'; +import { ThreatMapping, Type } from '@kbn/securitysolution-io-ts-alerting-types'; import { MATCHES, AND, OR } from '../../../../common/components/threat_match/translations'; -import { ThreatMapping } from '../../../../../common/detection_engine/schemas/types'; import { assertUnreachable } from '../../../../../common/utility_types'; import * as i18nSeverity from '../severity_mapping/translations'; import * as i18nRiskScore from '../risk_score_mapping/translations'; -import { Threshold, Type } from '../../../../../common/detection_engine/schemas/common/schemas'; +import { Threshold } from '../../../../../common/detection_engine/schemas/common/schemas'; import { esFilters } from '../../../../../../../../src/plugins/data/public'; import { diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/index.tsx index 9c40853794743..ab84f1a65cc4b 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/index.tsx @@ -10,7 +10,7 @@ import { isEmpty, chunk, get, pick, isNumber } from 'lodash/fp'; import React, { memo, useState } from 'react'; import styled from 'styled-components'; -import { ThreatMapping } from '../../../../../common/detection_engine/schemas/types'; +import { ThreatMapping, Threats, Type } from '@kbn/securitysolution-io-ts-alerting-types'; import { IIndexPattern, Filter, @@ -39,7 +39,6 @@ import { import { buildMlJobsDescription } from './ml_job_description'; import { buildActionsDescription } from './actions_description'; import { buildThrottleDescription } from './throttle_description'; -import { Threats, Type } from '../../../../../common/detection_engine/schemas/common/schemas'; import { THREAT_QUERY_LABEL } from './translations'; import { filterEmptyThreats } from '../../../pages/detection_engine/rules/create/helpers'; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/types.ts b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/types.ts index 0e685da078226..dc5e7fea8e771 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/types.ts +++ b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/types.ts @@ -6,7 +6,7 @@ */ import { ReactNode } from 'react'; -import { Threats } from '../../../../../common/detection_engine/schemas/common/schemas'; +import { Threats } from '@kbn/securitysolution-io-ts-alerting-types'; import { IIndexPattern, diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/mitre/helpers.ts b/x-pack/plugins/security_solution/public/detections/components/rules/mitre/helpers.ts index b867d3d76cc70..6f5cb37d9f91f 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/mitre/helpers.ts +++ b/x-pack/plugins/security_solution/public/detections/components/rules/mitre/helpers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { ThreatTechnique } from '../../../../../common/detection_engine/schemas/common/schemas'; +import { ThreatTechnique } from '@kbn/securitysolution-io-ts-alerting-types'; import { subtechniquesOptions } from '../../../mitre/mitre_tactics_techniques'; /** 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 c39efa1409bc3..25eb7a65e0d1b 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 @@ -11,7 +11,7 @@ import React, { memo, useCallback, useMemo } from 'react'; import styled from 'styled-components'; import { isEqual } from 'lodash'; -import { Threat, Threats } from '../../../../../common/detection_engine/schemas/common/schemas'; +import { Threat, Threats } from '@kbn/securitysolution-io-ts-alerting-types'; import { tacticsOptions } from '../../../mitre/mitre_tactics_techniques'; import * as Rulei18n from '../../../pages/detection_engine/rules/translations'; import { FieldHook } from '../../../../shared_imports'; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/mitre/subtechnique_fields.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/mitre/subtechnique_fields.tsx index d283c19bd13da..7504a5d706f18 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/mitre/subtechnique_fields.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/mitre/subtechnique_fields.tsx @@ -17,10 +17,7 @@ import { camelCase } from 'lodash/fp'; import React, { useCallback, useMemo } from 'react'; import styled from 'styled-components'; -import { - Threats, - ThreatSubtechnique, -} from '../../../../../common/detection_engine/schemas/common/schemas'; +import { Threats, ThreatSubtechnique } from '@kbn/securitysolution-io-ts-alerting-types'; import { subtechniquesOptions } from '../../../mitre/mitre_tactics_techniques'; import * as Rulei18n from '../../../pages/detection_engine/rules/translations'; import { FieldHook } from '../../../../shared_imports'; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/mitre/technique_fields.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/mitre/technique_fields.tsx index 7f698740f5d3b..5a0fde1a739a3 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/mitre/technique_fields.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/mitre/technique_fields.tsx @@ -17,10 +17,7 @@ import { kebabCase, camelCase } from 'lodash/fp'; import React, { useCallback } from 'react'; import styled, { css } from 'styled-components'; -import { - Threats, - ThreatTechnique, -} from '../../../../../common/detection_engine/schemas/common/schemas'; +import { Threats, ThreatTechnique } from '@kbn/securitysolution-io-ts-alerting-types'; import { techniquesOptions } from '../../../mitre/mitre_tactics_techniques'; import * as Rulei18n from '../../../pages/detection_engine/rules/translations'; import { FieldHook } from '../../../../shared_imports'; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/query_preview/helpers.ts b/x-pack/plugins/security_solution/public/detections/components/rules/query_preview/helpers.ts index bc4888acc90ff..1d3135b8cb34a 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/query_preview/helpers.ts +++ b/x-pack/plugins/security_solution/public/detections/components/rules/query_preview/helpers.ts @@ -9,10 +9,10 @@ import { Position, ScaleType } from '@elastic/charts'; import { EuiSelectOption } from '@elastic/eui'; import { Unit } from '@elastic/datemath'; +import { Type, Language } from '@kbn/securitysolution-io-ts-alerting-types'; import * as i18n from './translations'; import { histogramDateTimeFormatter } from '../../../../common/components/utils'; import { ChartSeriesConfigs } from '../../../../common/components/charts/common'; -import { Type, Language } from '../../../../../common/detection_engine/schemas/common/schemas'; import { getQueryFilter } from '../../../../../common/detection_engine/get_query_filter'; import { FieldValueQueryBar } from '../query_bar'; import { ESQuery } from '../../../../../common/typed_json'; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/query_preview/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/query_preview/index.tsx index 70d292660388d..6342d468f5962 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/query_preview/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/query_preview/index.tsx @@ -20,11 +20,11 @@ import { } from '@elastic/eui'; import { debounce } from 'lodash/fp'; +import { Type } from '@kbn/securitysolution-io-ts-alerting-types'; import * as i18n from './translations'; import { useMatrixHistogram } from '../../../../common/containers/matrix_histogram'; import { MatrixHistogramType } from '../../../../../common/search_strategy/security_solution/matrix_histogram'; import { FieldValueQueryBar } from '../query_bar'; -import { Type } from '../../../../../common/detection_engine/schemas/common/schemas'; import { PreviewEqlQueryHistogram } from './eql_histogram'; import { useEqlPreview } from '../../../../common/hooks/eql/'; import { PreviewThresholdQueryHistogram } from './threshold_histogram'; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/query_preview/reducer.ts b/x-pack/plugins/security_solution/public/detections/components/rules/query_preview/reducer.ts index 2dff858d61c79..afddca63afcc6 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/query_preview/reducer.ts +++ b/x-pack/plugins/security_solution/public/detections/components/rules/query_preview/reducer.ts @@ -8,10 +8,10 @@ import { Unit } from '@elastic/datemath'; import { EuiSelectOption } from '@elastic/eui'; +import { Type, Language } from '@kbn/securitysolution-io-ts-alerting-types'; import * as i18n from './translations'; import { Filter } from '../../../../../../../../src/plugins/data/common/es_query'; import { ESQuery } from '../../../../../common/typed_json'; -import { Language, Type } from '../../../../../common/detection_engine/schemas/common/schemas'; import { FieldValueQueryBar } from '../query_bar'; import { formatDate } from '../../../../common/components/super_date_picker'; import { getInfoFromQueryBar, getTimeframeOptions } from './helpers'; 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 79c54a1cc0225..c02f7992a9b92 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 @@ -19,13 +19,13 @@ import { import React, { useCallback, useMemo } from 'react'; import styled from 'styled-components'; import { noop } from 'lodash/fp'; +import { RiskScoreMapping } from '@kbn/securitysolution-io-ts-alerting-types'; import * as i18n from './translations'; import { FieldHook } from '../../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; import { AboutStepRiskScore } from '../../../pages/detection_engine/rules/types'; import { FieldComponent } from '../../../../common/components/autocomplete/field'; import { IFieldType } from '../../../../../../../../src/plugins/data/common/index_patterns/fields'; import { IIndexPattern } from '../../../../../../../../src/plugins/data/common/index_patterns'; -import { RiskScoreMapping } from '../../../../../common/detection_engine/schemas/common/schemas'; const NestedContent = styled.div` margin-left: 24px; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/select_rule_type/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/select_rule_type/index.tsx index 5650c2c55488e..712166df2b539 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/select_rule_type/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/select_rule_type/index.tsx @@ -8,7 +8,7 @@ import React, { useCallback, useMemo } from 'react'; import { EuiCard, EuiFlexGrid, EuiFlexItem, EuiFormRow, EuiIcon } from '@elastic/eui'; -import { Type } from '../../../../../common/detection_engine/schemas/common/schemas'; +import { Type } from '@kbn/securitysolution-io-ts-alerting-types'; import { isMlRule } from '../../../../../common/machine_learning/helpers'; import { isThresholdRule, 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 d83ad8f4f4d26..8b8c9441e7eae 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 @@ -19,6 +19,11 @@ import { import { noop } from 'lodash/fp'; import React, { useCallback, useMemo } from 'react'; import styled from 'styled-components'; +import { + Severity, + SeverityMapping, + SeverityMappingItem, +} from '@kbn/securitysolution-io-ts-alerting-types'; import * as i18n from './translations'; import { FieldHook } from '../../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; import { SeverityOptionItem } from '../step_about_rule/data'; @@ -29,11 +34,6 @@ 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 NestedContent = styled.div` margin-left: 24px; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/data.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/data.tsx index 8a01d5b072fb6..264e499d9cf86 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/data.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/data.tsx @@ -10,7 +10,7 @@ import { EuiHealth } from '@elastic/eui'; import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; import React from 'react'; -import { Severity } from '../../../../../common/detection_engine/schemas/common/schemas'; +import { Severity } from '@kbn/securitysolution-io-ts-alerting-types'; import * as I18n from './translations'; export interface SeverityOptionItem { diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/transforms.ts b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/transforms.ts index 7eb91e259a72f..891e7f47c1b7e 100644 --- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/transforms.ts +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/transforms.ts @@ -6,7 +6,7 @@ */ import { flow } from 'fp-ts/lib/function'; -import { addIdToItem, removeIdFromItem } from '../../../../../common/add_remove_id_to_item'; +import { addIdToItem, removeIdFromItem } from '@kbn/securitysolution-utils'; import { CreateRulesSchema, UpdateRulesSchema, diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/types.ts b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/types.ts index 2c3d6484aebdd..338124ad5ce65 100644 --- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/types.ts +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/types.ts @@ -7,28 +7,28 @@ import * as t from 'io-ts'; +import { listArray } from '@kbn/securitysolution-io-ts-list-types'; +import { + risk_score_mapping, + threat_query, + threat_index, + threat_indicator_path, + threat_mapping, + threat_language, + threat_filters, + threats, + type, + severity_mapping, +} from '@kbn/securitysolution-io-ts-alerting-types'; import { SortOrder, author, building_block_type, license, - risk_score_mapping, rule_name_override, - severity_mapping, timestamp_override, threshold, - type, - threats, } from '../../../../../common/detection_engine/schemas/common/schemas'; -import { - listArray, - threat_query, - threat_index, - threat_indicator_path, - threat_mapping, - threat_language, - threat_filters, -} from '../../../../../common/detection_engine/schemas/types'; import { CreateRulesSchema, PatchRulesSchema, @@ -38,6 +38,7 @@ import { /** * Params is an "record", since it is a type of AlertActionParams which is action templates. * @see x-pack/plugins/alerting/common/alert.ts + * @deprecated Use the one from @kbn/security-io-ts-alerting-types */ export const action = t.exact( t.type({ diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/use_dissasociate_exception_list.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/use_dissasociate_exception_list.tsx index 1fc6ff607c47f..8807f02774e0e 100644 --- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/use_dissasociate_exception_list.tsx +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/use_dissasociate_exception_list.tsx @@ -7,8 +7,8 @@ import { useEffect, useState, useRef } from 'react'; +import { List } from '@kbn/securitysolution-io-ts-list-types'; import { HttpStart } from '../../../../../../../../src/core/public'; -import { List } from '../../../../../common/detection_engine/schemas/types/lists'; import { patchRule } from './api'; type Func = (lists: List[]) => void; diff --git a/x-pack/plugins/security_solution/public/detections/mitre/valid_threat_mock.ts b/x-pack/plugins/security_solution/public/detections/mitre/valid_threat_mock.ts index 70c340096f462..a7de7494e1116 100644 --- a/x-pack/plugins/security_solution/public/detections/mitre/valid_threat_mock.ts +++ b/x-pack/plugins/security_solution/public/detections/mitre/valid_threat_mock.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Threats } from '../../../common/detection_engine/schemas/common/schemas'; +import { Threats } from '@kbn/securitysolution-io-ts-alerting-types'; import { mockThreatData } from './mitre_tactics_techniques'; const { tactic, technique, subtechnique } = mockThreatData; 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 98d3dadc7bbcb..f018bc148d626 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 @@ -5,7 +5,7 @@ * 2.0. */ -import { List } from '../../../../../../common/detection_engine/schemas/types'; +import { List } from '@kbn/securitysolution-io-ts-list-types'; import { CreateRulesSchema } from '../../../../../../common/detection_engine/schemas/request'; import { Rule } from '../../../../containers/detection_engine/rules'; import { @@ -40,7 +40,7 @@ import { mockActionsStepRule, } from '../all/__mocks__/mock'; import { getThreatMock } from '../../../../../../common/detection_engine/schemas/types/threat.mock'; -import { Threat, Threats } from '../../../../../../common/detection_engine/schemas/common/schemas'; +import { Threat, Threats } from '@kbn/securitysolution-io-ts-alerting-types'; describe('helpers', () => { describe('getTimeTypeValue', () => { 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 29b63721513d4..5259b95a09ae6 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 @@ -9,20 +9,22 @@ import { has, isEmpty } from 'lodash/fp'; import moment from 'moment'; import deepmerge from 'deepmerge'; -import type { ExceptionListType, NamespaceType } from '@kbn/securitysolution-io-ts-list-types'; -import { NOTIFICATION_THROTTLE_NO_ACTIONS } from '../../../../../../common/constants'; -import { assertUnreachable } from '../../../../../../common/utility_types'; -import { transformAlertToRuleAction } from '../../../../../../common/detection_engine/transform_actions'; -import { List } from '../../../../../../common/detection_engine/schemas/types'; -import { ENDPOINT_LIST_ID } from '../../../../../shared_imports'; -import { Rule } from '../../../../containers/detection_engine/rules'; +import type { + ExceptionListType, + NamespaceType, + List, +} from '@kbn/securitysolution-io-ts-list-types'; import { Threats, ThreatSubtechnique, ThreatTechnique, Type, -} from '../../../../../../common/detection_engine/schemas/common/schemas'; - +} from '@kbn/securitysolution-io-ts-alerting-types'; +import { NOTIFICATION_THROTTLE_NO_ACTIONS } from '../../../../../../common/constants'; +import { assertUnreachable } from '../../../../../../common/utility_types'; +import { transformAlertToRuleAction } from '../../../../../../common/detection_engine/transform_actions'; +import { ENDPOINT_LIST_ID } from '../../../../../shared_imports'; +import { Rule } from '../../../../containers/detection_engine/rules'; import { AboutStepRule, DefineStepRule, 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 03688264bcf46..25785f6bbcb2d 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 @@ -12,6 +12,12 @@ import { useLocation } from 'react-router-dom'; import styled from 'styled-components'; import { EuiFlexItem } from '@elastic/eui'; +import { + Threats, + Type, + SeverityMapping, + Severity, +} from '@kbn/securitysolution-io-ts-alerting-types'; import { ActionVariables } from '../../../../../../triggers_actions_ui/public'; import { normalizeThresholdField } from '../../../../../common/detection_engine/utils'; import { RuleAlertAction } from '../../../../../common/detection_engine/types'; @@ -27,12 +33,6 @@ import { ScheduleStepRule, ActionsStepRule, } from './types'; -import { - SeverityMapping, - Type, - Severity, - Threats, -} from '../../../../../common/detection_engine/schemas/common/schemas'; import { severityOptions } from '../../../components/rules/step_about_rule/data'; export interface GetStepsData { diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/types.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/types.ts index 58994c5a5f556..cf82e7cb7944e 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/types.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/types.ts @@ -5,6 +5,16 @@ * 2.0. */ +import { List } from '@kbn/securitysolution-io-ts-list-types'; +import { + RiskScoreMapping, + ThreatIndex, + ThreatMapping, + Threats, + Type, + SeverityMapping, + Severity, +} from '@kbn/securitysolution-io-ts-alerting-types'; import { RuleAlertAction } from '../../../../../common/detection_engine/types'; import { AlertAction } from '../../../../../../alerting/common'; import { Filter } from '../../../../../../../../src/plugins/data/common'; @@ -15,20 +25,10 @@ import { Author, BuildingBlockType, License, - RiskScoreMapping, RuleNameOverride, - SeverityMapping, SortOrder, TimestampOverride, - Type, - Severity, - Threats, } from '../../../../../common/detection_engine/schemas/common/schemas'; -import { - List, - ThreatIndex, - ThreatMapping, -} from '../../../../../common/detection_engine/schemas/types'; export interface EuiBasicTableSortTypes { field: string; diff --git a/x-pack/plugins/security_solution/public/lists_plugin_deps.ts b/x-pack/plugins/security_solution/public/lists_plugin_deps.ts deleted file mode 100644 index 498995b538429..0000000000000 --- a/x-pack/plugins/security_solution/public/lists_plugin_deps.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -// DEPRECATED: Do not add exports to this file; please import from shared_imports instead - -export * from './shared_imports'; diff --git a/x-pack/plugins/security_solution/public/network/components/port/index.test.tsx b/x-pack/plugins/security_solution/public/network/components/port/index.test.tsx index 9c7a0833b24bb..ef1039bfc92e3 100644 --- a/x-pack/plugins/security_solution/public/network/components/port/index.test.tsx +++ b/x-pack/plugins/security_solution/public/network/components/port/index.test.tsx @@ -8,7 +8,7 @@ import { shallow } from 'enzyme'; import React from 'react'; -import { removeExternalLinkText } from '../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import '../../../common/mock/match_media'; import { TestProviders } from '../../../common/mock/test_providers'; import { useMountAppended } from '../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/network/components/source_destination/index.test.tsx b/x-pack/plugins/security_solution/public/network/components/source_destination/index.test.tsx index 6be0382e54cde..01065ad5bf15f 100644 --- a/x-pack/plugins/security_solution/public/network/components/source_destination/index.test.tsx +++ b/x-pack/plugins/security_solution/public/network/components/source_destination/index.test.tsx @@ -10,7 +10,7 @@ import { shallow } from 'enzyme'; import { get } from 'lodash/fp'; import React from 'react'; -import { removeExternalLinkText } from '../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import { asArrayIfExists } from '../../../common/lib/helpers'; import { getMockNetflowData } from '../../../common/mock'; import '../../../common/mock/match_media'; diff --git a/x-pack/plugins/security_solution/public/network/components/source_destination/source_destination_ip.test.tsx b/x-pack/plugins/security_solution/public/network/components/source_destination/source_destination_ip.test.tsx index a13621cfe3a9c..f767e793c8f21 100644 --- a/x-pack/plugins/security_solution/public/network/components/source_destination/source_destination_ip.test.tsx +++ b/x-pack/plugins/security_solution/public/network/components/source_destination/source_destination_ip.test.tsx @@ -8,7 +8,7 @@ import { get } from 'lodash/fp'; import React from 'react'; -import { removeExternalLinkText } from '../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import { asArrayIfExists } from '../../../common/lib/helpers'; import { getMockNetflowData } from '../../../common/mock'; import '../../../common/mock/match_media'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/certificate_fingerprint/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/certificate_fingerprint/index.test.tsx index 63e27bd8fa9c3..7a38c873450ca 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/certificate_fingerprint/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/certificate_fingerprint/index.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; -import { removeExternalLinkText } from '../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import { TestProviders } from '../../../common/mock'; import '../../../common/mock/match_media'; import { useMountAppended } from '../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/ja3_fingerprint/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/ja3_fingerprint/index.test.tsx index bb2061f744289..802dd74c1892b 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/ja3_fingerprint/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/ja3_fingerprint/index.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; -import { removeExternalLinkText } from '../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import { TestProviders } from '../../../common/mock'; import '../../../common/mock/match_media'; import { useMountAppended } from '../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/netflow/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/netflow/index.test.tsx index 5e6d804b01fde..e2c8b8854504a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/netflow/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/netflow/index.test.tsx @@ -9,7 +9,7 @@ import { get } from 'lodash/fp'; import React from 'react'; import { shallow } from 'enzyme'; -import { removeExternalLinkText } from '../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import { asArrayIfExists } from '../../../common/lib/helpers'; import { getMockNetflowData } from '../../../common/mock'; import '../../../common/mock/match_media'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/get_row_renderer.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/get_row_renderer.test.tsx index b92a4381d837b..56dbc99d47c66 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/get_row_renderer.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/get_row_renderer.test.tsx @@ -9,7 +9,7 @@ import { shallow } from 'enzyme'; import { cloneDeep } from 'lodash'; import React from 'react'; -import { removeExternalLinkText } from '../../../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import '../../../../../common/mock/match_media'; import { mockBrowserFields } from '../../../../../common/containers/source/mock'; import { Ecs } from '../../../../../../common/ecs'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_details.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_details.test.tsx index bd8c2d10ccfaf..5960f43174b98 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_details.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_details.test.tsx @@ -8,7 +8,7 @@ import { shallow } from 'enzyme'; import React from 'react'; -import { removeExternalLinkText } from '../../../../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { mockTimelineData } from '../../../../../../common/mock'; import '../../../../../../common/mock/match_media'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_row_renderer.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_row_renderer.test.tsx index 469c8f6c3ec4c..098d6775cfaa4 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_row_renderer.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_row_renderer.test.tsx @@ -9,7 +9,7 @@ import { shallow } from 'enzyme'; import { cloneDeep } from 'lodash/fp'; import React from 'react'; -import { removeExternalLinkText } from '../../../../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { Ecs } from '../../../../../../../common/ecs'; import { mockTimelineData } from '../../../../../../common/mock'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/generic_row_renderer.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/generic_row_renderer.test.tsx index b7857e6bf4585..8e8ce9cb2f988 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/generic_row_renderer.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/generic_row_renderer.test.tsx @@ -9,7 +9,7 @@ import { shallow } from 'enzyme'; import { cloneDeep } from 'lodash/fp'; import React from 'react'; -import { removeExternalLinkText } from '../../../../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import { BrowserFields } from '../../../../../../common/containers/source'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { Ecs } from '../../../../../../../common/ecs'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_details.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_details.test.tsx index 0f27dccd1aff0..04150163fb4d4 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_details.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_details.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; -import { removeExternalLinkText } from '../../../../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import '../../../../../../common/mock/match_media'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { mockTimelineData, TestProviders } from '../../../../../../common/mock'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_row_renderer.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_row_renderer.test.tsx index 2d20da0c5e6dc..749e450b36ae4 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_row_renderer.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_row_renderer.test.tsx @@ -9,7 +9,7 @@ import { shallow } from 'enzyme'; import { cloneDeep } from 'lodash/fp'; import React from 'react'; -import { removeExternalLinkText } from '../../../../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { Ecs } from '../../../../../../../common/ecs'; import { mockTimelineData, TestProviders } from '../../../../../../common/mock'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_signature.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_signature.test.tsx index 4fc2f90c87da4..61155331b1a4b 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_signature.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_signature.test.tsx @@ -9,7 +9,7 @@ import { shallow } from 'enzyme'; import { cloneDeep } from 'lodash/fp'; import React from 'react'; -import { removeExternalLinkText } from '../../../../../../../common/test_utils'; +import { removeExternalLinkText } from '@kbn/securitysolution-io-ts-utils'; import '../../../../../../common/mock/match_media'; import { Ecs } from '../../../../../../../common/ecs'; import { mockTimelineData, TestProviders } from '../../../../../../common/mock'; 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 f3bc195b5a896..e73e3eb5c56f8 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 @@ -8,8 +8,8 @@ import { createHash } from 'crypto'; import { deflate } from 'zlib'; import { Entry, EntryNested } from '@kbn/securitysolution-io-ts-list-types'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; import { ExceptionListItemSchema } from '../../../../../lists/common/schemas'; -import { validate } from '../../../../common/validate'; import { ExceptionListClient } from '../../../../../lists/server'; import { ENDPOINT_LIST_ID, ENDPOINT_TRUSTED_APPS_LIST_ID } from '../../../../common/shared_imports'; 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 7e1accac37cf0..43d4fc49161bb 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 @@ -7,7 +7,7 @@ import { flatMap, isEqual } from 'lodash'; import semver from 'semver'; -import { validate } from '../../../../common'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; import { InternalArtifactSchema, InternalManifestSchema, diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/mapping.ts b/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/mapping.ts index e4704523a16c3..897ffe4ee48cd 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/mapping.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/trusted_apps/mapping.ts @@ -13,11 +13,11 @@ import type { EntryMatchWildcard, EntryNested, NestedEntriesArray, + OsType, } from '@kbn/securitysolution-io-ts-list-types'; import type { ExceptionListItemSchema } from '../../../../../lists/common'; -import type { OsType } from '../../../../../lists/common/schemas'; import { ENDPOINT_TRUSTED_APPS_LIST_ID } from '../../../../../lists/common/constants'; import type { CreateExceptionListItemOptions, diff --git a/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/lists.ts b/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/lists.ts index 1b1370472f633..3a37bfbe9320c 100644 --- a/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/lists.ts +++ b/x-pack/plugins/security_solution/server/endpoint/schemas/artifacts/lists.ts @@ -6,7 +6,7 @@ */ import * as t from 'io-ts'; -import { operator } from '../../../../../lists/common/schemas'; +import { listOperator as operator } from '@kbn/securitysolution-io-ts-list-types'; export const translatedEntryMatchAnyMatcher = t.keyof({ exact_cased_any: null, 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 e2f6118f4f0a7..d7b05ffa5592e 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 @@ -10,11 +10,11 @@ import { SavedObjectsClientContract, SavedObjectsUpdateResponse, } from 'src/core/server'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; import { manifestSchemaVersion, ManifestSchemaVersion, } from '../../../../common/endpoint/schema/common'; -import { validate } from '../../../../common/validate'; import { ManifestConstants } from '../../lib/artifacts'; import { InternalManifestSchema, InternalManifestCreateSchema } from '../../schemas/artifacts'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/create_bootstrap_index.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/index/create_bootstrap_index.ts deleted file mode 100644 index 02f8f3f7b36ab..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/create_bootstrap_index.ts +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ElasticsearchClient } from 'kibana/server'; - -// See the reference(s) below on explanations about why -000001 was chosen and -// why the is_write_index is true as well as the bootstrapping step which is needed. -// Ref: https://www.elastic.co/guide/en/elasticsearch/reference/current/applying-policy-to-template.html - -/** - * @deprecated Use the one from kbn-securitysolution-es-utils - */ -export const createBootstrapIndex = async ( - esClient: ElasticsearchClient, - index: string -): Promise => { - return ( - await esClient.transport.request({ - path: `/${index}-000001`, - method: 'PUT', - body: { - aliases: { - [index]: { - is_write_index: true, - }, - }, - }, - }) - ).body; -}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/delete_all_index.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/index/delete_all_index.ts deleted file mode 100644 index d76290921fac8..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/delete_all_index.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ElasticsearchClient } from 'kibana/server'; - -/** - * @deprecated Use the one from kbn-securitysolution-es-utils - */ -export const deleteAllIndex = async ( - esClient: ElasticsearchClient, - pattern: string, - maxAttempts = 5 -): Promise => { - for (let attempt = 1; ; attempt++) { - if (attempt > maxAttempts) { - throw new Error( - `Failed to delete indexes with pattern [${pattern}] after ${maxAttempts} attempts` - ); - } - - // resolve pattern to concrete index names - const { body: resp } = await esClient.indices.getAlias( - { - index: pattern, - }, - { ignore: [404] } - ); - - // @ts-expect-error status doesn't exist on response - if (resp.status === 404) { - return true; - } - - const indices = Object.keys(resp) as string[]; - - // if no indexes exits then we're done with this pattern - if (!indices.length) { - return true; - } - - // delete the concrete indexes we found and try again until this pattern resolves to no indexes - await esClient.indices.delete({ - index: indices, - ignore_unavailable: true, - }); - } -}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/delete_policy.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/index/delete_policy.ts deleted file mode 100644 index 924970d304c88..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/delete_policy.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ElasticsearchClient } from 'kibana/server'; - -/** - * @deprecated Use the one from kbn-securitysolution-es-utils - */ -export const deletePolicy = async ( - esClient: ElasticsearchClient, - policy: string -): Promise => { - return ( - await esClient.transport.request({ - path: `/_ilm/policy/${policy}`, - method: 'DELETE', - }) - ).body; -}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/delete_template.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/index/delete_template.ts deleted file mode 100644 index 5466fd03f534c..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/delete_template.ts +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ -import { ElasticsearchClient } from 'kibana/server'; - -/** - * @deprecated Use the one from kbn-securitysolution-es-utils - */ -export const deleteTemplate = async ( - esClient: ElasticsearchClient, - name: string -): Promise => { - return ( - await esClient.indices.deleteTemplate({ - name, - }) - ).body; -}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_exists.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_exists.test.ts deleted file mode 100644 index abe587ec825c0..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_exists.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks'; -import { getIndexExists } from './get_index_exists'; - -class StatusCode extends Error { - status: number = -1; - constructor(status: number, message: string) { - super(message); - this.status = status; - } -} - -describe('get_index_exists', () => { - test('it should return a true if you have _shards', async () => { - const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser; - esClient.search.mockReturnValue( - // @ts-expect-error not full interface - elasticsearchClientMock.createSuccessTransportRequestPromise({ _shards: { total: 1 } }) - ); - const indexExists = await getIndexExists(esClient, 'some-index'); - expect(indexExists).toEqual(true); - }); - - test('it should return a false if you do NOT have _shards', async () => { - const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser; - esClient.search.mockReturnValue( - // @ts-expect-error not full interface - elasticsearchClientMock.createSuccessTransportRequestPromise({ _shards: { total: 0 } }) - ); - const indexExists = await getIndexExists(esClient, 'some-index'); - expect(indexExists).toEqual(false); - }); - - test('it should return a false if it encounters a 404', async () => { - const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser; - esClient.search.mockReturnValue( - elasticsearchClientMock.createErrorTransportRequestPromise({ - body: new StatusCode(404, 'I am a 404 error'), - }) - ); - const indexExists = await getIndexExists(esClient, 'some-index'); - expect(indexExists).toEqual(false); - }); - - test('it should reject if it encounters a non 404', async () => { - const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser; - esClient.search.mockReturnValue( - elasticsearchClientMock.createErrorTransportRequestPromise( - new StatusCode(500, 'I am a 500 error') - ) - ); - await expect(getIndexExists(esClient, 'some-index')).rejects.toThrow('I am a 500 error'); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_exists.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_exists.ts deleted file mode 100644 index 7ca7f9818ba0b..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_exists.ts +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ElasticsearchClient } from 'kibana/server'; - -/** - * @deprecated Use the one from kbn-securitysolution-es-utils - */ -export const getIndexExists = async ( - esClient: ElasticsearchClient, - index: string -): Promise => { - try { - const { body: response } = await esClient.search({ - index, - size: 0, - allow_no_indices: true, - body: { - terminate_after: 1, - }, - }); - return response._shards.total > 0; - } catch (err) { - if (err.body?.status === 404) { - return false; - } else { - throw err.body ? err.body : err; - } - } -}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_policy_exists.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_policy_exists.ts deleted file mode 100644 index 6ebdac0d244cb..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_policy_exists.ts +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ElasticsearchClient } from 'kibana/server'; - -/** - * @deprecated Use the one from kbn-securitysolution-es-utils - */ -export const getPolicyExists = async ( - esClient: ElasticsearchClient, - policy: string -): Promise => { - try { - await esClient.transport.request({ - path: `/_ilm/policy/${policy}`, - method: 'GET', - }); - // Return true that there exists a policy which is not 404 or some error - // Since there is not a policy exists API, this is how we create one by calling - // into the API to get it if it exists or rely on it to throw a 404 - return true; - } catch (err) { - if (err.statusCode === 404) { - return false; - } else { - throw err; - } - } -}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_template_exists.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_template_exists.ts deleted file mode 100644 index af5f874a05688..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/get_template_exists.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ElasticsearchClient } from 'kibana/server'; - -/** - * @deprecated Use the one from kbn-securitysolution-es-utils - */ -export const getTemplateExists = async ( - esClient: ElasticsearchClient, - template: string -): Promise => { - return ( - await esClient.indices.existsTemplate({ - name: template, - }) - ).body; -}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/set_policy.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/index/set_policy.ts deleted file mode 100644 index 113b9d368e0d9..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/set_policy.ts +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ElasticsearchClient } from 'kibana/server'; - -/** - * @deprecated Use the one from kbn-securitysolution-es-utils - */ -export const setPolicy = async ( - esClient: ElasticsearchClient, - policy: string, - body: Record -): Promise => { - return ( - await esClient.transport.request({ - path: `/_ilm/policy/${policy}`, - method: 'PUT', - body, - }) - ).body; -}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/index/set_template.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/index/set_template.ts deleted file mode 100644 index 288377c306325..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/index/set_template.ts +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ElasticsearchClient } from 'kibana/server'; - -/** - * @deprecated Use the one from kbn-securitysolution-es-utils - */ -export const setTemplate = async ( - esClient: ElasticsearchClient, - name: string, - body: Record -): Promise => { - return ( - await esClient.indices.putTemplate({ - name, - body, - }) - ).body; -}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/create_migration_saved_object.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/create_migration_saved_object.ts index 9c1154f19e8dc..3aee9db31bf1b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/create_migration_saved_object.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/create_migration_saved_object.ts @@ -9,7 +9,7 @@ import { chain, tryCatch } from 'fp-ts/lib/TaskEither'; import { pipe } from 'fp-ts/lib/pipeable'; import { SavedObjectsClientContract } from 'src/core/server'; -import { validateTaskEither } from '../../../../common/validate'; +import { validateTaskEither } from '@kbn/securitysolution-io-ts-utils'; import { toError, toPromise } from '../../../../common/fp_utils'; import { signalsMigrationSOClient } from './saved_objects_client'; import { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/finalize_migration.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/finalize_migration.test.ts index bdc22f2ff20ce..46de2eb133bac 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/finalize_migration.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/finalize_migration.test.ts @@ -6,13 +6,13 @@ */ import { elasticsearchServiceMock, savedObjectsClientMock } from 'src/core/server/mocks'; -import { getIndexCount } from '../index/get_index_count'; +import { getIndexCount } from '@kbn/securitysolution-es-utils'; import { updateMigrationSavedObject } from './update_migration_saved_object'; import { getSignalsMigrationSavedObjectMock } from './saved_objects_schema.mock'; import { finalizeMigration } from './finalize_migration'; jest.mock('./update_migration_saved_object'); -jest.mock('../index/get_index_count'); +jest.mock('@kbn/securitysolution-es-utils'); describe('finalizeMigration', () => { let esClient: ReturnType; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/finalize_migration.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/finalize_migration.ts index 7a52470e58051..ca8ae01ee2d1f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/finalize_migration.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/finalize_migration.ts @@ -6,7 +6,7 @@ */ import { ElasticsearchClient, SavedObjectsClientContract } from 'src/core/server'; -import { getIndexCount } from '../index/get_index_count'; +import { getIndexCount } from '@kbn/securitysolution-es-utils'; import { isMigrationPending } from './helpers'; import { applyMigrationCleanupPolicy } from './migration_cleanup'; import { replaceSignalsIndexAlias } from './replace_signals_index_alias'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/find_migration_saved_objects.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/find_migration_saved_objects.ts index 2a3e25ee57aa2..2cc73c36500f2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/find_migration_saved_objects.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/find_migration_saved_objects.ts @@ -9,9 +9,9 @@ import { fold } from 'fp-ts/lib/Either'; import { pipe } from 'fp-ts/lib/pipeable'; import { SavedObjectsClientContract, SavedObjectsFindOptions } from 'src/core/server'; +import { validateEither } from '@kbn/securitysolution-io-ts-utils'; import { signalsMigrationSOClient } from './saved_objects_client'; import { SignalsMigrationSO, signalsMigrationSOs } from './saved_objects_schema'; -import { validateEither } from '../../../../common/validate'; export const findMigrationSavedObjects = async ({ options, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/get_migration_saved_objects_by_id.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/get_migration_saved_objects_by_id.ts index 7d66dca2ef192..66bbc01ef0d68 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/get_migration_saved_objects_by_id.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/get_migration_saved_objects_by_id.ts @@ -9,7 +9,7 @@ import { fold } from 'fp-ts/lib/Either'; import { pipe } from 'fp-ts/lib/pipeable'; import { SavedObjectsClientContract } from 'src/core/server'; -import { validateEither } from '../../../../common/validate'; +import { validateEither } from '@kbn/securitysolution-io-ts-utils'; import { signalsMigrationSOClient } from './saved_objects_client'; import { SignalsMigrationSO, signalsMigrationSOs } from './saved_objects_schema'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/saved_objects_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/saved_objects_schema.ts index 3ce798ec5a5c1..e81583b825e39 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/saved_objects_schema.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/saved_objects_schema.ts @@ -7,7 +7,7 @@ import * as t from 'io-ts'; -import { IsoDateString, PositiveInteger } from '../../../../common/detection_engine/schemas/types'; +import { IsoDateString, PositiveInteger } from '@kbn/securitysolution-io-ts-types'; import { unionWithNullType } from '../../../../common/utility_types'; const status = t.keyof({ success: null, failure: null, pending: null }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/update_migration_saved_object.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/update_migration_saved_object.ts index 05d7d3e50dca7..5bd8b47c3b74a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/update_migration_saved_object.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/update_migration_saved_object.ts @@ -9,7 +9,7 @@ import { chain, tryCatch } from 'fp-ts/lib/TaskEither'; import { pipe } from 'fp-ts/lib/pipeable'; import { SavedObjectsClientContract, SavedObjectsUpdateResponse } from 'src/core/server'; -import { validateTaskEither } from '../../../../common/validate'; +import { validateTaskEither } from '@kbn/securitysolution-io-ts-utils'; import { toError, toPromise } from '../../../../common/fp_utils'; import { signalsMigrationSOClient } from './saved_objects_client'; import { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/create_index_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/create_index_route.ts index cd1b77862af04..d98cd7cea0f2b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/create_index_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/create_index_route.ts @@ -5,19 +5,22 @@ * 2.0. */ +import { + transformError, + getIndexExists, + getPolicyExists, + setPolicy, + setTemplate, + createBootstrapIndex, +} from '@kbn/securitysolution-es-utils'; import type { AppClient, SecuritySolutionPluginRouter, SecuritySolutionRequestHandlerContext, } from '../../../../types'; import { DETECTION_ENGINE_INDEX_URL } from '../../../../../common/constants'; -import { transformError, buildSiemResponse } from '../utils'; -import { getIndexExists } from '../../index/get_index_exists'; -import { getPolicyExists } from '../../index/get_policy_exists'; -import { setPolicy } from '../../index/set_policy'; -import { setTemplate } from '../../index/set_template'; +import { buildSiemResponse } from '../utils'; import { getSignalsTemplate, SIGNALS_TEMPLATE_VERSION } from './get_signals_template'; -import { createBootstrapIndex } from '../../index/create_bootstrap_index'; import { ensureMigrationCleanupPolicy } from '../../migrations/migration_cleanup'; import signalsPolicy from './signals_policy.json'; import { templateNeedsUpdate } from './check_template_version'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/delete_index_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/delete_index_route.ts index 1a4f00a570424..5260c9487de8a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/delete_index_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/delete_index_route.ts @@ -5,15 +5,18 @@ * 2.0. */ +import { + transformError, + getIndexExists, + getPolicyExists, + deletePolicy, + getTemplateExists, + deleteAllIndex, + deleteTemplate, +} from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_INDEX_URL } from '../../../../../common/constants'; -import { transformError, buildSiemResponse } from '../utils'; -import { getIndexExists } from '../../index/get_index_exists'; -import { getPolicyExists } from '../../index/get_policy_exists'; -import { deletePolicy } from '../../index/delete_policy'; -import { getTemplateExists } from '../../index/get_template_exists'; -import { deleteAllIndex } from '../../index/delete_all_index'; -import { deleteTemplate } from '../../index/delete_template'; +import { buildSiemResponse } from '../utils'; /** * Deletes all of the indexes, template, ilm policies, and aliases. You can check diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/get_index_version.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/get_index_version.ts index b333ef999a6ae..b6f711fc319fb 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/get_index_version.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/get_index_version.ts @@ -6,8 +6,8 @@ */ import { get } from 'lodash'; +import { readIndex } from '@kbn/securitysolution-es-utils'; import { ElasticsearchClient } from '../../../../../../../../src/core/server'; -import { readIndex } from '../../index/read_index'; export const getIndexVersion = async ( esClient: ElasticsearchClient, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/read_index_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/read_index_route.ts index 01d07f68aa489..6af4397a4193a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/read_index_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/read_index_route.ts @@ -5,10 +5,11 @@ * 2.0. */ +import { transformError, getIndexExists } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_INDEX_URL } from '../../../../../common/constants'; -import { transformError, buildSiemResponse } from '../utils'; -import { getIndexExists } from '../../index/get_index_exists'; + +import { buildSiemResponse } from '../utils'; import { SIGNALS_TEMPLATE_VERSION } from './get_signals_template'; import { getIndexVersion } from './get_index_version'; import { isOutdated } from '../../migrations/helpers'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.ts index f006d9250d369..04fd2aeaebb2d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/privileges/read_privileges_route.ts @@ -7,9 +7,11 @@ import { merge } from 'lodash/fp'; +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_PRIVILEGES_URL } from '../../../../../common/constants'; -import { buildSiemResponse, transformError } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { readPrivileges } from '../../privileges/read_privileges'; export const readPrivilegesRoute = ( diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts index 4f9bd7d0cfd6c..03d357ab10bb9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts @@ -6,13 +6,14 @@ */ import moment from 'moment'; +import { transformError, getIndexExists } from '@kbn/securitysolution-es-utils'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; import type { AppClient, SecuritySolutionPluginRouter, SecuritySolutionRequestHandlerContext, } from '../../../../types'; -import { validate } from '../../../../../common/validate'; import { PrePackagedRulesAndTimelinesSchema, prePackagedRulesAndTimelinesSchema, @@ -24,7 +25,6 @@ import { ConfigType } from '../../../../config'; import { SetupPlugins } from '../../../../plugin'; import { buildFrameworkRequest } from '../../../timeline/utils/common'; -import { getIndexExists } from '../../index/get_index_exists'; import { getLatestPrepackagedRules } from '../../rules/get_prepackaged_rules'; import { installPrepackagedRules } from '../../rules/install_prepacked_rules'; import { updatePrepackagedRules } from '../../rules/update_prepacked_rules'; @@ -33,7 +33,7 @@ import { getRulesToUpdate } from '../../rules/get_rules_to_update'; import { getExistingPrepackagedRules } from '../../rules/get_existing_prepackaged_rules'; import { ruleAssetSavedObjectsClientFactory } from '../../rules/rule_asset_saved_objects_client'; -import { transformError, buildSiemResponse } from '../utils'; +import { buildSiemResponse } from '../utils'; import { AlertsClient } from '../../../../../../alerting/server'; import { FrameworkRequest } from '../../../framework'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts index cd0e1883e78f5..500c74e47ea7d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts @@ -5,7 +5,8 @@ * 2.0. */ -import { validate } from '../../../../../common/validate'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; +import { getIndexExists } from '@kbn/securitysolution-es-utils'; import { createRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/create_rules_type_dependents'; import { createRulesBulkSchema } from '../../../../../common/detection_engine/schemas/request/create_rules_bulk_schema'; import { rulesBulkSchema } from '../../../../../common/detection_engine/schemas/response/rules_bulk_schema'; @@ -17,7 +18,6 @@ import { throwHttpError } from '../../../machine_learning/validation'; import { readRules } from '../../rules/read_rules'; import { getDuplicates } from './utils'; import { transformValidateBulkError } from './validate'; -import { getIndexExists } from '../../index/get_index_exists'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import { transformBulkError, createBulkErrorObject, buildSiemResponse } from '../utils'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts index 1e34bbbbe4749..9b7e7bb42f423 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError, getIndexExists } from '@kbn/securitysolution-es-utils'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; @@ -12,8 +13,8 @@ import type { SecuritySolutionPluginRouter } from '../../../../types'; import { buildMlAuthz } from '../../../machine_learning/authz'; import { throwHttpError } from '../../../machine_learning/validation'; import { readRules } from '../../rules/read_rules'; -import { getIndexExists } from '../../index/get_index_exists'; -import { transformError, buildSiemResponse } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { updateRulesNotifications } from '../../rules/update_rules_notifications'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; import { createRulesSchema } from '../../../../../common/detection_engine/schemas/request'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts index 9739eb7ba9e00..1e7ba976d6915 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { validate } from '../../../../../common/validate'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; import { queryRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/query_rules_type_dependents'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts index 3bd7c7f8730b3..76fb9ac0c77e3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import { queryRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/query_rules_type_dependents'; import { queryRulesSchema, @@ -15,7 +16,8 @@ import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { deleteRules } from '../../rules/delete_rules'; import { getIdError, transform } from './utils'; -import { transformError, buildSiemResponse } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { deleteNotifications } from '../../notifications/delete_notifications'; import { deleteRuleActionsSavedObject } from '../../rule_actions/delete_rule_actions_saved_object'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts index 8fe20e4db612c..cb1c1feba5295 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import { exportRulesQuerySchema, ExportRulesQuerySchemaDecoded, @@ -18,7 +19,7 @@ import { ConfigType } from '../../../../config'; import { getNonPackagedRulesCount } from '../../rules/get_existing_prepackaged_rules'; import { getExportByObjectIds } from '../../rules/get_export_by_object_ids'; import { getExportAll } from '../../rules/get_export_all'; -import { transformError, buildSiemResponse } from '../utils'; +import { buildSiemResponse } from '../utils'; export const exportRulesRoute = (router: SecuritySolutionPluginRouter, config: ConfigType) => { router.post( diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts index 005266f5c178f..ccf0a59e87c74 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import { findRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/find_rules_type_dependents'; import { findRulesSchema, @@ -13,7 +14,8 @@ import { import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { findRules } from '../../rules/find_rules'; -import { transformError, buildSiemResponse } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { getRuleActionsSavedObject } from '../../rule_actions/get_rule_actions_saved_object'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts index cb436b89af01f..bd6e8fc9e7aad 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts @@ -5,11 +5,13 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { RuleStatusResponse } from '../../rules/types'; -import { transformError, buildSiemResponse, mergeStatuses, getFailingRules } from '../utils'; +import { buildSiemResponse, mergeStatuses, getFailingRules } from '../utils'; + import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; import { findRulesStatusesSchema, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts index 33f9746fe9245..cd02cc72ba40c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts @@ -5,14 +5,16 @@ * 2.0. */ -import { validate } from '../../../../../common/validate'; +import { transformError } from '@kbn/securitysolution-es-utils'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; import { PrePackagedRulesAndTimelinesStatusSchema, prePackagedRulesAndTimelinesStatusSchema, } from '../../../../../common/detection_engine/schemas/response/prepackaged_rules_status_schema'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_PREPACKAGED_URL } from '../../../../../common/constants'; -import { transformError, buildSiemResponse } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { getRulesToInstall } from '../../rules/get_rules_to_install'; import { getRulesToUpdate } from '../../rules/get_rules_to_update'; import { findRules } from '../../rules/find_rules'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts index b37cc41f1439e..8e322405280d3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts @@ -10,7 +10,8 @@ import { extname } from 'path'; import { schema } from '@kbn/config-schema'; import { createPromiseFromStreams } from '@kbn/utils'; -import { validate } from '../../../../../common/validate'; +import { transformError, getIndexExists } from '@kbn/securitysolution-es-utils'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; import { importRulesQuerySchema, ImportRulesQuerySchemaDecoded, @@ -29,16 +30,15 @@ import { buildMlAuthz } from '../../../machine_learning/authz'; import { throwHttpError } from '../../../machine_learning/validation'; import { createRules } from '../../rules/create_rules'; import { readRules } from '../../rules/read_rules'; -import { getIndexExists } from '../../index/get_index_exists'; import { createBulkErrorObject, ImportRuleResponse, BulkError, isBulkError, isImportRegular, - transformError, buildSiemResponse, } from '../utils'; + import { patchRules } from '../../rules/patch_rules'; import { getTupleDuplicateErrorsAndUniqueRules } from './utils'; import { createRulesStreamFromNdJson } from '../../rules/create_rules_stream_from_ndjson'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts index 7d7124259af06..7eb01e8b0d402 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { validate } from '../../../../../common/validate'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; import { RuleAlertAction } from '../../../../../common/detection_engine/types'; import { patchRulesBulkSchema, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts index fd5c33f126fef..780c248183ab9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import { RuleAlertAction } from '../../../../../common/detection_engine/types'; import { patchRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/patch_rules_type_dependents'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; @@ -18,7 +19,8 @@ import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; import { throwHttpError } from '../../../machine_learning/validation'; import { patchRules } from '../../rules/patch_rules'; -import { transformError, buildSiemResponse } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { getIdError } from './utils'; import { transformValidate } from './validate'; import { updateRulesNotifications } from '../../rules/update_rules_notifications'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts index b2dd9ea8fb796..ac45e5d2ed3b2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import { queryRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/query_rules_type_dependents'; import { queryRulesSchema, @@ -14,7 +15,8 @@ import { buildRouteValidation } from '../../../../utils/build_validation/route_v import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { getIdError, transform } from './utils'; -import { transformError, buildSiemResponse } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { readRules } from '../../rules/read_rules'; import { getRuleActionsSavedObject } from '../../rule_actions/get_rule_actions_saved_object'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts index d088795a118b3..4c59ae2ba442e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { validate } from '../../../../../common/validate'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; import { updateRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/update_rules_type_dependents'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import { updateRulesBulkSchema } from '../../../../../common/detection_engine/schemas/request/update_rules_bulk_schema'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts index b883b7b3462e7..aad0068758f7d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import { updateRulesSchema } from '../../../../../common/detection_engine/schemas/request'; import { updateRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/update_rules_type_dependents'; import type { SecuritySolutionPluginRouter } from '../../../../types'; @@ -12,7 +13,8 @@ import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; import { throwHttpError } from '../../../machine_learning/validation'; -import { transformError, buildSiemResponse } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { getIdError } from './utils'; import { transformValidate } from './validate'; import { updateRules } from '../../rules/update_rules'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/utils.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/utils.test.ts index b841507bc7a6b..f2788ab1bd4c9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/utils.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/utils.test.ts @@ -32,7 +32,7 @@ import { createRulesStreamFromNdJson } from '../../rules/create_rules_stream_fro import { RuleAlertType } from '../../rules/types'; import { ImportRulesSchemaDecoded } from '../../../../../common/detection_engine/schemas/request/import_rules_schema'; import { getCreateRulesSchemaMock } from '../../../../../common/detection_engine/schemas/request/rule_schemas.mock'; -import { ThreatMapping } from '../../../../../common/detection_engine/schemas/types/threat_mapping'; +import { ThreatMapping } from '@kbn/securitysolution-io-ts-alerting-types'; import { CreateRulesBulkSchema } from '../../../../../common/detection_engine/schemas/request'; import { getMlRuleParams, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/validate.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/validate.ts index ac9ac960d6f06..d27208de487df 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/validate.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/validate.ts @@ -7,11 +7,11 @@ import { SavedObject, SavedObjectsFindResponse } from 'kibana/server'; +import { validateNonExact } from '@kbn/securitysolution-io-ts-utils'; import { FullResponseSchema, fullResponseSchema, } from '../../../../../common/detection_engine/schemas/request'; -import { validateNonExact } from '../../../../../common/validate'; import { RulesSchema, rulesSchema, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/create_signals_migration_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/create_signals_migration_route.test.ts index aed15b66b9bb5..f10907f7c0c02 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/create_signals_migration_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/create_signals_migration_route.test.ts @@ -13,13 +13,19 @@ import { getCreateSignalsMigrationSchemaMock } from '../../../../../common/detec import { getIndexVersionsByIndex } from '../../migrations/get_index_versions_by_index'; import { getSignalVersionsByIndex } from '../../migrations/get_signal_versions_by_index'; import { createMigration } from '../../migrations/create_migration'; -import { getIndexAliases } from '../../index/get_index_aliases'; +import { getIndexAliases } from '@kbn/securitysolution-es-utils'; import { getTemplateVersion } from '../index/check_template_version'; import { createSignalsMigrationRoute } from './create_signals_migration_route'; import { SIGNALS_TEMPLATE_VERSION } from '../index/get_signals_template'; jest.mock('../index/check_template_version'); -jest.mock('../../index/get_index_aliases'); +jest.mock('@kbn/securitysolution-es-utils', () => { + const original = jest.requireActual('@kbn/securitysolution-es-utils'); + return { + ...original, + getIndexAliases: jest.fn(), + }; +}); jest.mock('../../migrations/create_migration'); jest.mock('../../migrations/get_index_versions_by_index'); jest.mock('../../migrations/get_signal_versions_by_index'); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/create_signals_migration_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/create_signals_migration_route.ts index 99732930234ae..6dd2534870dc2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/create_signals_migration_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/create_signals_migration_route.ts @@ -5,16 +5,16 @@ * 2.0. */ +import { transformError, BadRequestError, getIndexAliases } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { SetupPlugins } from '../../../../plugin'; import { DETECTION_ENGINE_SIGNALS_MIGRATION_URL } from '../../../../../common/constants'; import { createSignalsMigrationSchema } from '../../../../../common/detection_engine/schemas/request/create_signals_migration_schema'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; -import { buildSiemResponse, transformError } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { getTemplateVersion } from '../index/check_template_version'; import { isOutdated, signalsAreOutdated } from '../../migrations/helpers'; -import { getIndexAliases } from '../../index/get_index_aliases'; -import { BadRequestError } from '../../errors/bad_request_error'; import { signalsMigrationService } from '../../migrations/migration_service'; import { getIndexVersionsByIndex } from '../../migrations/get_index_versions_by_index'; import { getSignalVersionsByIndex } from '../../migrations/get_signal_versions_by_index'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/delete_signals_migration_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/delete_signals_migration_route.ts index 2f0749388522b..65ed42a0a166e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/delete_signals_migration_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/delete_signals_migration_route.ts @@ -5,12 +5,14 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { SetupPlugins } from '../../../../plugin'; import { DETECTION_ENGINE_SIGNALS_MIGRATION_URL } from '../../../../../common/constants'; import { deleteSignalsMigrationSchema } from '../../../../../common/detection_engine/schemas/request/delete_signals_migration_schema'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; -import { buildSiemResponse, transformError } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { signalsMigrationService } from '../../migrations/migration_service'; import { getMigrationSavedObjectsById } from '../../migrations/get_migration_saved_objects_by_id'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/finalize_signals_migration_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/finalize_signals_migration_route.ts index 93567f77d17de..20931a8ba7233 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/finalize_signals_migration_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/finalize_signals_migration_route.ts @@ -5,15 +5,16 @@ * 2.0. */ +import { transformError, BadRequestError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { SetupPlugins } from '../../../../plugin'; import { DETECTION_ENGINE_SIGNALS_FINALIZE_MIGRATION_URL } from '../../../../../common/constants'; import { finalizeSignalsMigrationSchema } from '../../../../../common/detection_engine/schemas/request/finalize_signals_migration_schema'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; -import { BadRequestError } from '../../errors/bad_request_error'; import { isMigrationFailed, isMigrationPending } from '../../migrations/helpers'; import { signalsMigrationService } from '../../migrations/migration_service'; -import { buildSiemResponse, transformError } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { getMigrationSavedObjectsById } from '../../migrations/get_migration_saved_objects_by_id'; export const finalizeSignalsMigrationRoute = ( diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/get_signals_migration_status_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/get_signals_migration_status_route.ts index cd7cd017b8c2d..d800cead20cdc 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/get_signals_migration_status_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/get_signals_migration_status_route.ts @@ -5,18 +5,18 @@ * 2.0. */ +import { transformError, getIndexAliases } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_SIGNALS_MIGRATION_STATUS_URL } from '../../../../../common/constants'; import { getSignalsMigrationStatusSchema } from '../../../../../common/detection_engine/schemas/request/get_signals_migration_status_schema'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; -import { getIndexAliases } from '../../index/get_index_aliases'; import { getIndexVersionsByIndex } from '../../migrations/get_index_versions_by_index'; import { getMigrationSavedObjectsByIndex } from '../../migrations/get_migration_saved_objects_by_index'; import { getSignalsIndicesInRange } from '../../migrations/get_signals_indices_in_range'; import { getSignalVersionsByIndex } from '../../migrations/get_signal_versions_by_index'; import { isOutdated, signalsAreOutdated } from '../../migrations/helpers'; import { getTemplateVersion } from '../index/check_template_version'; -import { buildSiemResponse, transformError } from '../utils'; +import { buildSiemResponse } from '../utils'; export const getSignalsMigrationStatusRoute = (router: SecuritySolutionPluginRouter) => { router.get( diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts index d92d39f91baa4..fd001595fb9c7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import { setSignalStatusValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/set_signal_status_type_dependents'; import { SetSignalsStatusSchemaDecoded, @@ -12,7 +13,8 @@ import { } from '../../../../../common/detection_engine/schemas/request/set_signal_status_schema'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_SIGNALS_STATUS_URL } from '../../../../../common/constants'; -import { transformError, buildSiemResponse } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; export const setSignalsStatusRoute = (router: SecuritySolutionPluginRouter) => { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts index 9e542f6974ffc..91172a277bf54 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts @@ -5,9 +5,10 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_QUERY_SIGNALS_URL } from '../../../../../common/constants'; -import { transformError, buildSiemResponse } from '../utils'; +import { buildSiemResponse } from '../utils'; import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/tags/read_tags_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/tags/read_tags_route.ts index 31ee4f5f42a5d..817e4b95aabce 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/tags/read_tags_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/tags/read_tags_route.ts @@ -5,9 +5,11 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { DETECTION_ENGINE_TAGS_URL } from '../../../../../common/constants'; -import { transformError, buildSiemResponse } from '../utils'; +import { buildSiemResponse } from '../utils'; + import { readTags } from '../../tags/read_tags'; export const readTagsRoute = (router: SecuritySolutionPluginRouter) => { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.test.ts index cca7e871f5b8b..3c3eda5b19e44 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.test.ts @@ -6,15 +6,13 @@ */ import Boom from '@hapi/boom'; -import { errors } from '@elastic/elasticsearch'; import { SavedObjectsFindResponse } from 'kibana/server'; import { alertsClientMock } from '../../../../../alerting/server/mocks'; import { IRuleSavedAttributesSavedObjectAttributes, IRuleStatusSOAttributes } from '../rules/types'; -import { BadRequestError } from '../errors/bad_request_error'; +import { BadRequestError } from '@kbn/securitysolution-es-utils'; import { - transformError, transformBulkError, BulkError, createSuccessObject, @@ -35,95 +33,6 @@ import { getQueryRuleParams } from '../schemas/rule_schemas.mock'; let alertsClient: ReturnType; describe('utils', () => { - describe('transformError', () => { - test('returns transformed output error from boom object with a 500 and payload of internal server error', () => { - const boom = new Boom.Boom('some boom message'); - const transformed = transformError(boom); - expect(transformed).toEqual({ - message: 'An internal server error occurred', - statusCode: 500, - }); - }); - - test('returns transformed output if it is some non boom object that has a statusCode', () => { - const error: Error & { statusCode?: number } = { - statusCode: 403, - name: 'some name', - message: 'some message', - }; - const transformed = transformError(error); - expect(transformed).toEqual({ - message: 'some message', - statusCode: 403, - }); - }); - - test('returns a transformed message with the message set and statusCode', () => { - const error: Error & { statusCode?: number } = { - statusCode: 403, - name: 'some name', - message: 'some message', - }; - const transformed = transformError(error); - expect(transformed).toEqual({ - message: 'some message', - statusCode: 403, - }); - }); - - test('transforms best it can if it is some non boom object but it does not have a status Code.', () => { - const error: Error = { - name: 'some name', - message: 'some message', - }; - const transformed = transformError(error); - expect(transformed).toEqual({ - message: 'some message', - statusCode: 500, - }); - }); - - test('it detects a BadRequestError and returns a status code of 400 from that particular error type', () => { - const error: BadRequestError = new BadRequestError('I have a type error'); - const transformed = transformError(error); - expect(transformed).toEqual({ - message: 'I have a type error', - statusCode: 400, - }); - }); - - test('it detects a BadRequestError and returns a Boom status of 400', () => { - const error: BadRequestError = new BadRequestError('I have a type error'); - const transformed = transformError(error); - expect(transformed).toEqual({ - message: 'I have a type error', - statusCode: 400, - }); - }); - - it('transforms a ResponseError returned by the elasticsearch client', () => { - const error: errors.ResponseError = { - name: 'ResponseError', - message: 'illegal_argument_exception', - headers: {}, - body: { - error: { - type: 'illegal_argument_exception', - reason: 'detailed explanation', - }, - }, - meta: ({} as unknown) as errors.ResponseError['meta'], - statusCode: 400, - }; - const transformed = transformError(error); - - expect(transformed).toEqual({ - message: 'illegal_argument_exception: detailed explanation', - statusCode: 400, - }); - }); - }); - describe('transformBulkError', () => { test('returns transformed object if it is a boom object', () => { const boom = new Boom.Boom('some boom message', { statusCode: 400 }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.ts index c2acbf9c5cc0a..130084da21591 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.ts @@ -6,8 +6,8 @@ */ import Boom from '@hapi/boom'; -import { errors } from '@elastic/elasticsearch'; import { has, snakeCase } from 'lodash/fp'; +import { BadRequestError } from '@kbn/securitysolution-es-utils'; import { SanitizedAlert } from '../../../../../alerting/common'; import { @@ -17,53 +17,12 @@ import { SavedObjectsFindResult, } from '../../../../../../../src/core/server'; import { AlertsClient } from '../../../../../alerting/server'; -import { BadRequestError } from '../errors/bad_request_error'; import { RuleStatusResponse, IRuleStatusSOAttributes } from '../rules/types'; export interface OutputError { message: string; statusCode: number; } - -/** - * @deprecated Use kbn-securitysolution-es-utils version - */ -export const transformError = (err: Error & Partial): OutputError => { - if (Boom.isBoom(err)) { - return { - message: err.output.payload.message, - statusCode: err.output.statusCode, - }; - } else { - if (err.statusCode != null) { - if (err.body?.error != null) { - return { - statusCode: err.statusCode, - message: `${err.body.error.type}: ${err.body.error.reason}`, - }; - } else { - return { - statusCode: err.statusCode, - message: err.message, - }; - } - } else if (err instanceof BadRequestError) { - // allows us to throw request validation errors in the absence of Boom - return { - message: err.message, - statusCode: 400, - }; - } else { - // natively return the err and allow the regular framework - // to deal with the error when it is a non Boom - return { - message: err.message ?? '(unknown error message)', - statusCode: 500, - }; - } - } -}; - export interface BulkError { id?: string; rule_id?: string; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.test.ts index 248afda7ff5c3..c5b3e98c4c44e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.test.ts @@ -8,7 +8,7 @@ import { Readable } from 'stream'; import { createPromiseFromStreams } from '@kbn/utils'; import { createRulesStreamFromNdJson } from './create_rules_stream_from_ndjson'; -import { BadRequestError } from '../errors/bad_request_error'; +import { BadRequestError } from '@kbn/securitysolution-es-utils'; import { ImportRulesSchemaDecoded } from '../../../../common/detection_engine/schemas/request/import_rules_schema'; type PromiseFromStreams = ImportRulesSchemaDecoded | Error; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.ts index 5e3c3c8b1cb98..0c2d81c18646b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.ts @@ -11,15 +11,14 @@ import { pipe } from 'fp-ts/lib/pipeable'; import { fold } from 'fp-ts/lib/Either'; import { createSplitStream, createMapStream, createConcatStream } from '@kbn/utils'; -import { formatErrors } from '../../../../common/format_errors'; +import { exactCheck, formatErrors } from '@kbn/securitysolution-io-ts-utils'; +import { BadRequestError } from '@kbn/securitysolution-es-utils'; import { importRuleValidateTypeDependents } from '../../../../common/detection_engine/schemas/request/import_rules_type_dependents'; -import { exactCheck } from '../../../../common/exact_check'; import { importRulesSchema, ImportRulesSchema, ImportRulesSchemaDecoded, } from '../../../../common/detection_engine/schemas/request/import_rules_schema'; -import { BadRequestError } from '../errors/bad_request_error'; import { parseNdjsonStrings, filterExportedCounts, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_prepackaged_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_prepackaged_rules.ts index b91557c6d7b1b..f2d28d13fa926 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_prepackaged_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_prepackaged_rules.ts @@ -8,14 +8,13 @@ import * as t from 'io-ts'; import { fold } from 'fp-ts/lib/Either'; import { pipe } from 'fp-ts/lib/pipeable'; -import { formatErrors } from '../../../../common/format_errors'; -import { exactCheck } from '../../../../common/exact_check'; +import { exactCheck, formatErrors } from '@kbn/securitysolution-io-ts-utils'; +import { BadRequestError } from '@kbn/securitysolution-es-utils'; import { addPrepackagedRulesSchema, AddPrepackagedRulesSchema, AddPrepackagedRulesSchemaDecoded, } from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema'; -import { BadRequestError } from '../errors/bad_request_error'; // TODO: convert rules files to TS and add explicit type definitions import { rawRules } from './prepackaged_rules'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.ts index bccd1f2fb73ca..b9a88bc36a812 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.ts @@ -6,7 +6,7 @@ */ import { defaults } from 'lodash/fp'; -import { validate } from '../../../../common/validate'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; import { PartialAlert } from '../../../../../alerting/server'; import { transformRuleToAlertAction } from '../../../../common/detection_engine/transform_actions'; import { PatchRulesOptions } from './types'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/types.ts index 2990a0f728027..e670535c26ae5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/types.ts @@ -14,55 +14,70 @@ import { SavedObjectsFindResponse, SavedObjectsClientContract, } from 'kibana/server'; +import { + MachineLearningJobIdOrUndefined, + From, + FromOrUndefined, + RiskScore, + RiskScoreMapping, + RiskScoreMappingOrUndefined, + RiskScoreOrUndefined, + ThreatIndexOrUndefined, + ThreatQueryOrUndefined, + ThreatMappingOrUndefined, + ThreatFiltersOrUndefined, + ThreatLanguageOrUndefined, + ConcurrentSearchesOrUndefined, + ItemsPerSearchOrUndefined, + ThreatIndicatorPathOrUndefined, + Threats, + ThreatsOrUndefined, + TypeOrUndefined, + Type, + LanguageOrUndefined, + SeverityMapping, + SeverityMappingOrUndefined, + SeverityOrUndefined, + Severity, + MaxSignalsOrUndefined, + MaxSignals, +} from '@kbn/securitysolution-io-ts-alerting-types'; +import { VersionOrUndefined, Version } from '@kbn/securitysolution-io-ts-types'; + +import { ListArrayOrUndefined, ListArray } from '@kbn/securitysolution-io-ts-list-types'; import { UpdateRulesSchema } from '../../../../common/detection_engine/schemas/request'; import { RuleAlertAction } from '../../../../common/detection_engine/types'; import { FalsePositives, - From, RuleId, Immutable, DescriptionOrUndefined, Interval, - MaxSignals, - RiskScore, OutputIndex, Name, - Severity, Tags, - Threats, To, - Type, References, - Version, AnomalyThresholdOrUndefined, QueryOrUndefined, - LanguageOrUndefined, SavedIdOrUndefined, TimelineIdOrUndefined, TimelineTitleOrUndefined, - MachineLearningJobIdOrUndefined, IndexOrUndefined, NoteOrUndefined, MetaOrUndefined, Description, Enabled, - VersionOrUndefined, IdOrUndefined, RuleIdOrUndefined, EnabledOrUndefined, FalsePositivesOrUndefined, - FromOrUndefined, OutputIndexOrUndefined, IntervalOrUndefined, - MaxSignalsOrUndefined, - RiskScoreOrUndefined, NameOrUndefined, - SeverityOrUndefined, TagsOrUndefined, ToOrUndefined, - ThreatsOrUndefined, ThresholdOrUndefined, - TypeOrUndefined, ReferencesOrUndefined, PerPageOrUndefined, PageOrUndefined, @@ -79,31 +94,16 @@ import { Author, AuthorOrUndefined, LicenseOrUndefined, - RiskScoreMapping, - RiskScoreMappingOrUndefined, - SeverityMapping, - SeverityMappingOrUndefined, TimestampOverrideOrUndefined, BuildingBlockTypeOrUndefined, RuleNameOverrideOrUndefined, EventCategoryOverrideOrUndefined, } from '../../../../common/detection_engine/schemas/common/schemas'; -import { - ThreatIndexOrUndefined, - ThreatQueryOrUndefined, - ThreatMappingOrUndefined, - ThreatFiltersOrUndefined, - ThreatLanguageOrUndefined, - ConcurrentSearchesOrUndefined, - ItemsPerSearchOrUndefined, - ThreatIndicatorPathOrUndefined, -} from '../../../../common/detection_engine/schemas/types/threat_mapping'; import { AlertsClient, PartialAlert } from '../../../../../alerting/server'; import { Alert, SanitizedAlert } from '../../../../../alerting/common'; import { SIGNALS_ID } from '../../../../common/constants'; import { PartialFilter } from '../types'; -import { ListArrayOrUndefined, ListArray } from '../../../../common/detection_engine/schemas/types'; import { RuleParams } from '../schemas/rule_schemas'; export type RuleAlertType = Alert; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/utils.ts index 5c8450201d096..a31f9bec2cd58 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/utils.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/utils.ts @@ -6,53 +6,53 @@ */ import { pickBy, isEmpty } from 'lodash/fp'; +import { + FromOrUndefined, + MachineLearningJobIdOrUndefined, + RiskScoreMappingOrUndefined, + RiskScoreOrUndefined, + ConcurrentSearchesOrUndefined, + ItemsPerSearchOrUndefined, + ThreatFiltersOrUndefined, + ThreatIndexOrUndefined, + ThreatLanguageOrUndefined, + ThreatMappingOrUndefined, + ThreatQueryOrUndefined, + ThreatsOrUndefined, + TypeOrUndefined, + LanguageOrUndefined, + SeverityOrUndefined, + SeverityMappingOrUndefined, + MaxSignalsOrUndefined, +} from '@kbn/securitysolution-io-ts-alerting-types'; +import { ListArrayOrUndefined } from '@kbn/securitysolution-io-ts-list-types'; +import { VersionOrUndefined } from '@kbn/securitysolution-io-ts-types'; import { DescriptionOrUndefined, AnomalyThresholdOrUndefined, QueryOrUndefined, - LanguageOrUndefined, SavedIdOrUndefined, TimelineIdOrUndefined, TimelineTitleOrUndefined, - MachineLearningJobIdOrUndefined, IndexOrUndefined, NoteOrUndefined, MetaOrUndefined, - VersionOrUndefined, FalsePositivesOrUndefined, - FromOrUndefined, OutputIndexOrUndefined, IntervalOrUndefined, - MaxSignalsOrUndefined, - RiskScoreOrUndefined, NameOrUndefined, - SeverityOrUndefined, TagsOrUndefined, ToOrUndefined, - ThreatsOrUndefined, ThresholdOrUndefined, - TypeOrUndefined, ReferencesOrUndefined, AuthorOrUndefined, BuildingBlockTypeOrUndefined, LicenseOrUndefined, - RiskScoreMappingOrUndefined, RuleNameOverrideOrUndefined, - SeverityMappingOrUndefined, TimestampOverrideOrUndefined, EventCategoryOverrideOrUndefined, } from '../../../../common/detection_engine/schemas/common/schemas'; import { PartialFilter } from '../types'; -import { - ConcurrentSearchesOrUndefined, - ItemsPerSearchOrUndefined, - ListArrayOrUndefined, - ThreatFiltersOrUndefined, - ThreatIndexOrUndefined, - ThreatLanguageOrUndefined, - ThreatMappingOrUndefined, - ThreatQueryOrUndefined, -} from '../../../../common/detection_engine/schemas/types'; export const calculateInterval = ( interval: string | undefined, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/schemas/rule_schemas.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/schemas/rule_schemas.ts index 79b862d6419c2..2af481b195a07 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/schemas/rule_schemas.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/schemas/rule_schemas.ts @@ -7,15 +7,26 @@ import * as t from 'io-ts'; -import { listArray } from '../../../../common/detection_engine/schemas/types/lists'; import { + actionsCamel, + from, + machine_learning_job_id_normalized, + risk_score, + risk_score_mapping, threat_mapping, threat_index, threat_query, concurrentSearchesOrUndefined, itemsPerSearchOrUndefined, threatIndicatorPathOrUndefined, -} from '../../../../common/detection_engine/schemas/types/threat_mapping'; + threats, + severity, + severity_mapping, + throttleOrNull, + max_signals, +} from '@kbn/securitysolution-io-ts-alerting-types'; +import { listArray } from '@kbn/securitysolution-io-ts-list-types'; +import { version } from '@kbn/securitysolution-io-ts-types'; import { author, buildingBlockTypeOrUndefined, @@ -23,7 +34,6 @@ import { enabled, noteOrUndefined, false_positives, - from, rule_id, immutable, indexOrUndefined, @@ -36,32 +46,23 @@ import { query, queryOrUndefined, filtersOrUndefined, - max_signals, - risk_score, - risk_score_mapping, ruleNameOverrideOrUndefined, - severity, - severity_mapping, tags, timestampOverrideOrUndefined, - threats, to, references, - version, eventCategoryOverrideOrUndefined, savedIdOrUndefined, saved_id, thresholdNormalized, anomaly_threshold, - actionsCamel, - throttleOrNull, createdByOrNull, updatedByOrNull, created_at, updated_at, } from '../../../../common/detection_engine/schemas/common/schemas'; + import { SIGNALS_ID, SERVER_APP_ID } from '../../../../common/constants'; -import { machine_learning_job_id_normalized } from '../../../../common/detection_engine/schemas/types/normalized_ml_job_id'; const nonEqlLanguages = t.keyof({ kuery: null, lucene: null }); export const baseRuleParams = t.exact( diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/types.ts index e1618d217d0dc..f653fde816c62 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/types.ts @@ -7,9 +7,10 @@ import type { estypes } from '@elastic/elasticsearch'; import { Logger } from 'src/core/server'; +import { Type } from '@kbn/securitysolution-io-ts-list-types'; import { ListClient } from '../../../../../../lists/server'; import { BuildRuleMessage } from '../rule_messages'; -import { ExceptionListItemSchema, Type } from '../../../../../../lists/common/schemas'; +import { ExceptionListItemSchema } from '../../../../../../lists/common/schemas'; export interface FilterEventsAgainstListOptions { listClient: ListClient; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.ts index 86940e9b77084..3d6a1f8da7f4d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.ts @@ -5,15 +5,14 @@ * 2.0. */ +import { BadRequestError } from '@kbn/securitysolution-es-utils'; +import { Type, LanguageOrUndefined, Language } from '@kbn/securitysolution-io-ts-alerting-types'; import { assertUnreachable } from '../../../../common/utility_types'; import { getQueryFilter } from '../../../../common/detection_engine/get_query_filter'; import { - LanguageOrUndefined, QueryOrUndefined, - Type, SavedIdOrUndefined, IndexOrUndefined, - Language, } from '../../../../common/detection_engine/schemas/common/schemas'; import { ExceptionListItemSchema } from '../../../../../lists/common/schemas'; import { @@ -22,7 +21,6 @@ import { AlertServices, } from '../../../../../alerting/server'; import { PartialFilter } from '../types'; -import { BadRequestError } from '../errors/bad_request_error'; import { QueryFilter } from './types'; interface GetFilterArgs { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.test.ts index 88ce9de15cff8..82f3ff46b347d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.test.ts @@ -5,10 +5,7 @@ * 2.0. */ -import { - RiskScore, - RiskScoreMappingOrUndefined, -} from '../../../../../common/detection_engine/schemas/common/schemas'; +import { RiskScore, RiskScoreMappingOrUndefined } from '@kbn/securitysolution-io-ts-alerting-types'; import { sampleDocRiskScore } from '../__mocks__/es_results'; import { buildRiskScoreFromMapping, 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 84d45f22b7f44..7253b24e66088 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 @@ -5,12 +5,9 @@ * 2.0. */ +import { RiskScore, RiskScoreMappingOrUndefined } from '@kbn/securitysolution-io-ts-alerting-types'; import { get } from 'lodash/fp'; -import { - Meta, - RiskScore, - RiskScoreMappingOrUndefined, -} from '../../../../../common/detection_engine/schemas/common/schemas'; +import { Meta } from '../../../../../common/detection_engine/schemas/common/schemas'; import { SignalSource } from '../types'; export interface BuildRiskScoreFromMappingProps { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.test.ts index cfd4b81ae3bc8..4ccf24a307cc4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.test.ts @@ -5,10 +5,8 @@ * 2.0. */ -import { - Severity, - SeverityMappingOrUndefined, -} from '../../../../../common/detection_engine/schemas/common/schemas'; +import { Severity, SeverityMappingOrUndefined } from '@kbn/securitysolution-io-ts-alerting-types'; + import { sampleDocSeverity } from '../__mocks__/es_results'; import { buildSeverityFromMapping, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.ts index 44e41fbd0c9c0..652b6b2221900 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.ts @@ -6,13 +6,14 @@ */ import { get } from 'lodash/fp'; + import { - Meta, Severity, SeverityMappingItem, severity as SeverityIOTS, SeverityMappingOrUndefined, -} from '../../../../../common/detection_engine/schemas/common/schemas'; +} from '@kbn/securitysolution-io-ts-alerting-types'; +import { Meta } from '../../../../../common/detection_engine/schemas/common/schemas'; import { SearchTypes } from '../../../../../common/detection_engine/types'; import { SignalSource } from '../types'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.ts index 6e24e96c6e36d..d00bcc2a9f11e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.ts @@ -12,7 +12,7 @@ import { chain, tryCatch } from 'fp-ts/lib/TaskEither'; import { flow } from 'fp-ts/lib/function'; import * as t from 'io-ts'; -import { validateNonExact } from '../../../../common/validate'; +import { validateNonExact } from '@kbn/securitysolution-io-ts-utils'; import { toError, toPromise } from '../../../../common/fp_utils'; import { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/build_threat_mapping_filter.mock.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/build_threat_mapping_filter.mock.ts index e39b78b4f4a44..f49e3dec93600 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/build_threat_mapping_filter.mock.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/build_threat_mapping_filter.mock.ts @@ -5,7 +5,7 @@ * 2.0. */ import type { estypes } from '@elastic/elasticsearch'; -import { ThreatMapping } from '../../../../../common/detection_engine/schemas/types/threat_mapping'; +import { ThreatMapping } from '@kbn/securitysolution-io-ts-alerting-types'; import { Filter } from 'src/plugins/data/common'; import { ThreatListDoc, ThreatListItem } from './types'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/build_threat_mapping_filter.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/build_threat_mapping_filter.test.ts index 1c0300ee0cc74..a96eb50af3c50 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/build_threat_mapping_filter.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/build_threat_mapping_filter.test.ts @@ -5,10 +5,7 @@ * 2.0. */ -import { - ThreatMapping, - ThreatMappingEntries, -} from '../../../../../common/detection_engine/schemas/types/threat_mapping'; +import { ThreatMapping, ThreatMappingEntries } from '@kbn/securitysolution-io-ts-alerting-types'; import { filterThreatMapping, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/build_threat_mapping_filter.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/build_threat_mapping_filter.ts index 18204bb678a47..22e21ef40cb3e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/build_threat_mapping_filter.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/build_threat_mapping_filter.ts @@ -7,7 +7,7 @@ import get from 'lodash/fp/get'; import { Filter } from 'src/plugins/data/common'; -import { ThreatMapping } from '../../../../../common/detection_engine/schemas/types/threat_mapping'; +import { ThreatMapping } from '@kbn/securitysolution-io-ts-alerting-types'; import { BooleanFilter, BuildEntriesMappingFilterOptions, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts index 360fb118faa84..82fc0dd3abd0a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts @@ -5,11 +5,6 @@ * 2.0. */ import type { estypes } from '@elastic/elasticsearch'; -import { ListClient } from '../../../../../../lists/server'; -import { - Type, - LanguageOrUndefined, -} from '../../../../../common/detection_engine/schemas/common/schemas'; import { ThreatQuery, ThreatMapping, @@ -19,7 +14,10 @@ import { ConcurrentSearches, ItemsPerSearch, ThreatIndicatorPathOrUndefined, -} from '../../../../../common/detection_engine/schemas/types/threat_mapping'; + LanguageOrUndefined, + Type, +} from '@kbn/securitysolution-io-ts-alerting-types'; +import { ListClient } from '../../../../../../lists/server'; import { AlertInstanceContext, AlertInstanceState, 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 bd37cf62c74b0..c2e3fe83b8893 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 @@ -14,6 +14,7 @@ import { isEmpty, partition } from 'lodash'; import { ApiResponse, Context } from '@elastic/elasticsearch/lib/Transport'; import { SortResults } from '@elastic/elasticsearch/api/types'; +import { ListArray } from '@kbn/securitysolution-io-ts-list-types'; import { TimestampOverrideOrUndefined, Privilege, @@ -27,7 +28,6 @@ import { } from '../../../../../alerting/server'; import { ExceptionListClient, ListClient, ListPluginSetup } from '../../../../../lists/server'; import { ExceptionListItemSchema } from '../../../../../lists/common/schemas'; -import { ListArray } from '../../../../common/detection_engine/schemas/types/lists'; import { BulkResponseErrorAggregation, SignalHit, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/types.ts index 85c8483a0b988..03ec7928115b7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/types.ts @@ -5,54 +5,55 @@ * 2.0. */ +import { + From, + MachineLearningJobIdOrUndefined, + RiskScore, + RiskScoreMappingOrUndefined, + ThreatIndexOrUndefined, + ThreatQueryOrUndefined, + ThreatMappingOrUndefined, + ThreatLanguageOrUndefined, + ConcurrentSearchesOrUndefined, + ItemsPerSearchOrUndefined, + ThreatIndicatorPathOrUndefined, + ThreatsOrUndefined, + Type, + LanguageOrUndefined, + Severity, + SeverityMappingOrUndefined, + MaxSignals, +} from '@kbn/securitysolution-io-ts-alerting-types'; +import { Version } from '@kbn/securitysolution-io-ts-types'; + +import { ListArrayOrUndefined } from '@kbn/securitysolution-io-ts-list-types'; import { AnomalyThresholdOrUndefined, Description, NoteOrUndefined, - ThreatsOrUndefined, ThresholdOrUndefined, FalsePositives, - From, Immutable, IndexOrUndefined, - LanguageOrUndefined, - MaxSignals, - MachineLearningJobIdOrUndefined, - RiskScore, OutputIndex, QueryOrUndefined, References, SavedIdOrUndefined, - Severity, To, TimelineIdOrUndefined, TimelineTitleOrUndefined, - Version, MetaOrUndefined, RuleId, AuthorOrUndefined, BuildingBlockTypeOrUndefined, LicenseOrUndefined, - RiskScoreMappingOrUndefined, RuleNameOverrideOrUndefined, - SeverityMappingOrUndefined, TimestampOverrideOrUndefined, - Type, EventCategoryOverrideOrUndefined, } from '../../../common/detection_engine/schemas/common/schemas'; -import { - ThreatIndexOrUndefined, - ThreatQueryOrUndefined, - ThreatMappingOrUndefined, - ThreatLanguageOrUndefined, - ConcurrentSearchesOrUndefined, - ItemsPerSearchOrUndefined, - ThreatIndicatorPathOrUndefined, -} from '../../../common/detection_engine/schemas/types/threat_mapping'; import { LegacyCallAPIOptions } from '../../../../../../src/core/server'; import { Filter } from '../../../../../../src/plugins/data/server'; -import { ListArrayOrUndefined } from '../../../common/detection_engine/schemas/types'; import { AlertTypeParams } from '../../../../alerting/common'; export type PartialFilter = Partial; diff --git a/x-pack/plugins/security_solution/server/lib/machine_learning/authz.ts b/x-pack/plugins/security_solution/server/lib/machine_learning/authz.ts index 85c1eea7a957a..d5e8e951397c2 100644 --- a/x-pack/plugins/security_solution/server/lib/machine_learning/authz.ts +++ b/x-pack/plugins/security_solution/server/lib/machine_learning/authz.ts @@ -7,6 +7,7 @@ import { i18n } from '@kbn/i18n'; +import { Type } from '@kbn/securitysolution-io-ts-alerting-types'; import { KibanaRequest, SavedObjectsClientContract } from '../../../../../../src/core/server/'; import { ILicense } from '../../../../licensing/server'; import { MlPluginSetup } from '../../../../ml/server'; @@ -16,8 +17,6 @@ import { hasMlAdminPermissions } from '../../../common/machine_learning/has_ml_a import { isMlRule } from '../../../common/machine_learning/helpers'; import { Validation } from './validation'; import { cache } from './cache'; -import { Type } from '../../../common/detection_engine/schemas/common/schemas'; - export interface MlAuthz { validateRuleType: (type: Type) => Promise; } diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/draft_timelines/clean_draft_timelines/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/draft_timelines/clean_draft_timelines/index.ts index 113860f369f78..62770408af2fe 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/draft_timelines/clean_draft_timelines/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/draft_timelines/clean_draft_timelines/index.ts @@ -6,9 +6,11 @@ */ import uuid from 'uuid'; +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../../types'; import { ConfigType } from '../../../../..'; -import { transformError, buildSiemResponse } from '../../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../../detection_engine/routes/utils'; + import { TIMELINE_DRAFT_URL } from '../../../../../../common/constants'; import { buildFrameworkRequest } from '../../../utils/common'; import { SetupPlugins } from '../../../../../plugin'; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/draft_timelines/get_draft_timelines/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/draft_timelines/get_draft_timelines/index.ts index f3f813ace411d..cd7770dcd5b48 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/draft_timelines/get_draft_timelines/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/draft_timelines/get_draft_timelines/index.ts @@ -5,9 +5,11 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../../types'; import { ConfigType } from '../../../../..'; -import { transformError, buildSiemResponse } from '../../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../../detection_engine/routes/utils'; + import { TIMELINE_DRAFT_URL } from '../../../../../../common/constants'; import { buildFrameworkRequest } from '../../../utils/common'; import { SetupPlugins } from '../../../../../plugin'; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/notes/persist_note.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/notes/persist_note.ts index cb7d984ade40b..32fd87f39620b 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/notes/persist_note.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/notes/persist_note.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { NOTE_URL } from '../../../../../common/constants'; @@ -13,7 +14,7 @@ import { SetupPlugins } from '../../../../plugin'; import { buildRouteValidationWithExcess } from '../../../../utils/build_validation/route_validation'; import { ConfigType } from '../../../..'; -import { transformError, buildSiemResponse } from '../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../detection_engine/routes/utils'; import { buildFrameworkRequest } from '../../utils/common'; import { persistNoteSchema } from '../../schemas/notes'; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/pinned_events/persist_pinned_event.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/pinned_events/persist_pinned_event.ts index 53ac002721c6e..ee407468f0c30 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/pinned_events/persist_pinned_event.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/pinned_events/persist_pinned_event.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../types'; import { PINNED_EVENT_URL } from '../../../../../common/constants'; @@ -13,7 +14,7 @@ import { SetupPlugins } from '../../../../plugin'; import { buildRouteValidationWithExcess } from '../../../../utils/build_validation/route_validation'; import { ConfigType } from '../../../..'; -import { transformError, buildSiemResponse } from '../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../detection_engine/routes/utils'; import { buildFrameworkRequest } from '../../utils/common'; import { persistPinnedEventSchema } from '../../schemas/pinned_events'; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/prepackaged_timelines/install_prepackaged_timelines/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/prepackaged_timelines/install_prepackaged_timelines/index.ts index bb447948df24a..438ce71edd089 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/prepackaged_timelines/install_prepackaged_timelines/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/prepackaged_timelines/install_prepackaged_timelines/index.ts @@ -5,15 +5,16 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; import type { SecuritySolutionPluginRouter } from '../../../../../types'; import { TIMELINE_PREPACKAGED_URL } from '../../../../../../common/constants'; import { SetupPlugins } from '../../../../../plugin'; import { ConfigType } from '../../../../../config'; -import { validate } from '../../../../../../common/validate'; -import { buildSiemResponse, transformError } from '../../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../../detection_engine/routes/utils'; import { installPrepackagedTimelines } from './helpers'; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/create_timelines/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/create_timelines/index.ts index f35ddf1a76c7d..432a441e61e07 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/create_timelines/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/create_timelines/index.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../../types'; import { TIMELINE_URL } from '../../../../../../common/constants'; @@ -13,7 +14,7 @@ import { ConfigType } from '../../../../..'; import { SetupPlugins } from '../../../../../plugin'; import { buildRouteValidationWithExcess } from '../../../../../utils/build_validation/route_validation'; -import { transformError, buildSiemResponse } from '../../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../../detection_engine/routes/utils'; import { createTimelineSchema } from '../../../schemas/timelines'; import { diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/delete_timelines/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/delete_timelines/index.ts index 7617881b90b7f..13fbc22aba5d3 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/delete_timelines/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/delete_timelines/index.ts @@ -5,13 +5,15 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import { buildRouteValidationWithExcess } from '../../../../../utils/build_validation/route_validation'; import { ConfigType } from '../../../../..'; import { deleteTimelinesSchema } from '../../../schemas/timelines/delete_timelines_schema'; import { SecuritySolutionPluginRouter } from '../../../../../types'; import { SetupPlugins } from '../../../../../plugin'; import { TIMELINE_URL } from '../../../../../../common/constants'; -import { transformError, buildSiemResponse } from '../../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../../detection_engine/routes/utils'; + import { buildFrameworkRequest } from '../../../utils/common'; import { deleteTimeline } from '../../../saved_object/timelines'; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/export_timelines/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/export_timelines/index.ts index 9e1eabc4450bd..0d60129b1fcd6 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/export_timelines/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/export_timelines/index.ts @@ -5,10 +5,11 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import { TIMELINE_EXPORT_URL } from '../../../../../../common/constants'; import type { SecuritySolutionPluginRouter } from '../../../../../types'; import { ConfigType } from '../../../../../config'; -import { transformError, buildSiemResponse } from '../../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../../detection_engine/routes/utils'; import { exportTimelinesQuerySchema, diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/get_timeline/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/get_timeline/index.ts index 8d94cd2ef2cce..921ae2352a565 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/get_timeline/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/get_timeline/index.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../../types'; import { TIMELINE_URL } from '../../../../../../common/constants'; @@ -13,7 +14,7 @@ import { ConfigType } from '../../../../..'; import { SetupPlugins } from '../../../../../plugin'; import { buildRouteValidationWithExcess } from '../../../../../utils/build_validation/route_validation'; -import { buildSiemResponse, transformError } from '../../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../../detection_engine/routes/utils'; import { buildFrameworkRequest } from '../../../utils/common'; import { getTimelineQuerySchema } from '../../../schemas/timelines'; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/get_timelines/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/get_timelines/index.ts index 51a02db681b0c..4599916092611 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/get_timelines/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/get_timelines/index.ts @@ -10,13 +10,14 @@ import { pipe } from 'fp-ts/lib/pipeable'; import { fold } from 'fp-ts/lib/Either'; import { identity } from 'fp-ts/lib/function'; +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../../types'; import { TIMELINES_URL } from '../../../../../../common/constants'; import { ConfigType } from '../../../../..'; import { SetupPlugins } from '../../../../../plugin'; -import { buildSiemResponse, transformError } from '../../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../../detection_engine/routes/utils'; import { buildFrameworkRequest, escapeHatch, throwErrors } from '../../../utils/common'; import { getAllTimeline } from '../../../saved_object/timelines'; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/import_timelines/create_timelines_stream_from_ndjson.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/import_timelines/create_timelines_stream_from_ndjson.ts index aeb7463377b1f..d016fe8a24ff2 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/import_timelines/create_timelines_stream_from_ndjson.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/import_timelines/create_timelines_stream_from_ndjson.ts @@ -11,6 +11,7 @@ import { pipe } from 'fp-ts/lib/pipeable'; import { fold } from 'fp-ts/lib/Either'; import { identity } from 'fp-ts/lib/function'; import { createConcatStream, createSplitStream, createMapStream } from '@kbn/utils'; +import { BadRequestError } from '@kbn/securitysolution-es-utils'; import { parseNdjsonStrings, filterExportedCounts, @@ -19,7 +20,6 @@ import { import { ImportTimelineResponse } from './types'; import { ImportTimelinesSchemaRt } from '../../../schemas/timelines/import_timelines_schema'; -import { BadRequestError } from '../../../../detection_engine/errors/bad_request_error'; import { throwErrors } from '../../../utils/common'; type ErrorFactory = (message: string) => Error; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/import_timelines/helpers.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/import_timelines/helpers.ts index a19276652e78b..70d93d7552b1c 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/import_timelines/helpers.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/import_timelines/helpers.ts @@ -10,12 +10,12 @@ import { Readable } from 'stream'; import uuid from 'uuid'; import { createPromiseFromStreams } from '@kbn/utils'; +import { validate } from '@kbn/securitysolution-io-ts-utils'; import { ImportTimelineResultSchema, importTimelineResultSchema, TimelineStatus, } from '../../../../../../common/types/timeline'; -import { validate } from '../../../../../../common/validate'; import { createBulkErrorObject, BulkError } from '../../../../detection_engine/routes/utils'; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/import_timelines/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/import_timelines/index.ts index 603aad16dd9c6..65ffd10c5168b 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/import_timelines/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/import_timelines/index.ts @@ -8,6 +8,7 @@ import { extname } from 'path'; import { Readable } from 'stream'; +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../../types'; import { TIMELINE_IMPORT_URL } from '../../../../../../common/constants'; @@ -15,7 +16,7 @@ import { TIMELINE_IMPORT_URL } from '../../../../../../common/constants'; import { SetupPlugins } from '../../../../../plugin'; import { ConfigType } from '../../../../../config'; import { buildRouteValidationWithExcess } from '../../../../../utils/build_validation/route_validation'; -import { buildSiemResponse, transformError } from '../../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../../detection_engine/routes/utils'; import { importTimelines } from './helpers'; import { ImportTimelinesPayloadSchemaRt } from '../../../schemas/timelines/import_timelines_schema'; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/patch_timelines/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/patch_timelines/index.ts index b0142625f5e08..e3ad9bc7cb048 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/patch_timelines/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/patch_timelines/index.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../../types'; import { TIMELINE_URL } from '../../../../../../common/constants'; @@ -13,7 +14,7 @@ import { SetupPlugins } from '../../../../../plugin'; import { buildRouteValidationWithExcess } from '../../../../../utils/build_validation/route_validation'; import { ConfigType } from '../../../../..'; -import { transformError, buildSiemResponse } from '../../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../../detection_engine/routes/utils'; import { patchTimelineSchema } from '../../../schemas/timelines/patch_timelines_schema'; import { buildFrameworkRequest, TimelineStatusActions } from '../../../utils/common'; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/persist_favorite/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/persist_favorite/index.ts index 2cc3888696248..0de64171e0fb8 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/persist_favorite/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/persist_favorite/index.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { transformError } from '@kbn/securitysolution-es-utils'; import type { SecuritySolutionPluginRouter } from '../../../../../types'; import { TIMELINE_FAVORITE_URL } from '../../../../../../common/constants'; @@ -13,7 +14,7 @@ import { SetupPlugins } from '../../../../../plugin'; import { buildRouteValidationWithExcess } from '../../../../../utils/build_validation/route_validation'; import { ConfigType } from '../../../../..'; -import { transformError, buildSiemResponse } from '../../../../detection_engine/routes/utils'; +import { buildSiemResponse } from '../../../../detection_engine/routes/utils'; import { buildFrameworkRequest } from '../../../utils/common'; import { persistFavorite } from '../../../saved_object/timelines'; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/utils/common.ts b/x-pack/plugins/security_solution/server/lib/timeline/utils/common.ts index c4ddefd925b37..be086732ddcd0 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/utils/common.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/utils/common.ts @@ -11,9 +11,9 @@ import fs from 'fs'; import { Readable } from 'stream'; import { createListStream } from '@kbn/utils'; import { schema } from '@kbn/config-schema'; -import { isObject } from 'lodash/fp'; import { KibanaRequest } from 'src/core/server'; +import { formatErrors } from '@kbn/securitysolution-io-ts-utils'; import { SetupPlugins, StartPlugins } from '../../../plugin'; import type { SecuritySolutionRequestHandlerContext } from '../../../types'; @@ -40,32 +40,6 @@ export const buildFrameworkRequest = async ( export const escapeHatch = schema.object({}, { unknowns: 'allow' }); -/** - * @deprecated Use packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.ts - */ -export const formatErrors = (errors: rt.Errors): string[] => { - const err = errors.map((error) => { - if (error.message != null) { - return error.message; - } else { - const keyContext = error.context - .filter( - (entry) => entry.key != null && !Number.isInteger(+entry.key) && entry.key.trim() !== '' - ) - .map((entry) => entry.key) - .join(','); - - const nameContext = error.context.find((entry) => entry.type?.name?.length > 0); - const suppliedValue = - keyContext !== '' ? keyContext : nameContext != null ? nameContext.type.name : ''; - const value = isObject(error.value) ? JSON.stringify(error.value) : error.value; - return `Invalid value "${value}" supplied to "${suppliedValue}"`; - } - }); - - return [...new Set(err)]; -}; - type ErrorFactory = (message: string) => Error; export const throwErrors = (createError: ErrorFactory) => (errors: rt.Errors) => { diff --git a/x-pack/plugins/security_solution/server/utils/build_validation/route_validation.ts b/x-pack/plugins/security_solution/server/utils/build_validation/route_validation.ts index caba0eb9f0152..5dfa74c14bf72 100644 --- a/x-pack/plugins/security_solution/server/utils/build_validation/route_validation.ts +++ b/x-pack/plugins/security_solution/server/utils/build_validation/route_validation.ts @@ -8,8 +8,7 @@ import { fold } from 'fp-ts/lib/Either'; import { pipe } from 'fp-ts/lib/pipeable'; import * as rt from 'io-ts'; -import { formatErrors } from '../../../common/format_errors'; -import { exactCheck } from '../../../common/exact_check'; +import { exactCheck, formatErrors } from '@kbn/securitysolution-io-ts-utils'; import { RouteValidationFunction, RouteValidationResultFactory, diff --git a/x-pack/plugins/security_solution/server/utils/read_stream/create_stream_from_ndjson.ts b/x-pack/plugins/security_solution/server/utils/read_stream/create_stream_from_ndjson.ts index 02749cf093695..b0b70aeb3ea34 100644 --- a/x-pack/plugins/security_solution/server/utils/read_stream/create_stream_from_ndjson.ts +++ b/x-pack/plugins/security_solution/server/utils/read_stream/create_stream_from_ndjson.ts @@ -12,15 +12,14 @@ import { fold } from 'fp-ts/lib/Either'; import * as t from 'io-ts'; import { createMapStream, createFilterStream } from '@kbn/utils'; -import { formatErrors } from '../../../common/format_errors'; +import { exactCheck, formatErrors } from '@kbn/securitysolution-io-ts-utils'; +import { BadRequestError } from '@kbn/securitysolution-es-utils'; import { importRuleValidateTypeDependents } from '../../../common/detection_engine/schemas/request/import_rules_type_dependents'; import { ImportRulesSchemaDecoded, importRulesSchema, ImportRulesSchema, } from '../../../common/detection_engine/schemas/request/import_rules_schema'; -import { exactCheck } from '../../../common/exact_check'; -import { BadRequestError } from '../../lib/detection_engine/errors/bad_request_error'; export interface RulesObjectsExportResultDetails { /** number of successfully exported objects */ diff --git a/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/__snapshots__/confirm_delete_modal.test.tsx.snap b/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/__snapshots__/confirm_delete_modal.test.tsx.snap deleted file mode 100644 index 5bf93a1021c05..0000000000000 --- a/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/__snapshots__/confirm_delete_modal.test.tsx.snap +++ /dev/null @@ -1,93 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`ConfirmDeleteModal renders as expected 1`] = ` - - - - - - - - -

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

- - - -
-
- - - - - - - - -
-`; diff --git a/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/confirm_delete_modal.scss b/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/confirm_delete_modal.scss deleted file mode 100644 index 887495a231485..0000000000000 --- a/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/confirm_delete_modal.scss +++ /dev/null @@ -1,3 +0,0 @@ -.spcConfirmDeleteModal { - max-width: $euiFormMaxWidth + ($euiSizeL * 2); -} diff --git a/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/confirm_delete_modal.test.tsx b/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/confirm_delete_modal.test.tsx index 36d282a1cd653..59c7dde71aedb 100644 --- a/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/confirm_delete_modal.test.tsx +++ b/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/confirm_delete_modal.test.tsx @@ -6,10 +6,10 @@ */ import React from 'react'; +import { act } from 'react-dom/test-utils'; import { mountWithIntl, shallowWithIntl } from '@kbn/test/jest'; -import type { SpacesManager } from '../../../spaces_manager'; import { spacesManagerMock } from '../../../spaces_manager/mocks'; import { ConfirmDeleteModal } from './confirm_delete_modal'; @@ -22,25 +22,53 @@ describe('ConfirmDeleteModal', () => { }; const spacesManager = spacesManagerMock.create(); - spacesManager.getActiveSpace.mockResolvedValue(space); - const onCancel = jest.fn(); - const onConfirm = jest.fn(); expect( shallowWithIntl( - + ) - ).toMatchSnapshot(); + ).toMatchInlineSnapshot(` + + +

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

+

+ +

+
+
+ `); }); - it(`requires the space name to be typed before confirming`, () => { + it('deletes the space when confirmed', async () => { const space = { id: 'my-space', name: 'My Space', @@ -48,34 +76,23 @@ describe('ConfirmDeleteModal', () => { }; const spacesManager = spacesManagerMock.create(); - spacesManager.getActiveSpace.mockResolvedValue(space); - const onCancel = jest.fn(); - const onConfirm = jest.fn(); + const onSuccess = jest.fn(); const wrapper = mountWithIntl( - ); - const input = wrapper.find('input'); - expect(input).toHaveLength(1); - - input.simulate('change', { target: { value: 'My Invalid Space Name ' } }); - - const confirmButton = wrapper.find('button[data-test-subj="confirmModalConfirmButton"]'); - confirmButton.simulate('click'); - - expect(onConfirm).not.toHaveBeenCalled(); - - input.simulate('change', { target: { value: 'My Space' } }); - confirmButton.simulate('click'); + await act(async () => { + wrapper.find('EuiButton[data-test-subj="confirmModalConfirmButton"]').simulate('click'); + await spacesManager.deleteSpace.mock.results[0]; + }); - expect(onConfirm).toHaveBeenCalledTimes(1); + expect(spacesManager.deleteSpace).toHaveBeenLastCalledWith(space); }); }); diff --git a/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/confirm_delete_modal.tsx b/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/confirm_delete_modal.tsx index 100b5b6493e30..f3ed578a94962 100644 --- a/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/confirm_delete_modal.tsx +++ b/x-pack/plugins/spaces/public/management/components/confirm_delete_modal/confirm_delete_modal.tsx @@ -5,224 +5,127 @@ * 2.0. */ -import './confirm_delete_modal.scss'; - -import type { CommonProps, EuiModalProps } from '@elastic/eui'; -import { - EuiButton, - EuiButtonEmpty, - EuiCallOut, - EuiFieldText, - EuiFormRow, - EuiModal, - EuiModalBody, - EuiModalFooter, - EuiModalHeader, - EuiModalHeaderTitle, - EuiSpacer, - EuiText, -} from '@elastic/eui'; -import type { ChangeEvent } from 'react'; -import React, { Component } from 'react'; - -import type { InjectedIntl } from '@kbn/i18n/react'; -import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; +import { EuiCallOut, EuiConfirmModal, EuiSpacer, EuiText } from '@elastic/eui'; +import type { FunctionComponent } from 'react'; +import React from 'react'; +import useAsync from 'react-use/lib/useAsync'; +import useAsyncFn from 'react-use/lib/useAsyncFn'; + +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; import type { Space } from 'src/plugins/spaces_oss/common'; +import { useKibana } from '../../../../../../../src/plugins/kibana_react/public'; import type { SpacesManager } from '../../../spaces_manager'; interface Props { space: Space; spacesManager: SpacesManager; - onCancel: () => void; - onConfirm: () => void; - intl: InjectedIntl; -} - -interface State { - confirmSpaceName: string; - error: boolean | null; - deleteInProgress: boolean; - isDeletingCurrentSpace: boolean; + onCancel(): void; + onSuccess?(): void; } -class ConfirmDeleteModalUI extends Component { - public state = { - confirmSpaceName: '', - error: null, - deleteInProgress: false, - isDeletingCurrentSpace: false, - }; - - public componentDidMount() { - isCurrentSpace(this.props.space, this.props.spacesManager).then((result) => { - this.setState({ - isDeletingCurrentSpace: result, - }); - }); - } - - public render() { - const { space, onCancel, intl } = this.props; - const { isDeletingCurrentSpace } = this.state; - - let warning = null; - if (isDeletingCurrentSpace) { - const name = ( - - ({space.name}) - - ); - warning = ( - <> - - - - - - - +export const ConfirmDeleteModal: FunctionComponent = ({ + space, + onSuccess, + onCancel, + spacesManager, +}) => { + const { services } = useKibana(); + + const { value: isCurrentSpace } = useAsync( + async () => space.id === (await spacesManager.getActiveSpace()).id, + [space.id] + ); + + const [state, deleteSpace] = useAsyncFn(async () => { + try { + await spacesManager.deleteSpace(space); + services.notifications!.toasts.addSuccess( + i18n.translate('xpack.spaces.management.confirmDeleteModal.successMessage', { + defaultMessage: "Deleted space '{name}'", + values: { name: space.name }, + }) ); - } - - // This is largely the same as the built-in EuiConfirmModal component, but we needed the ability - // to disable the buttons since this could be a long-running operation - - const modalProps: Omit & CommonProps = { - onClose: onCancel, - className: 'spcConfirmDeleteModal', - initialFocus: 'input[name="confirmDeleteSpaceInput"]', - }; - - return ( - - - - - - - - -

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

- - - - - - {warning} -
-
- - - - - - - - - -
- ); - } - - private onSpaceNameChange = (e: ChangeEvent) => { - if (typeof this.state.error === 'boolean') { - this.setState({ - confirmSpaceName: e.target.value, - error: e.target.value !== this.props.space.name, - }); - } else { - this.setState({ - confirmSpaceName: e.target.value, - }); - } - }; - - private onConfirm = async () => { - if (this.state.confirmSpaceName === this.props.space.name) { - const needsRedirect = this.state.isDeletingCurrentSpace; - const spacesManager = this.props.spacesManager; - - this.setState({ - deleteInProgress: true, - }); - - await this.props.onConfirm(); - - this.setState({ - deleteInProgress: false, - }); - - if (needsRedirect) { + if (isCurrentSpace) { spacesManager.redirectToSpaceSelector(); + } else { + onSuccess?.(); } - } else { - this.setState({ - error: true, + } catch (error) { + services.notifications!.toasts.addDanger({ + title: i18n.translate('xpack.spaces.management.confirmDeleteModal.errorMessage', { + defaultMessage: "Could not delete space '{name}'", + values: { name: space.name }, + }), + text: (error as any).body?.message || error.message, }); } - }; -} - -async function isCurrentSpace(space: Space, spacesManager: SpacesManager) { - return space.id === (await spacesManager.getActiveSpace()).id; -} - -export const ConfirmDeleteModal = injectI18n(ConfirmDeleteModalUI); + }, [isCurrentSpace]); + + return ( + + {isCurrentSpace && ( + <> + + + + + + )} + +

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

+

+ +

+
+
+ ); +}; diff --git a/x-pack/plugins/spaces/public/management/edit_space/delete_spaces_button.tsx b/x-pack/plugins/spaces/public/management/edit_space/delete_spaces_button.tsx index d03b878cb19ab..92b68426d172e 100644 --- a/x-pack/plugins/spaces/public/management/edit_space/delete_spaces_button.tsx +++ b/x-pack/plugins/spaces/public/management/edit_space/delete_spaces_button.tsx @@ -95,44 +95,13 @@ export class DeleteSpacesButton extends Component { showConfirmDeleteModal: false, }); }} - onConfirm={this.deleteSpaces} + onSuccess={() => { + this.setState({ + showConfirmDeleteModal: false, + }); + this.props.onDelete?.(); + }} /> ); }; - - public deleteSpaces = async () => { - const { spacesManager, space } = this.props; - - this.setState({ - showConfirmDeleteModal: false, - }); - - try { - await spacesManager.deleteSpace(space); - } catch (error) { - const { message: errorMessage = '' } = error.data || error.body || {}; - - this.props.notifications.toasts.addDanger( - i18n.translate('xpack.spaces.management.deleteSpacesButton.deleteSpaceErrorTitle', { - defaultMessage: 'Error deleting space: {errorMessage}', - values: { errorMessage }, - }) - ); - return; - } - - const message = i18n.translate( - 'xpack.spaces.management.deleteSpacesButton.spaceSuccessfullyDeletedNotificationMessage', - { - defaultMessage: 'Deleted {spaceName} space.', - values: { spaceName: space.name }, - } - ); - - this.props.notifications.toasts.addSuccess(message); - - if (this.props.onDelete) { - this.props.onDelete(); - } - }; } diff --git a/x-pack/plugins/spaces/public/management/spaces_grid/__snapshots__/spaces_grid_pages.test.tsx.snap b/x-pack/plugins/spaces/public/management/spaces_grid/__snapshots__/spaces_grid_page.test.tsx.snap similarity index 100% rename from x-pack/plugins/spaces/public/management/spaces_grid/__snapshots__/spaces_grid_pages.test.tsx.snap rename to x-pack/plugins/spaces/public/management/spaces_grid/__snapshots__/spaces_grid_page.test.tsx.snap diff --git a/x-pack/plugins/spaces/public/management/spaces_grid/spaces_grid_pages.test.tsx b/x-pack/plugins/spaces/public/management/spaces_grid/spaces_grid_page.test.tsx similarity index 100% rename from x-pack/plugins/spaces/public/management/spaces_grid/spaces_grid_pages.test.tsx rename to x-pack/plugins/spaces/public/management/spaces_grid/spaces_grid_page.test.tsx diff --git a/x-pack/plugins/spaces/public/management/spaces_grid/spaces_grid_page.tsx b/x-pack/plugins/spaces/public/management/spaces_grid/spaces_grid_page.tsx index ac57a566e2a00..a4f797e441ab5 100644 --- a/x-pack/plugins/spaces/public/management/spaces_grid/spaces_grid_page.tsx +++ b/x-pack/plugins/spaces/public/management/spaces_grid/spaces_grid_page.tsx @@ -180,53 +180,16 @@ export class SpacesGridPage extends Component { showConfirmDeleteModal: false, }); }} - onConfirm={this.deleteSpace} + onSuccess={() => { + this.setState({ + showConfirmDeleteModal: false, + }); + this.loadGrid(); + }} /> ); }; - public deleteSpace = async () => { - const { spacesManager } = this.props; - - const space = this.state.selectedSpace; - - if (!space) { - return; - } - - this.setState({ - showConfirmDeleteModal: false, - }); - - try { - await spacesManager.deleteSpace(space); - } catch (error) { - const { message: errorMessage = '' } = error.data || error.body || {}; - - this.props.notifications.toasts.addDanger( - i18n.translate('xpack.spaces.management.spacesGridPage.errorDeletingSpaceErrorMessage', { - defaultMessage: 'Error deleting space: {errorMessage}', - values: { - errorMessage, - }, - }) - ); - return; - } - - this.loadGrid(); - - const message = i18n.translate( - 'xpack.spaces.management.spacesGridPage.spaceSuccessfullyDeletedNotificationMessage', - { - defaultMessage: 'Deleted "{spaceName}" space.', - values: { spaceName: space.name }, - } - ); - - this.props.notifications.toasts.addSuccess(message); - }; - public loadGrid = async () => { const { spacesManager, getFeatures, notifications } = this.props; diff --git a/x-pack/plugins/spaces/public/management/spaces_management_app.tsx b/x-pack/plugins/spaces/public/management/spaces_management_app.tsx index da0f9157f310d..c97ec5fbcc227 100644 --- a/x-pack/plugins/spaces/public/management/spaces_management_app.tsx +++ b/x-pack/plugins/spaces/public/management/spaces_management_app.tsx @@ -14,7 +14,10 @@ import type { StartServicesAccessor } from 'src/core/public'; import type { RegisterManagementAppArgs } from 'src/plugins/management/public'; import type { Space } from 'src/plugins/spaces_oss/common'; -import { RedirectAppLinks } from '../../../../../src/plugins/kibana_react/public'; +import { + KibanaContextProvider, + RedirectAppLinks, +} from '../../../../../src/plugins/kibana_react/public'; import type { PluginsStart } from '../plugin'; import type { SpacesManager } from '../spaces_manager'; @@ -36,22 +39,23 @@ export const spacesManagementApp = Object.freeze({ title, async mount({ element, setBreadcrumbs, history }) { - const [startServices, { SpacesGridPage }, { ManageSpacePage }] = await Promise.all([ + const [ + [coreStart, { features }], + { SpacesGridPage }, + { ManageSpacePage }, + ] = await Promise.all([ getStartServices(), import('./spaces_grid'), import('./edit_space'), ]); - const [ - { notifications, i18n: i18nStart, application, chrome }, - { features }, - ] = startServices; const spacesBreadcrumbs = [ { text: title, href: `/`, }, ]; + const { notifications, i18n: i18nStart, application, chrome } = coreStart; chrome.docTitle.change(title); @@ -119,23 +123,25 @@ export const spacesManagementApp = Object.freeze({ }; render( - - - - - - - - - - - - - - - - - , + + + + + + + + + + + + + + + + + + + , element ); diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index ae61f24201ce5..a2615ae9713a2 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -9514,7 +9514,6 @@ "xpack.fleet.fleetServerUpgradeModal.breakingChangeMessage": "これは大きい変更であるため、ベータリリースにしています。ご不便をおかけしていることをお詫び申し上げます。ご質問がある場合や、サポートが必要な場合は、{link}を共有してください。", "xpack.fleet.fleetServerUpgradeModal.checkboxLabel": "次回以降このメッセージを表示しない", "xpack.fleet.fleetServerUpgradeModal.closeButton": "閉じて開始する", - "xpack.fleet.fleetServerUpgradeModal.cloudDescriptionMessage": "Fleetサーバーを使用できます。スケーラビリティとセキュリティが強化されました。すでにElastic CloudでAPMを使用している場合は、APM & Fleetにアップグレードされました。{existingAgentsMessage} Fleetを使用し続けるには、Fleetサーバーと新しいバージョンのElasticエージェントを各ホストにインストールする必要があります。詳細については、{link}をご覧ください。", "xpack.fleet.fleetServerUpgradeModal.existingAgentText": "既存のElasticエージェントは自動的に登録解除され、データの送信を停止しました。", "xpack.fleet.fleetServerUpgradeModal.failedUpdateTitle": "設定の保存エラー", "xpack.fleet.fleetServerUpgradeModal.fleetFeedbackLink": "フィードバック", @@ -22651,13 +22650,6 @@ "xpack.spaces.management.confirmAlterActiveSpaceModal.reloadWarningMessage": "このスペースで表示される機能を更新しました。保存後にページが更新されます。", "xpack.spaces.management.confirmAlterActiveSpaceModal.title": "スペースの更新の確認", "xpack.spaces.management.confirmAlterActiveSpaceModal.updateSpaceButton": "スペースを更新", - "xpack.spaces.management.confirmDeleteModal.allContentsText": "すべてのコンテンツ", - "xpack.spaces.management.confirmDeleteModal.cancelButtonLabel": "キャンセル", - "xpack.spaces.management.confirmDeleteModal.confirmDeleteSpaceButtonLabel": "スペース {spaceName} を削除", - "xpack.spaces.management.confirmDeleteModal.confirmSpaceNameFormRowLabel": "削除するスペース名の確定", - "xpack.spaces.management.confirmDeleteModal.deleteSpaceAndAllContentsButtonLabel": " スペースとすべてのコンテンツを削除", - "xpack.spaces.management.confirmDeleteModal.redirectAfterDeletingCurrentSpaceWarningMessage": "現在のスペース {name} を削除しようとしています。続行すると、別のスペースを選択する画面に移動します。", - "xpack.spaces.management.confirmDeleteModal.spaceNamesDoNoMatchErrorMessage": "スペース名が一致していません。", "xpack.spaces.management.copyToSpace.actionDescription": "1つ以上のスペースでこの保存されたオブジェクトのコピーを作成します", "xpack.spaces.management.copyToSpace.actionTitle": "スペースにコピー", "xpack.spaces.management.copyToSpace.cancelButton": "キャンセル", @@ -22722,8 +22714,6 @@ "xpack.spaces.management.customizeSpaceAvatar.selectImageUrl": "画像ファイルを選択", "xpack.spaces.management.deleteSpacesButton.deleteSpaceAriaLabel": "スペースを削除", "xpack.spaces.management.deleteSpacesButton.deleteSpaceButtonLabel": "スペースを削除", - "xpack.spaces.management.deleteSpacesButton.deleteSpaceErrorTitle": "スペースの削除中にエラーが発生:{errorMessage}", - "xpack.spaces.management.deleteSpacesButton.spaceSuccessfullyDeletedNotificationMessage": "{spaceName} スペースが削除されました。", "xpack.spaces.management.deselectAllFeaturesLink": "すべて選択解除", "xpack.spaces.management.enabledFeatures.featureCategoryButtonLabel": "カテゴリ切り替え", "xpack.spaces.management.enabledSpaceFeatures.allFeaturesEnabledMessage": " (表示されているすべての機能) ", @@ -22739,7 +22729,6 @@ "xpack.spaces.management.manageSpacePage.avatarFormRowLabel": "アバター", "xpack.spaces.management.manageSpacePage.awesomeSpacePlaceholder": "素晴らしいスペース", "xpack.spaces.management.manageSpacePage.cancelSpaceButton": "キャンセル", - "xpack.spaces.management.manageSpacePage.clickToCustomizeTooltip": "クリックしてこのスペースのアバターをカスタマイズします", "xpack.spaces.management.manageSpacePage.createSpaceButton": "スペースを作成", "xpack.spaces.management.manageSpacePage.createSpaceTitle": "スペースの作成", "xpack.spaces.management.manageSpacePage.customizeSpacePanelDescription": "スペースに名前を付けてアバターをカスタマイズします。", @@ -22774,7 +22763,6 @@ "xpack.spaces.management.spacesGridPage.deleteActionName": "{spaceName} を削除。", "xpack.spaces.management.spacesGridPage.descriptionColumnName": "説明", "xpack.spaces.management.spacesGridPage.editSpaceActionName": "{spaceName} を編集。", - "xpack.spaces.management.spacesGridPage.errorDeletingSpaceErrorMessage": "スペースの削除中にエラーが発生:{errorMessage}", "xpack.spaces.management.spacesGridPage.errorTitle": "スペースの読み込みエラー", "xpack.spaces.management.spacesGridPage.featuresColumnName": "機能", "xpack.spaces.management.spacesGridPage.identifierColumnName": "識別子", @@ -22784,7 +22772,6 @@ "xpack.spaces.management.spacesGridPage.someFeaturesEnabled": "{totalFeatureCount} 件中 {enabledFeatureCount} 件の機能を表示中", "xpack.spaces.management.spacesGridPage.spaceColumnName": "スペース", "xpack.spaces.management.spacesGridPage.spacesTitle": "スペース", - "xpack.spaces.management.spacesGridPage.spaceSuccessfullyDeletedNotificationMessage": "「{spaceName}」スペースが削除されました。", "xpack.spaces.management.spacesGridPage.tableCaption": "Kibana スペース", "xpack.spaces.management.toggleAllFeaturesLink": " (すべて変更) ", "xpack.spaces.management.unauthorizedPrompt.permissionDeniedDescription": "スペースを管理するアクセス権がありません。", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index ecd6c0d68a94f..a6cf8e5ddb865 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -9603,7 +9603,6 @@ "xpack.fleet.fleetServerUpgradeModal.breakingChangeMessage": "这是一项重大更改,所以我们在公测版中进行该更改。非常抱歉带来不便。如果您有疑问或需要帮助,请共享 {link}。", "xpack.fleet.fleetServerUpgradeModal.checkboxLabel": "不再显示此消息", "xpack.fleet.fleetServerUpgradeModal.closeButton": "关闭并开始使用", - "xpack.fleet.fleetServerUpgradeModal.cloudDescriptionMessage": "Fleet 服务器现在可用并提供改善的可扩展性和安全性。如果在 Elastic Cloud 上已有 APM,则我们已将其升级到 APM & Fleet。{existingAgentsMessage}要继续使用 Fleet,必须在各个主机上安装 Fleet 服务器和新版 Elastic 代理。详细了解我们的 {link}。", "xpack.fleet.fleetServerUpgradeModal.existingAgentText": "您现有的 Elastic 代理已被自动销注且已停止发送数据。", "xpack.fleet.fleetServerUpgradeModal.failedUpdateTitle": "保存设置时出错", "xpack.fleet.fleetServerUpgradeModal.fleetFeedbackLink": "反馈", @@ -23010,14 +23009,6 @@ "xpack.spaces.management.confirmAlterActiveSpaceModal.reloadWarningMessage": "您已更新此工作区中的可见功能。保存后,您的页面将重新加载。", "xpack.spaces.management.confirmAlterActiveSpaceModal.title": "确认更新工作区", "xpack.spaces.management.confirmAlterActiveSpaceModal.updateSpaceButton": "更新工作区", - "xpack.spaces.management.confirmDeleteModal.allContentsText": "所有内容", - "xpack.spaces.management.confirmDeleteModal.cancelButtonLabel": "取消", - "xpack.spaces.management.confirmDeleteModal.confirmDeleteSpaceButtonLabel": "删除空间 {spaceName}", - "xpack.spaces.management.confirmDeleteModal.confirmSpaceNameFormRowLabel": "确认要删除的工作区名称", - "xpack.spaces.management.confirmDeleteModal.deleteSpaceAndAllContentsButtonLabel": " 删除空间及其所有内容", - "xpack.spaces.management.confirmDeleteModal.deletingSpaceWarningMessage": "删除空间会永久删除空间及{allContents}。此操作无法撤消。", - "xpack.spaces.management.confirmDeleteModal.redirectAfterDeletingCurrentSpaceWarningMessage": "您即将删除当前空间 {name}。如果继续,您将会被重定向以选择其他空间的位置。", - "xpack.spaces.management.confirmDeleteModal.spaceNamesDoNoMatchErrorMessage": "空间名称不匹配。", "xpack.spaces.management.copyToSpace.actionDescription": "在一个或多个工作区中创建此已保存对象的副本", "xpack.spaces.management.copyToSpace.actionTitle": "复制到工作区", "xpack.spaces.management.copyToSpace.cancelButton": "取消", @@ -23083,8 +23074,6 @@ "xpack.spaces.management.customizeSpaceAvatar.selectImageUrl": "选择图像文件", "xpack.spaces.management.deleteSpacesButton.deleteSpaceAriaLabel": "删除此空间", "xpack.spaces.management.deleteSpacesButton.deleteSpaceButtonLabel": "删除空间", - "xpack.spaces.management.deleteSpacesButton.deleteSpaceErrorTitle": "删除空间时出错:{errorMessage}", - "xpack.spaces.management.deleteSpacesButton.spaceSuccessfullyDeletedNotificationMessage": "已删除 {spaceName} 空间。", "xpack.spaces.management.deselectAllFeaturesLink": "取消全选", "xpack.spaces.management.enabledFeatures.featureCategoryButtonLabel": "类别切换", "xpack.spaces.management.enabledSpaceFeatures.allFeaturesEnabledMessage": " (所有可见功能) ", @@ -23100,7 +23089,6 @@ "xpack.spaces.management.manageSpacePage.avatarFormRowLabel": "头像", "xpack.spaces.management.manageSpacePage.awesomeSpacePlaceholder": "超卓的空间", "xpack.spaces.management.manageSpacePage.cancelSpaceButton": "取消", - "xpack.spaces.management.manageSpacePage.clickToCustomizeTooltip": "单击可定制此工作区头像", "xpack.spaces.management.manageSpacePage.createSpaceButton": "创建工作区", "xpack.spaces.management.manageSpacePage.createSpaceTitle": "创建一个空间", "xpack.spaces.management.manageSpacePage.customizeSpacePanelDescription": "命名您的工作区并定制其头像。", @@ -23135,7 +23123,6 @@ "xpack.spaces.management.spacesGridPage.deleteActionName": "删除 {spaceName}。", "xpack.spaces.management.spacesGridPage.descriptionColumnName": "描述", "xpack.spaces.management.spacesGridPage.editSpaceActionName": "编辑 {spaceName}。", - "xpack.spaces.management.spacesGridPage.errorDeletingSpaceErrorMessage": "删除空间时出错:{errorMessage}", "xpack.spaces.management.spacesGridPage.errorTitle": "加载工作区时出错", "xpack.spaces.management.spacesGridPage.featuresColumnName": "功能", "xpack.spaces.management.spacesGridPage.identifierColumnName": "标识符", @@ -23145,7 +23132,6 @@ "xpack.spaces.management.spacesGridPage.someFeaturesEnabled": "{enabledFeatureCount} / {totalFeatureCount} 个功能可见", "xpack.spaces.management.spacesGridPage.spaceColumnName": "工作区", "xpack.spaces.management.spacesGridPage.spacesTitle": "工作区", - "xpack.spaces.management.spacesGridPage.spaceSuccessfullyDeletedNotificationMessage": "已删除“{spaceName}”工作区。", "xpack.spaces.management.spacesGridPage.tableCaption": "Kibana 工作区", "xpack.spaces.management.toggleAllFeaturesLink": " (全部更改) ", "xpack.spaces.management.unauthorizedPrompt.permissionDeniedDescription": "您无权管理工作区。", diff --git a/x-pack/plugins/uptime/public/components/fleet_package/combo_box.tsx b/x-pack/plugins/uptime/public/components/fleet_package/combo_box.tsx index 12ee154dbcac4..7a1df79b0a59a 100644 --- a/x-pack/plugins/uptime/public/components/fleet_package/combo_box.tsx +++ b/x-pack/plugins/uptime/public/components/fleet_package/combo_box.tsx @@ -13,7 +13,7 @@ export interface Props { selectedOptions: string[]; } -export const ComboBox = ({ onChange, selectedOptions }: Props) => { +export const ComboBox = ({ onChange, selectedOptions, ...props }: Props) => { const [formattedSelectedOptions, setSelectedOptions] = useState< Array> >(selectedOptions.map((option) => ({ label: option, key: option }))); @@ -66,6 +66,7 @@ export const ComboBox = ({ onChange, selectedOptions }: Props) => { onChange={onOptionsChange} onSearchChange={onSearchChange} isInvalid={isInvalid} + {...props} /> ); }; diff --git a/x-pack/plugins/uptime/public/components/fleet_package/custom_fields.tsx b/x-pack/plugins/uptime/public/components/fleet_package/custom_fields.tsx index 0bc2fc8823cec..e6703a6eaa97c 100644 --- a/x-pack/plugins/uptime/public/components/fleet_package/custom_fields.tsx +++ b/x-pack/plugins/uptime/public/components/fleet_package/custom_fields.tsx @@ -76,6 +76,7 @@ export const CustomFields = memo( defaultMessage="Configure your monitor with the following options." /> } + data-test-subj="monitorSettingsSection" > @@ -104,6 +105,7 @@ export const CustomFields = memo( configKey: ConfigKeys.MONITOR_TYPE, }) } + data-test-subj="syntheticsMonitorTypeField" /> )} @@ -128,6 +130,7 @@ export const CustomFields = memo( onChange={(event) => handleInputChange({ value: event.target.value, configKey: ConfigKeys.URLS }) } + data-test-subj="syntheticsUrlField" /> )} @@ -155,6 +158,7 @@ export const CustomFields = memo( configKey: ConfigKeys.HOSTS, }) } + data-test-subj="syntheticsTCPHostField" /> )} @@ -182,6 +186,7 @@ export const CustomFields = memo( configKey: ConfigKeys.HOSTS, }) } + data-test-subj="syntheticsICMPHostField" /> )} @@ -268,6 +273,7 @@ export const CustomFields = memo( configKey: ConfigKeys.APM_SERVICE_NAME, }) } + data-test-subj="syntheticsAPMServiceName" /> {isHTTP && ( @@ -364,6 +370,7 @@ export const CustomFields = memo( handleInputChange({ value, configKey: ConfigKeys.TAGS })} + data-test-subj="syntheticsTags" /> @@ -385,6 +392,7 @@ export const CustomFields = memo( defaultMessage="Configure TLS options, including verification mode, certificate authorities, and client certificates." /> } + data-test-subj="syntheticsIsTLSEnabled" > (({ validate }) => { defaultMessage="Advanced HTTP options" /> } + data-test-subj="syntheticsHTTPAdvancedFieldsAccordion" > (({ validate }) => { defaultMessage="Configure an optional request to send to the remote host including method, body, and headers." /> } + data-test-subj="httpAdvancedFieldsSection" > (({ validate }) => { configKey: ConfigKeys.USERNAME, }) } + data-test-subj="syntheticsUsername" /> (({ validate }) => { configKey: ConfigKeys.PASSWORD, }) } + data-test-subj="syntheticsPassword" /> (({ validate }) => { configKey: ConfigKeys.PROXY_URL, }) } + data-test-subj="syntheticsProxyUrl" /> (({ validate }) => { configKey: ConfigKeys.REQUEST_METHOD_CHECK, }) } + data-test-subj="syntheticsRequestMethod" /> (({ validate }) => { defaultMessage="A dictionary of additional HTTP headers to send. By default the client will set the User-Agent header to identify itself." /> } + data-test-subj="syntheticsRequestHeaders" > (({ validate }) => { http.response.body.headers } + data-test-subj="syntheticsIndexResponseHeaders" > (({ validate }) => { configKey: ConfigKeys.RESPONSE_STATUS_CHECK, }) } + data-test-subj="syntheticsResponseStatusCheck" /> (({ validate }) => { defaultMessage="A list of expected response headers." /> } + data-test-subj="syntheticsResponseHeaders" > (({ validate }) => { }), [handleInputChange] )} + data-test-subj="syntheticsResponseBodyCheckPositive" /> (({ validate }) => { }), [handleInputChange] )} + data-test-subj="syntheticsResponseBodyCheckNegative" /> diff --git a/x-pack/plugins/uptime/public/components/fleet_package/index_response_body_field.tsx b/x-pack/plugins/uptime/public/components/fleet_package/index_response_body_field.tsx index a82e7a0938078..fc53b275f0828 100644 --- a/x-pack/plugins/uptime/public/components/fleet_package/index_response_body_field.tsx +++ b/x-pack/plugins/uptime/public/components/fleet_package/index_response_body_field.tsx @@ -38,7 +38,7 @@ export const ResponseBodyIndexField = ({ defaultValue, onChange }: Props) => { return ( - + { { id: Mode.TEXT, name: modeLabels[Mode.TEXT], + 'data-test-subj': `syntheticsRequestBodyTab__${Mode.TEXT}`, content: ( { { id: Mode.JSON, name: modeLabels[Mode.JSON], + 'data-test-subj': `syntheticsRequestBodyTab__${Mode.JSON}`, content: ( { { id: Mode.XML, name: modeLabels[Mode.XML], + 'data-test-subj': `syntheticsRequestBodyTab__${Mode.XML}`, content: ( { { id: Mode.FORM, name: modeLabels[Mode.FORM], + 'data-test-subj': `syntheticsRequestBodyTab__${Mode.FORM}`, content: ( { ); return ( - + { configKey: ConfigKeys.PROXY_URL, }) } + data-test-subj="syntheticsProxyUrl" /> {!!fields[ConfigKeys.PROXY_URL] && ( - + { }), [handleInputChange] )} + data-test-subj="syntheticsTCPRequestSendCheck" /> @@ -166,6 +172,7 @@ export const TCPAdvancedFields = () => { }), [handleInputChange] )} + data-test-subj="syntheticsTCPResponseReceiveCheck" /> diff --git a/x-pack/plugins/uptime/public/components/fleet_package/tls_fields.tsx b/x-pack/plugins/uptime/public/components/fleet_package/tls_fields.tsx index de8879ec3a819..a2db0d99088f7 100644 --- a/x-pack/plugins/uptime/public/components/fleet_package/tls_fields.tsx +++ b/x-pack/plugins/uptime/public/components/fleet_package/tls_fields.tsx @@ -139,6 +139,7 @@ export const TLSFields: React.FunctionComponent<{ }, })); }} + data-test-subj="syntheticsTLSVerificationMode" /> {fields[ConfigKeys.TLS_VERIFICATION_MODE].value === VerificationMode.NONE && ( @@ -229,6 +230,7 @@ export const TLSFields: React.FunctionComponent<{ }, })); }} + data-test-subj="syntheticsTLSCA" /> diff --git a/x-pack/test/accessibility/apps/spaces.ts b/x-pack/test/accessibility/apps/spaces.ts index a08ae474497e5..6242896c263ba 100644 --- a/x-pack/test/accessibility/apps/spaces.ts +++ b/x-pack/test/accessibility/apps/spaces.ts @@ -111,14 +111,10 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.spaceSelector.clickManageSpaces(); await PageObjects.spaceSelector.clickOnDeleteSpaceButton('space_b'); await a11y.testAppSnapshot(); - // a11y test for no space name in confirm dialogue box - await PageObjects.spaceSelector.confirmDeletingSpace(); - await a11y.testAppSnapshot(); }); // test starts with deleting space b so we can get the space selection page instead of logging out in the test it('a11y test for space selection page', async () => { - await PageObjects.spaceSelector.setSpaceNameTobeDeleted('space_b'); await PageObjects.spaceSelector.confirmDeletingSpace(); await a11y.testAppSnapshot(); await PageObjects.spaceSelector.clickSpaceCard('default'); diff --git a/x-pack/test/accessibility/config.ts b/x-pack/test/accessibility/config.ts index 5b46e7de1efa4..81cfd70a23956 100644 --- a/x-pack/test/accessibility/config.ts +++ b/x-pack/test/accessibility/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; import { pageObjects } from './page_objects'; diff --git a/x-pack/test/accessibility/ftr_provider_context.d.ts b/x-pack/test/accessibility/ftr_provider_context.d.ts index ec28c00e72e47..24f5087ef7fe2 100644 --- a/x-pack/test/accessibility/ftr_provider_context.d.ts +++ b/x-pack/test/accessibility/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { services } from './services'; diff --git a/x-pack/test/alerting_api_integration/common/config.ts b/x-pack/test/alerting_api_integration/common/config.ts index 7844eaf3920c6..8647c5951b7f3 100644 --- a/x-pack/test/alerting_api_integration/common/config.ts +++ b/x-pack/test/alerting_api_integration/common/config.ts @@ -9,7 +9,7 @@ import path from 'path'; import getPort from 'get-port'; import fs from 'fs'; import { CA_CERT_PATH } from '@kbn/dev-utils'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; import { getAllExternalServiceSimulatorPaths } from './fixtures/plugins/actions_simulators/server/plugin'; import { getTlsWebhookServerUrls } from './lib/get_tls_webhook_servers'; diff --git a/x-pack/test/alerting_api_integration/common/ftr_provider_context.d.ts b/x-pack/test/alerting_api_integration/common/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/alerting_api_integration/common/ftr_provider_context.d.ts +++ b/x-pack/test/alerting_api_integration/common/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/api_integration/config.ts b/x-pack/test/api_integration/config.ts index 9fd7afbfacc40..5c998a4322480 100644 --- a/x-pack/test/api_integration/config.ts +++ b/x-pack/test/api_integration/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; export async function getApiIntegrationConfig({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/api_integration/config_security_basic.ts b/x-pack/test/api_integration/config_security_basic.ts index d4ff1574fa4ad..fc32e66c63e9e 100644 --- a/x-pack/test/api_integration/config_security_basic.ts +++ b/x-pack/test/api_integration/config_security_basic.ts @@ -7,7 +7,7 @@ /* eslint-disable import/no-default-export */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { default as createTestConfig } from './config'; export default async function (context: FtrConfigProviderContext) { diff --git a/x-pack/test/api_integration/config_security_trial.ts b/x-pack/test/api_integration/config_security_trial.ts index 441305e4ce7ed..93b1eefd350e9 100644 --- a/x-pack/test/api_integration/config_security_trial.ts +++ b/x-pack/test/api_integration/config_security_trial.ts @@ -7,7 +7,7 @@ /* eslint-disable import/no-default-export */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { default as createTestConfig } from './config'; export default async function (context: FtrConfigProviderContext) { diff --git a/x-pack/test/api_integration/ftr_provider_context.d.ts b/x-pack/test/api_integration/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/api_integration/ftr_provider_context.d.ts +++ b/x-pack/test/api_integration/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/api_integration_basic/config.ts b/x-pack/test/api_integration_basic/config.ts index 3e24e49d620de..446f8e07679e3 100644 --- a/x-pack/test/api_integration_basic/config.ts +++ b/x-pack/test/api_integration_basic/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const xpackApiIntegrationConfig = await readConfigFile( diff --git a/x-pack/test/api_integration_basic/ftr_provider_context.d.ts b/x-pack/test/api_integration_basic/ftr_provider_context.d.ts index db8621db0136e..63c97af0ed22a 100644 --- a/x-pack/test/api_integration_basic/ftr_provider_context.d.ts +++ b/x-pack/test/api_integration_basic/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from '../api_integration/services'; diff --git a/x-pack/test/apm_api_integration/common/config.ts b/x-pack/test/apm_api_integration/common/config.ts index 732f14d2a7bc8..68a0c6b4e9f1c 100644 --- a/x-pack/test/apm_api_integration/common/config.ts +++ b/x-pack/test/apm_api_integration/common/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import supertest from 'supertest'; import { format, UrlObject } from 'url'; import path from 'path'; diff --git a/x-pack/test/apm_api_integration/common/ftr_provider_context.ts b/x-pack/test/apm_api_integration/common/ftr_provider_context.ts index 7ca731854152b..cac4304696431 100644 --- a/x-pack/test/apm_api_integration/common/ftr_provider_context.ts +++ b/x-pack/test/apm_api_integration/common/ftr_provider_context.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { FtrProviderContext as InheritedFtrProviderContext } from '../../api_integration/ftr_provider_context'; import { ApmServices } from './config'; diff --git a/x-pack/test/banners_functional/config.ts b/x-pack/test/banners_functional/config.ts index 21cce31ca5d85..a4b2867b8d7ce 100644 --- a/x-pack/test/banners_functional/config.ts +++ b/x-pack/test/banners_functional/config.ts @@ -6,7 +6,7 @@ */ import path from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services, pageObjects } from './ftr_provider_context'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/banners_functional/ftr_provider_context.ts b/x-pack/test/banners_functional/ftr_provider_context.ts index faac2954b00f6..c641b4efcc493 100644 --- a/x-pack/test/banners_functional/ftr_provider_context.ts +++ b/x-pack/test/banners_functional/ftr_provider_context.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from '../functional/services'; import { pageObjects } from '../functional/page_objects'; diff --git a/x-pack/test/case_api_integration/common/config.ts b/x-pack/test/case_api_integration/common/config.ts index 3c81407276453..8beabe450f66e 100644 --- a/x-pack/test/case_api_integration/common/config.ts +++ b/x-pack/test/case_api_integration/common/config.ts @@ -6,7 +6,7 @@ */ import { CA_CERT_PATH } from '@kbn/dev-utils'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import path from 'path'; import fs from 'fs'; diff --git a/x-pack/test/case_api_integration/common/ftr_provider_context.d.ts b/x-pack/test/case_api_integration/common/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/case_api_integration/common/ftr_provider_context.d.ts +++ b/x-pack/test/case_api_integration/common/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/common/ftr_provider_context.ts b/x-pack/test/common/ftr_provider_context.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/common/ftr_provider_context.ts +++ b/x-pack/test/common/ftr_provider_context.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/detection_engine_api_integration/common/config.ts b/x-pack/test/detection_engine_api_integration/common/config.ts index 355703ae35052..659c836eb9207 100644 --- a/x-pack/test/detection_engine_api_integration/common/config.ts +++ b/x-pack/test/detection_engine_api_integration/common/config.ts @@ -6,7 +6,7 @@ */ import { CA_CERT_PATH } from '@kbn/dev-utils'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; interface CreateTestConfigOptions { diff --git a/x-pack/test/detection_engine_api_integration/common/ftr_provider_context.d.ts b/x-pack/test/detection_engine_api_integration/common/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/detection_engine_api_integration/common/ftr_provider_context.d.ts +++ b/x-pack/test/detection_engine_api_integration/common/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/finalize_signals_migrations.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/finalize_signals_migrations.ts index e65086b43a377..6ab23edae9b3b 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/finalize_signals_migrations.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/finalize_signals_migrations.ts @@ -47,7 +47,8 @@ export default ({ getService }: FtrProviderContext): void => { const supertest = getService('supertest'); const supertestWithoutAuth = getService('supertestWithoutAuth'); - describe('Finalizing signals migrations', () => { + // FAILING ES PROMOTION: https://github.com/elastic/kibana/issues/99915 + describe.skip('Finalizing signals migrations', () => { let legacySignalsIndexName: string; let outdatedSignalsIndexName: string; let createdMigrations: CreateResponse[]; diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/get_signals_migration_status.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/get_signals_migration_status.ts index 793dec9eaae4b..869d1672150cc 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/get_signals_migration_status.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/get_signals_migration_status.ts @@ -19,7 +19,8 @@ export default ({ getService }: FtrProviderContext): void => { const supertest = getService('supertest'); const supertestWithoutAuth = getService('supertestWithoutAuth'); - describe('Signals migration status', () => { + // FAILING ES PROMOTION: https://github.com/elastic/kibana/issues/99915 + describe.skip('Signals migration status', () => { let legacySignalsIndexName: string; beforeEach(async () => { await createSignalsIndex(supertest); diff --git a/x-pack/test/detection_engine_api_integration/utils.ts b/x-pack/test/detection_engine_api_integration/utils.ts index 0f57728f99d67..d8466f013a110 100644 --- a/x-pack/test/detection_engine_api_integration/utils.ts +++ b/x-pack/test/detection_engine_api_integration/utils.ts @@ -12,8 +12,8 @@ import { SuperTest } from 'supertest'; import supertestAsPromised from 'supertest-as-promised'; import { Context } from '@elastic/elasticsearch/lib/Transport'; import { SearchResponse } from 'elasticsearch'; +import { NonEmptyEntriesArray } from '@kbn/securitysolution-io-ts-list-types'; import { PrePackagedRulesAndTimelinesStatusSchema } from '../../plugins/security_solution/common/detection_engine/schemas/response'; -import { NonEmptyEntriesArray } from '../../plugins/lists/common/schemas'; import { getCreateExceptionListDetectionSchemaMock } from '../../plugins/lists/common/schemas/request/create_exception_list_schema.mock'; import { CreateRulesSchema, diff --git a/x-pack/test/encrypted_saved_objects_api_integration/config.ts b/x-pack/test/encrypted_saved_objects_api_integration/config.ts index 71903fe6c73a8..9305431711de6 100644 --- a/x-pack/test/encrypted_saved_objects_api_integration/config.ts +++ b/x-pack/test/encrypted_saved_objects_api_integration/config.ts @@ -6,7 +6,7 @@ */ import path from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/encrypted_saved_objects_api_integration/ftr_provider_context.d.ts b/x-pack/test/encrypted_saved_objects_api_integration/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/encrypted_saved_objects_api_integration/ftr_provider_context.d.ts +++ b/x-pack/test/encrypted_saved_objects_api_integration/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/endpoint_api_integration_no_ingest/config.ts b/x-pack/test/endpoint_api_integration_no_ingest/config.ts index 9670d809699b7..c6837256cf61b 100644 --- a/x-pack/test/endpoint_api_integration_no_ingest/config.ts +++ b/x-pack/test/endpoint_api_integration_no_ingest/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const xPackAPITestsConfig = await readConfigFile(require.resolve('../api_integration/config.ts')); diff --git a/x-pack/test/endpoint_api_integration_no_ingest/ftr_provider_context.d.ts b/x-pack/test/endpoint_api_integration_no_ingest/ftr_provider_context.d.ts index db8621db0136e..63c97af0ed22a 100644 --- a/x-pack/test/endpoint_api_integration_no_ingest/ftr_provider_context.d.ts +++ b/x-pack/test/endpoint_api_integration_no_ingest/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from '../api_integration/services'; diff --git a/x-pack/test/examples/config.ts b/x-pack/test/examples/config.ts index fe1b5ce299447..491c23a33a3ef 100644 --- a/x-pack/test/examples/config.ts +++ b/x-pack/test/examples/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { resolve } from 'path'; import fs from 'fs'; // @ts-expect-error https://github.com/elastic/kibana/issues/95679 diff --git a/x-pack/test/fleet_api_integration/config.ts b/x-pack/test/fleet_api_integration/config.ts index 2344bdc32904a..cd47da8ef5fc3 100644 --- a/x-pack/test/fleet_api_integration/config.ts +++ b/x-pack/test/fleet_api_integration/config.ts @@ -7,7 +7,7 @@ import path from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { defineDockerServersConfig } from '@kbn/test'; // Docker image to use for Fleet API integration tests. diff --git a/x-pack/test/fleet_functional/config.ts b/x-pack/test/fleet_functional/config.ts index 386f39d7ec668..15d0c72ffc603 100644 --- a/x-pack/test/fleet_functional/config.ts +++ b/x-pack/test/fleet_functional/config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { services } from './services'; diff --git a/x-pack/test/fleet_functional/ftr_provider_context.d.ts b/x-pack/test/fleet_functional/ftr_provider_context.d.ts index ec28c00e72e47..24f5087ef7fe2 100644 --- a/x-pack/test/fleet_functional/ftr_provider_context.d.ts +++ b/x-pack/test/fleet_functional/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { services } from './services'; diff --git a/x-pack/test/functional/apps/dashboard/dashboard_lens_by_value.ts b/x-pack/test/functional/apps/dashboard/dashboard_lens_by_value.ts index 87ecfe0dcada9..865f4c64f0f1a 100644 --- a/x-pack/test/functional/apps/dashboard/dashboard_lens_by_value.ts +++ b/x-pack/test/functional/apps/dashboard/dashboard_lens_by_value.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; export default function ({ getPageObjects, getService }: FtrProviderContext) { - const PageObjects = getPageObjects(['common', 'dashboard', 'visualize', 'lens', 'header']); + const PageObjects = getPageObjects(['common', 'dashboard', 'visualize', 'lens', 'timePicker']); const find = getService('find'); const esArchiver = getService('esArchiver'); @@ -69,11 +69,10 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { expect(titles.indexOf(newTitle)).to.not.be(-1); }); - it('is no longer linked to a dashboard after visiting the visuali1ze listing page', async () => { - await PageObjects.visualize.gotoVisualizationLandingPage(); + it('is no longer linked to a dashboard after visiting the visualize listing page', async () => { await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickLensWidget(); - await PageObjects.header.waitUntilLoadingHasFinished(); + await PageObjects.timePicker.ensureHiddenNoDataPopover(); await PageObjects.lens.configureDimension({ dimension: 'lnsXY_xDimensionPanel > lns-empty-dimension', operation: 'date_histogram', @@ -84,8 +83,8 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { operation: 'average', field: 'bytes', }); + await PageObjects.lens.waitForVisualization(); await PageObjects.lens.notLinkedToOriginatingApp(); - await PageObjects.header.waitUntilLoadingHasFinished(); // return to origin should not be present in save modal await testSubjects.click('lnsApp_saveButton'); diff --git a/x-pack/test/functional/apps/spaces/enter_space.ts b/x-pack/test/functional/apps/spaces/enter_space.ts index 4e4d4974ced09..e8a67f8899a36 100644 --- a/x-pack/test/functional/apps/spaces/enter_space.ts +++ b/x-pack/test/functional/apps/spaces/enter_space.ts @@ -14,7 +14,8 @@ export default function enterSpaceFunctonalTests({ const esArchiver = getService('esArchiver'); const PageObjects = getPageObjects(['security', 'spaceSelector']); - describe('Enter Space', function () { + // FLAKY: https://github.com/elastic/kibana/issues/100012 + describe.skip('Enter Space', function () { this.tags('includeFirefox'); before(async () => { await esArchiver.load('spaces/enter_space'); diff --git a/x-pack/test/functional/apps/uptime/index.ts b/x-pack/test/functional/apps/uptime/index.ts index f96d2d0255d2a..0b02fd2bf322b 100644 --- a/x-pack/test/functional/apps/uptime/index.ts +++ b/x-pack/test/functional/apps/uptime/index.ts @@ -59,6 +59,7 @@ export default ({ loadTestFile, getService }: FtrProviderContext) => { loadTestFile(require.resolve('./locations')); loadTestFile(require.resolve('./settings')); loadTestFile(require.resolve('./certificates')); + loadTestFile(require.resolve('./synthetics_integration')); }); describe('with generated data but no data reset', () => { diff --git a/x-pack/test/functional/apps/uptime/synthetics_integration.ts b/x-pack/test/functional/apps/uptime/synthetics_integration.ts new file mode 100644 index 0000000000000..52ec81b8bf7db --- /dev/null +++ b/x-pack/test/functional/apps/uptime/synthetics_integration.ts @@ -0,0 +1,442 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../ftr_provider_context'; +import { FullAgentPolicy } from '../../../../plugins/fleet/common'; + +export default function ({ getPageObjects, getService }: FtrProviderContext) { + const monitorName = 'Sample Synthetics integration'; + + const uptimePage = getPageObjects(['syntheticsIntegration']); + const testSubjects = getService('testSubjects'); + const uptimeService = getService('uptime'); + + const generatePolicy = ({ + agentFullPolicy, + version, + monitorType, + name, + config, + }: { + agentFullPolicy: FullAgentPolicy; + version: string; + monitorType: string; + name: string; + config: Record; + }) => ({ + data_stream: { + namespace: 'default', + }, + id: agentFullPolicy.inputs[0].id, + meta: { + package: { + name: 'synthetics', + version, + }, + }, + name, + revision: 1, + streams: [ + { + data_stream: { + dataset: monitorType, + type: 'synthetics', + }, + id: `${agentFullPolicy.inputs[0]?.streams?.[0]?.id}`, + name, + type: monitorType, + processors: [ + { + add_observer_metadata: { + geo: { + name: 'Fleet managed', + }, + }, + }, + { + add_fields: { + fields: { + 'monitor.fleet_managed': true, + }, + target: '', + }, + }, + ], + ...config, + }, + ], + type: `synthetics/${monitorType}`, + use_output: 'default', + }); + + describe('When on the Synthetics Integration Policy Create Page', function () { + this.tags(['ciGroup6']); + const basicConfig = { + name: monitorName, + apmServiceName: 'Sample APM Service', + tags: 'sample tag', + }; + + const generateHTTPConfig = (url: string) => ({ + ...basicConfig, + url, + }); + + const generateTCPorICMPConfig = (host: string) => ({ + ...basicConfig, + host, + }); + + describe('displays custom UI', () => { + before(async () => { + const version = await uptimeService.syntheticsPackage.getSyntheticsPackageVersion(); + await uptimePage.syntheticsIntegration.navigateToPackagePage(version!); + }); + + it('should display policy view', async () => { + await uptimePage.syntheticsIntegration.ensureIsOnPackagePage(); + }); + + it('prevent saving when integration name, url/host, or schedule is missing', async () => { + const saveButton = await uptimePage.syntheticsIntegration.findSaveButton(); + await saveButton.click(); + + await testSubjects.missingOrFail('packagePolicyCreateSuccessToast'); + }); + }); + + describe('create new policy', () => { + let version: string; + before(async () => { + await uptimeService.syntheticsPackage.deletePolicyByName('system-1'); + }); + + beforeEach(async () => { + version = (await uptimeService.syntheticsPackage.getSyntheticsPackageVersion())!; + await uptimePage.syntheticsIntegration.navigateToPackagePage(version!); + await uptimeService.syntheticsPackage.deletePolicyByName(monitorName); + }); + + afterEach(async () => { + await uptimeService.syntheticsPackage.deletePolicyByName(monitorName); + }); + + it('allows saving when user enters a valid integration name and url/host', async () => { + // This test ensures that updates made to the Synthetics Policy are carried all the way through + // to the generated Agent Policy that is dispatch down to the Elastic Agent. + const config = generateHTTPConfig('http://elastic.co'); + await uptimePage.syntheticsIntegration.createBasicHTTPMonitorDetails(config); + await uptimePage.syntheticsIntegration.confirmAndSave(); + + await uptimePage.syntheticsIntegration.isPolicyCreatedSuccessfully(); + + const [agentPolicy] = await uptimeService.syntheticsPackage.getAgentPolicyList(); + const agentPolicyId = agentPolicy.id; + const agentFullPolicy = await uptimeService.syntheticsPackage.getFullAgentPolicy( + agentPolicyId + ); + + expect(agentFullPolicy.inputs).to.eql([ + generatePolicy({ + agentFullPolicy, + version, + name: monitorName, + monitorType: 'http', + config: { + max_redirects: 0, + 'response.include_body': 'on_error', + 'response.include_headers': true, + schedule: '@every 3m', + timeout: '16s', + urls: config.url, + 'service.name': config.apmServiceName, + tags: [config.tags], + 'check.request.method': 'GET', + }, + }), + ]); + }); + + it('allows enabling tls with defaults', async () => { + // This test ensures that updates made to the Synthetics Policy are carried all the way through + // to the generated Agent Policy that is dispatch down to the Elastic Agent. + const config = generateHTTPConfig('http://elastic.co'); + + await uptimePage.syntheticsIntegration.createBasicHTTPMonitorDetails(config); + await uptimePage.syntheticsIntegration.enableTLS(); + await uptimePage.syntheticsIntegration.confirmAndSave(); + + await uptimePage.syntheticsIntegration.isPolicyCreatedSuccessfully(); + + const [agentPolicy] = await uptimeService.syntheticsPackage.getAgentPolicyList(); + const agentPolicyId = agentPolicy.id; + const agentFullPolicy = await uptimeService.syntheticsPackage.getFullAgentPolicy( + agentPolicyId + ); + + expect(agentFullPolicy.inputs).to.eql([ + generatePolicy({ + agentFullPolicy, + version, + name: monitorName, + monitorType: 'http', + config: { + max_redirects: 0, + 'check.request.method': 'GET', + 'response.include_body': 'on_error', + 'response.include_headers': true, + schedule: '@every 3m', + 'ssl.supported_protocols': ['TLSv1.1', 'TLSv1.2', 'TLSv1.3'], + 'ssl.verification_mode': 'full', + timeout: '16s', + urls: config.url, + 'service.name': config.apmServiceName, + tags: [config.tags], + }, + }), + ]); + }); + + it('allows configuring tls', async () => { + // This test ensures that updates made to the Synthetics Policy are carried all the way through + // to the generated Agent Policy that is dispatch down to the Elastic Agent. + const config = generateHTTPConfig('http://elastic.co'); + + const tlsConfig = { + verificationMode: 'strict', + ca: 'ca', + cert: 'cert', + certKey: 'certKey', + certKeyPassphrase: 'certKeyPassphrase', + }; + await uptimePage.syntheticsIntegration.createBasicHTTPMonitorDetails(config); + await uptimePage.syntheticsIntegration.configureTLSOptions(tlsConfig); + await uptimePage.syntheticsIntegration.confirmAndSave(); + + await uptimePage.syntheticsIntegration.isPolicyCreatedSuccessfully(); + + const [agentPolicy] = await uptimeService.syntheticsPackage.getAgentPolicyList(); + const agentPolicyId = agentPolicy.id; + const agentFullPolicy = await uptimeService.syntheticsPackage.getFullAgentPolicy( + agentPolicyId + ); + + expect(agentFullPolicy.inputs).to.eql([ + generatePolicy({ + agentFullPolicy, + version, + name: monitorName, + monitorType: 'http', + config: { + max_redirects: 0, + 'check.request.method': 'GET', + 'response.include_body': 'on_error', + 'response.include_headers': true, + schedule: '@every 3m', + 'ssl.supported_protocols': ['TLSv1.1', 'TLSv1.2', 'TLSv1.3'], + 'ssl.verification_mode': tlsConfig.verificationMode, + 'ssl.certificate': tlsConfig.cert, + 'ssl.certificate_authorities': tlsConfig.ca, + 'ssl.key': tlsConfig.certKey, + 'ssl.key_passphrase': tlsConfig.certKeyPassphrase, + timeout: '16s', + urls: config.url, + 'service.name': config.apmServiceName, + tags: [config.tags], + }, + }), + ]); + }); + + it('allows configuring http advanced options', async () => { + // This test ensures that updates made to the Synthetics Policy are carried all the way through + // to the generated Agent Policy that is dispatch down to the Elastic Agent. + const config = generateHTTPConfig('http://elastic.co'); + + await uptimePage.syntheticsIntegration.createBasicHTTPMonitorDetails(config); + const advancedConfig = { + username: 'username', + password: 'password', + proxyUrl: 'proxyUrl', + requestMethod: 'POST', + responseStatusCheck: '204', + responseBodyCheckPositive: 'success', + responseBodyCheckNegative: 'failure', + requestHeaders: { + sampleRequestHeader1: 'sampleRequestKey1', + sampleRequestHeader2: 'sampleRequestKey2', + }, + responseHeaders: { + sampleResponseHeader1: 'sampleResponseKey1', + sampleResponseHeader2: 'sampleResponseKey2', + }, + requestBody: { + type: 'xml', + value: 'samplexml', + }, + indexResponseBody: false, + indexResponseHeaders: false, + }; + await uptimePage.syntheticsIntegration.configureHTTPAdvancedOptions(advancedConfig); + await uptimePage.syntheticsIntegration.confirmAndSave(); + + await uptimePage.syntheticsIntegration.isPolicyCreatedSuccessfully(); + + const [agentPolicy] = await uptimeService.syntheticsPackage.getAgentPolicyList(); + const agentPolicyId = agentPolicy.id; + const agentFullPolicy = await uptimeService.syntheticsPackage.getFullAgentPolicy( + agentPolicyId + ); + + expect(agentFullPolicy.inputs).to.eql([ + generatePolicy({ + agentFullPolicy, + version, + name: monitorName, + monitorType: 'http', + config: { + max_redirects: 0, + 'check.request.method': advancedConfig.requestMethod, + 'check.request.headers': { + 'Content-Type': 'application/xml', + ...advancedConfig.requestHeaders, + }, + 'check.response.headers': advancedConfig.responseHeaders, + 'check.response.status': [advancedConfig.responseStatusCheck], + 'check.request.body': `${advancedConfig.requestBody.value}`, // code editor adds closing tag + 'check.response.body.positive': [advancedConfig.responseBodyCheckPositive], + 'check.response.body.negative': [advancedConfig.responseBodyCheckNegative], + 'response.include_body': advancedConfig.indexResponseBody ? 'on_error' : 'never', + 'response.include_headers': advancedConfig.indexResponseHeaders, + schedule: '@every 3m', + timeout: '16s', + urls: config.url, + proxy_url: advancedConfig.proxyUrl, + username: advancedConfig.username, + password: advancedConfig.password, + 'service.name': config.apmServiceName, + tags: [config.tags], + }, + }), + ]); + }); + + it('allows saving tcp monitor when user enters a valid integration name and host+port', async () => { + // This test ensures that updates made to the Synthetics Policy are carried all the way through + // to the generated Agent Policy that is dispatch down to the Elastic Agent. + const config = generateTCPorICMPConfig('smtp.gmail.com:587'); + + await uptimePage.syntheticsIntegration.createBasicTCPMonitorDetails(config); + await uptimePage.syntheticsIntegration.confirmAndSave(); + + await uptimePage.syntheticsIntegration.isPolicyCreatedSuccessfully(); + + const [agentPolicy] = await uptimeService.syntheticsPackage.getAgentPolicyList(); + const agentPolicyId = agentPolicy.id; + const agentFullPolicy = await uptimeService.syntheticsPackage.getFullAgentPolicy( + agentPolicyId + ); + + expect(agentFullPolicy.inputs).to.eql([ + generatePolicy({ + agentFullPolicy, + version, + name: monitorName, + monitorType: 'tcp', + config: { + proxy_use_local_resolver: false, + schedule: '@every 3m', + timeout: '16s', + hosts: config.host, + tags: [config.tags], + 'service.name': config.apmServiceName, + }, + }), + ]); + }); + + it('allows configuring tcp advanced options', async () => { + // This test ensures that updates made to the Synthetics Policy are carried all the way through + // to the generated Agent Policy that is dispatch down to the Elastic Agent. + const config = generateTCPorICMPConfig('smtp.gmail.com:587'); + + await uptimePage.syntheticsIntegration.createBasicTCPMonitorDetails(config); + const advancedConfig = { + proxyUrl: 'proxyUrl', + requestSendCheck: 'body', + responseReceiveCheck: 'success', + proxyUseLocalResolver: true, + }; + await uptimePage.syntheticsIntegration.configureTCPAdvancedOptions(advancedConfig); + await uptimePage.syntheticsIntegration.confirmAndSave(); + + await uptimePage.syntheticsIntegration.isPolicyCreatedSuccessfully(); + + const [agentPolicy] = await uptimeService.syntheticsPackage.getAgentPolicyList(); + const agentPolicyId = agentPolicy.id; + const agentFullPolicy = await uptimeService.syntheticsPackage.getFullAgentPolicy( + agentPolicyId + ); + + expect(agentFullPolicy.inputs).to.eql([ + generatePolicy({ + agentFullPolicy, + version, + name: monitorName, + monitorType: 'tcp', + config: { + schedule: '@every 3m', + timeout: '16s', + hosts: config.host, + proxy_url: advancedConfig.proxyUrl, + proxy_use_local_resolver: advancedConfig.proxyUseLocalResolver, + 'check.receive': advancedConfig.responseReceiveCheck, + 'check.send': advancedConfig.requestSendCheck, + 'service.name': config.apmServiceName, + tags: [config.tags], + }, + }), + ]); + }); + + it('allows saving icmp monitor when user enters a valid integration name and host', async () => { + // This test ensures that updates made to the Synthetics Policy are carried all the way through + // to the generated Agent Policy that is dispatch down to the Elastic Agent. + const config = generateTCPorICMPConfig('1.1.1.1'); + + await uptimePage.syntheticsIntegration.createBasicICMPMonitorDetails(config); + await uptimePage.syntheticsIntegration.confirmAndSave(); + + await uptimePage.syntheticsIntegration.isPolicyCreatedSuccessfully(); + + const [agentPolicy] = await uptimeService.syntheticsPackage.getAgentPolicyList(); + const agentPolicyId = agentPolicy.id; + const agentFullPolicy = await uptimeService.syntheticsPackage.getFullAgentPolicy( + agentPolicyId + ); + + expect(agentFullPolicy.inputs).to.eql([ + generatePolicy({ + agentFullPolicy, + version, + name: monitorName, + monitorType: 'icmp', + config: { + schedule: '@every 3m', + timeout: '16s', + wait: '1s', + hosts: config.host, + 'service.name': config.apmServiceName, + tags: [config.tags], + }, + }), + ]); + }); + }); + }); +} diff --git a/x-pack/test/functional/config.js b/x-pack/test/functional/config.js index f171e247472f1..573350dad24d0 100644 --- a/x-pack/test/functional/config.js +++ b/x-pack/test/functional/config.js @@ -154,6 +154,9 @@ export default async function ({ readConfigFile }) { uptime: { pathname: '/app/uptime', }, + fleet: { + pathname: '/app/fleet', + }, ml: { pathname: '/app/ml', }, diff --git a/x-pack/test/functional/config_security_basic.ts b/x-pack/test/functional/config_security_basic.ts index d8d008508785a..4deb598fe8769 100644 --- a/x-pack/test/functional/config_security_basic.ts +++ b/x-pack/test/functional/config_security_basic.ts @@ -9,7 +9,7 @@ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; import { pageObjects } from './page_objects'; diff --git a/x-pack/test/functional/ftr_provider_context.d.ts b/x-pack/test/functional/ftr_provider_context.d.ts index ec28c00e72e47..24f5087ef7fe2 100644 --- a/x-pack/test/functional/ftr_provider_context.d.ts +++ b/x-pack/test/functional/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { services } from './services'; diff --git a/x-pack/test/functional/page_objects/index.ts b/x-pack/test/functional/page_objects/index.ts index 81c0328e76342..e83420a9cea1d 100644 --- a/x-pack/test/functional/page_objects/index.ts +++ b/x-pack/test/functional/page_objects/index.ts @@ -24,6 +24,7 @@ import { StatusPagePageProvider } from './status_page'; import { UpgradeAssistantPageProvider } from './upgrade_assistant_page'; import { RollupPageProvider } from './rollup_page'; import { UptimePageProvider } from './uptime_page'; +import { SyntheticsIntegrationPageProvider } from './synthetics_integration_page'; import { ApiKeysPageProvider } from './api_keys_page'; import { LicenseManagementPageProvider } from './license_management_page'; import { IndexManagementPageProvider } from './index_management_page'; @@ -64,6 +65,7 @@ export const pageObjects = { statusPage: StatusPagePageProvider, upgradeAssistant: UpgradeAssistantPageProvider, uptime: UptimePageProvider, + syntheticsIntegration: SyntheticsIntegrationPageProvider, rollup: RollupPageProvider, apiKeys: ApiKeysPageProvider, licenseManagement: LicenseManagementPageProvider, diff --git a/x-pack/test/functional/page_objects/space_selector_page.ts b/x-pack/test/functional/page_objects/space_selector_page.ts index 57ca0c97c63da..0a41e4b90287f 100644 --- a/x-pack/test/functional/page_objects/space_selector_page.ts +++ b/x-pack/test/functional/page_objects/space_selector_page.ts @@ -167,10 +167,6 @@ export function SpaceSelectorPageProvider({ getService, getPageObjects }: FtrPro await testSubjects.click(`${spaceName}-deleteSpace`); } - async setSpaceNameTobeDeleted(spaceName: string) { - await testSubjects.setValue('deleteSpaceInput', spaceName); - } - async cancelDeletingSpace() { await testSubjects.click('confirmModalCancelButton'); } diff --git a/x-pack/test/functional/page_objects/synthetics_integration_page.ts b/x-pack/test/functional/page_objects/synthetics_integration_page.ts new file mode 100644 index 0000000000000..69ae3f43d26f2 --- /dev/null +++ b/x-pack/test/functional/page_objects/synthetics_integration_page.ts @@ -0,0 +1,384 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { WebElementWrapper } from 'test/functional/services/lib/web_element_wrapper'; +import { FtrProviderContext } from '../ftr_provider_context'; + +export function SyntheticsIntegrationPageProvider({ + getService, + getPageObjects, +}: FtrProviderContext) { + const pageObjects = getPageObjects(['common', 'header']); + const testSubjects = getService('testSubjects'); + const comboBox = getService('comboBox'); + + return { + /** + * Navigates to the Synthetics Integration page + * + */ + async navigateToPackagePage(packageVersion: string) { + await pageObjects.common.navigateToUrl( + 'fleet', + `/integrations/synthetics-${packageVersion}/add-integration`, + { + shouldUseHashForSubUrl: true, + useActualUrl: true, + } + ); + await pageObjects.header.waitUntilLoadingHasFinished(); + }, + + async navigateToPackageEditPage(packageId: string, agentId: string) { + await pageObjects.common.navigateToUrl( + 'fleet', + `/policies/${agentId}/edit-integration/${packageId}`, + { + shouldUseHashForSubUrl: true, + useActualUrl: true, + } + ); + await pageObjects.header.waitUntilLoadingHasFinished(); + }, + + /** + * Finds and returns the Policy Details Page Save button + */ + async findSaveButton(isEditPage?: boolean) { + await this.ensureIsOnPackagePage(); + return await testSubjects.find( + isEditPage ? 'saveIntegration' : 'createPackagePolicySaveButton' + ); + }, + + /** + * Finds and returns the Policy Details Page Cancel Button + */ + async findCancelButton() { + await this.ensureIsOnPackagePage(); + return await testSubjects.find('policyDetailsCancelButton'); + }, + + /** + * Determines if the policy was created successfully by looking for the creation success toast + */ + async isPolicyCreatedSuccessfully() { + await testSubjects.existOrFail('packagePolicyCreateSuccessToast'); + }, + + /** + * Selects the monitor type + * @params {monitorType} the type of monitor, tcp, http, or icmp + */ + async selectMonitorType(monitorType: string) { + await testSubjects.selectValue('syntheticsMonitorTypeField', monitorType); + }, + + /** + * Fills a text input + * @params {testSubj} the testSubj of the input to fill + * @params {value} the value of the input + */ + async fillTextInputByTestSubj(testSubj: string, value: string) { + const field = await testSubjects.find(testSubj, 5000); + await field.click(); + await field.clearValue(); + await field.type(value); + }, + + /** + * Fills a text input + * @params {testSubj} the testSubj of the input to fill + * @params {value} the value of the input + */ + async fillTextInput(field: WebElementWrapper, value: string) { + await field.click(); + await field.clearValue(); + await field.type(value); + }, + + /** + * Fills a text input + * @params {testSubj} the testSubj of the comboBox + */ + async setComboBox(testSubj: string, value: string) { + await comboBox.setCustom(`${testSubj} > comboBoxInput`, value); + }, + + /** + * Finds and returns the HTTP advanced options accordion trigger + */ + async findHTTPAdvancedOptionsAccordion() { + await this.ensureIsOnPackagePage(); + const accordion = await testSubjects.find('syntheticsHTTPAdvancedFieldsAccordion', 5000); + return accordion; + }, + + /** + * Finds and returns the enable TLS checkbox + */ + async findEnableTLSCheckbox() { + await this.ensureIsOnPackagePage(); + const tlsCheckboxContainer = await testSubjects.find('syntheticsIsTLSEnabled'); + return await tlsCheckboxContainer.findByCssSelector('label'); + }, + + /** + * ensures that the package page is the currently display view + */ + async ensureIsOnPackagePage() { + await testSubjects.existOrFail('monitorSettingsSection'); + }, + + /** + * Clicks save button and confirms update on the Policy Details page + */ + async confirmAndSave(isEditPage?: boolean) { + await this.ensureIsOnPackagePage(); + const saveButton = await this.findSaveButton(isEditPage); + saveButton.click(); + }, + + /** + * Fills in the username and password field + * @params username {string} the value of the username + * @params password {string} the value of the password + */ + async configureUsernameAndPassword({ username, password }: Record) { + await this.fillTextInputByTestSubj('syntheticsUsername', username); + await this.fillTextInputByTestSubj('syntheticsPassword', password); + }, + + /** + * + * Configures request headers + * @params headers {string} an object containing desired headers + * + */ + async configureRequestHeaders(headers: Record) { + await this.configureHeaders('syntheticsRequestHeaders', headers); + }, + + /** + * + * Configures response headers + * @params headers {string} an object containing desired headers + * + */ + async configureResponseHeaders(headers: Record) { + await this.configureHeaders('syntheticsResponseHeaders', headers); + }, + + /** + * + * Configures headers + * @params testSubj {string} test subj + * @params headers {string} an object containing desired headers + * + */ + async configureHeaders(testSubj: string, headers: Record) { + const headersContainer = await testSubjects.find(testSubj); + const addHeaderButton = await headersContainer.findByCssSelector('button'); + const keys = Object.keys(headers); + + await Promise.all( + keys.map(async (key, index) => { + await addHeaderButton.click(); + const keyField = await headersContainer.findByCssSelector( + `[data-test-subj="keyValuePairsKey${index}"]` + ); + const valueField = await headersContainer.findByCssSelector( + `[data-test-subj="keyValuePairsValue${index}"]` + ); + await this.fillTextInput(keyField, key); + await this.fillTextInput(valueField, headers[key]); + }) + ); + }, + + /** + * + * Configures request body + * @params contentType {string} contentType of the request body + * @params value {string} value of the request body + * + */ + async configureRequestBody(testSubj: string, value: string) { + await testSubjects.click(`syntheticsRequestBodyTab__${testSubj}`); + const codeEditorContainer = await testSubjects.find('codeEditorContainer'); + const textArea = await codeEditorContainer.findByCssSelector('textarea'); + await textArea.clearValue(); + await textArea.type(value); + }, + + /** + * Creates basic common monitor details + * @params name {string} the name of the monitor + * @params url {string} the url of the monitor + * + */ + async createBasicMonitorDetails({ name, apmServiceName, tags }: Record) { + await this.fillTextInputByTestSubj('packagePolicyNameInput', name); + await this.fillTextInputByTestSubj('syntheticsAPMServiceName', apmServiceName); + await this.setComboBox('syntheticsTags', tags); + }, + + /** + * Fills in the fields to create a basic HTTP monitor + * @params name {string} the name of the monitor + * @params url {string} the url of the monitor + * + */ + async createBasicHTTPMonitorDetails({ + name, + url, + apmServiceName, + tags, + }: Record) { + await this.createBasicMonitorDetails({ name, apmServiceName, tags }); + await this.fillTextInputByTestSubj('syntheticsUrlField', url); + }, + + /** + * Fills in the fields to create a basic TCP monitor + * @params name {string} the name of the monitor + * @params host {string} the host (and port) of the monitor + * + */ + async createBasicTCPMonitorDetails({ + name, + host, + apmServiceName, + tags, + }: Record) { + await this.selectMonitorType('tcp'); + await this.createBasicMonitorDetails({ name, apmServiceName, tags }); + await this.fillTextInputByTestSubj('syntheticsTCPHostField', host); + }, + + /** + * Creates a basic ICMP monitor + * @params name {string} the name of the monitor + * @params host {string} the host of the monitor + */ + async createBasicICMPMonitorDetails({ + name, + host, + apmServiceName, + tags, + }: Record) { + await this.selectMonitorType('icmp'); + await this.fillTextInputByTestSubj('packagePolicyNameInput', name); + await this.createBasicMonitorDetails({ name, apmServiceName, tags }); + await this.fillTextInputByTestSubj('syntheticsICMPHostField', host); + }, + + /** + * Enables TLS + */ + async enableTLS() { + const tlsCheckbox = await this.findEnableTLSCheckbox(); + await tlsCheckbox.click(); + }, + + /** + * Configures TLS settings + * @params verificationMode {string} the name of the monitor + */ + async configureTLSOptions({ + verificationMode, + ca, + cert, + certKey, + certKeyPassphrase, + }: Record) { + await this.enableTLS(); + await testSubjects.selectValue('syntheticsTLSVerificationMode', verificationMode); + await this.fillTextInputByTestSubj('syntheticsTLSCA', ca); + await this.fillTextInputByTestSubj('syntheticsTLSCert', cert); + await this.fillTextInputByTestSubj('syntheticsTLSCertKey', certKey); + await this.fillTextInputByTestSubj('syntheticsTLSCertKeyPassphrase', certKeyPassphrase); + }, + + /** + * Configure http advanced settings + */ + async configureHTTPAdvancedOptions({ + username, + password, + proxyUrl, + requestMethod, + requestHeaders, + responseStatusCheck, + responseBodyCheckPositive, + responseBodyCheckNegative, + requestBody, + responseHeaders, + indexResponseBody, + indexResponseHeaders, + }: { + username: string; + password: string; + proxyUrl: string; + requestMethod: string; + responseStatusCheck: string; + responseBodyCheckPositive: string; + responseBodyCheckNegative: string; + requestBody: { value: string; type: string }; + requestHeaders: Record; + responseHeaders: Record; + indexResponseBody: boolean; + indexResponseHeaders: boolean; + }) { + await testSubjects.click('syntheticsHTTPAdvancedFieldsAccordion'); + await this.configureResponseHeaders(responseHeaders); + await this.configureRequestHeaders(requestHeaders); + await this.configureRequestBody(requestBody.type, requestBody.value); + await this.configureUsernameAndPassword({ username, password }); + await this.setComboBox('syntheticsResponseStatusCheck', responseStatusCheck); + await this.setComboBox('syntheticsResponseBodyCheckPositive', responseBodyCheckPositive); + await this.setComboBox('syntheticsResponseBodyCheckNegative', responseBodyCheckNegative); + await this.fillTextInputByTestSubj('syntheticsProxyUrl', proxyUrl); + await testSubjects.selectValue('syntheticsRequestMethod', requestMethod); + if (!indexResponseBody) { + const field = await testSubjects.find('syntheticsIndexResponseBody'); + const label = await field.findByCssSelector('label'); + await label.click(); + } + if (!indexResponseHeaders) { + const field = await testSubjects.find('syntheticsIndexResponseHeaders'); + const label = await field.findByCssSelector('label'); + await label.click(); + } + }, + + /** + * Configure tcp advanced settings + */ + async configureTCPAdvancedOptions({ + proxyUrl, + requestSendCheck, + responseReceiveCheck, + proxyUseLocalResolver, + }: { + proxyUrl: string; + requestSendCheck: string; + responseReceiveCheck: string; + proxyUseLocalResolver: boolean; + }) { + await testSubjects.click('syntheticsTCPAdvancedFieldsAccordion'); + await this.fillTextInputByTestSubj('syntheticsProxyUrl', proxyUrl); + await this.fillTextInputByTestSubj('syntheticsTCPRequestSendCheck', requestSendCheck); + await this.fillTextInputByTestSubj('syntheticsTCPResponseReceiveCheck', responseReceiveCheck); + if (proxyUseLocalResolver) { + const field = await testSubjects.find('syntheticsUseLocalResolver'); + const label = await field.findByCssSelector('label'); + await label.click(); + } + }, + }; +} diff --git a/x-pack/test/functional/services/ml/api.ts b/x-pack/test/functional/services/ml/api.ts index d341a27455a3c..4623b4f4e41ae 100644 --- a/x-pack/test/functional/services/ml/api.ts +++ b/x-pack/test/functional/services/ml/api.ts @@ -7,7 +7,7 @@ import { estypes } from '@elastic/elasticsearch'; import expect from '@kbn/expect'; -import { ProvidedType } from '@kbn/test/types/ftr'; +import { ProvidedType } from '@kbn/test'; import { Calendar } from '../../../../plugins/ml/server/models/calendar/index'; import { Annotation } from '../../../../plugins/ml/common/types/annotations'; import { DataFrameAnalyticsConfig } from '../../../../plugins/ml/public/application/data_frame_analytics/common'; diff --git a/x-pack/test/functional/services/ml/common_api.ts b/x-pack/test/functional/services/ml/common_api.ts index 22be24548892f..02cfecfc5208f 100644 --- a/x-pack/test/functional/services/ml/common_api.ts +++ b/x-pack/test/functional/services/ml/common_api.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { ProvidedType } from '@kbn/test/types/ftr'; +import { ProvidedType } from '@kbn/test'; import { FtrProviderContext } from '../../ftr_provider_context'; diff --git a/x-pack/test/functional/services/ml/common_ui.ts b/x-pack/test/functional/services/ml/common_ui.ts index f42f54116c926..b7288d5927b4c 100644 --- a/x-pack/test/functional/services/ml/common_ui.ts +++ b/x-pack/test/functional/services/ml/common_ui.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import { ProvidedType } from '@kbn/test/types/ftr'; +import { ProvidedType } from '@kbn/test'; import { FtrProviderContext } from '../../ftr_provider_context'; diff --git a/x-pack/test/functional/services/ml/custom_urls.ts b/x-pack/test/functional/services/ml/custom_urls.ts index 7c424c021fd6c..0b24c565b2fa8 100644 --- a/x-pack/test/functional/services/ml/custom_urls.ts +++ b/x-pack/test/functional/services/ml/custom_urls.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import { ProvidedType } from '@kbn/test/types/ftr'; +import { ProvidedType } from '@kbn/test'; import { FtrProviderContext } from '../../ftr_provider_context'; diff --git a/x-pack/test/functional/services/ml/dashboard_job_selection_table.ts b/x-pack/test/functional/services/ml/dashboard_job_selection_table.ts index f372928d92a50..4fc90585f1408 100644 --- a/x-pack/test/functional/services/ml/dashboard_job_selection_table.ts +++ b/x-pack/test/functional/services/ml/dashboard_job_selection_table.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import { ProvidedType } from '@kbn/test/types/ftr'; +import { ProvidedType } from '@kbn/test'; import { FtrProviderContext } from '../../ftr_provider_context'; export type MlDashboardJobSelectionTable = ProvidedType< diff --git a/x-pack/test/functional/services/ml/data_visualizer_table.ts b/x-pack/test/functional/services/ml/data_visualizer_table.ts index 3bd3b7e2e783a..cdd91da8ff9e6 100644 --- a/x-pack/test/functional/services/ml/data_visualizer_table.ts +++ b/x-pack/test/functional/services/ml/data_visualizer_table.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import { ProvidedType } from '@kbn/test/types/ftr'; +import { ProvidedType } from '@kbn/test'; import { FtrProviderContext } from '../../ftr_provider_context'; import { ML_JOB_FIELD_TYPES } from '../../../../plugins/ml/common/constants/field_types'; import { MlCommonUI } from './common_ui'; diff --git a/x-pack/test/functional/services/ml/security_common.ts b/x-pack/test/functional/services/ml/security_common.ts index 28d912a756acd..847730ca73548 100644 --- a/x-pack/test/functional/services/ml/security_common.ts +++ b/x-pack/test/functional/services/ml/security_common.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { ProvidedType } from '@kbn/test/types/ftr'; +import { ProvidedType } from '@kbn/test'; import { FtrProviderContext } from '../../ftr_provider_context'; diff --git a/x-pack/test/functional/services/ml/test_resources.ts b/x-pack/test/functional/services/ml/test_resources.ts index 547ff782bcbe5..f967099e10fa3 100644 --- a/x-pack/test/functional/services/ml/test_resources.ts +++ b/x-pack/test/functional/services/ml/test_resources.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { ProvidedType } from '@kbn/test/types/ftr'; +import { ProvidedType } from '@kbn/test'; import { savedSearches, dashboards } from './test_resources_data'; import { COMMON_REQUEST_HEADERS } from './common_api'; import { FtrProviderContext } from '../../ftr_provider_context'; diff --git a/x-pack/test/functional/services/transform/management.ts b/x-pack/test/functional/services/transform/management.ts index 807c3d49e344c..0aecc695049d1 100644 --- a/x-pack/test/functional/services/transform/management.ts +++ b/x-pack/test/functional/services/transform/management.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { ProvidedType } from '@kbn/test/types/ftr'; +import { ProvidedType } from '@kbn/test'; import { FtrProviderContext } from '../../ftr_provider_context'; export type TransformManagement = ProvidedType; diff --git a/x-pack/test/functional/services/transform/security_common.ts b/x-pack/test/functional/services/transform/security_common.ts index 12b24d45f5448..bae31dffa1412 100644 --- a/x-pack/test/functional/services/transform/security_common.ts +++ b/x-pack/test/functional/services/transform/security_common.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { ProvidedType } from '@kbn/test/types/ftr'; +import { ProvidedType } from '@kbn/test'; import { FtrProviderContext } from '../../ftr_provider_context'; diff --git a/x-pack/test/functional/services/uptime/synthetics_package.ts b/x-pack/test/functional/services/uptime/synthetics_package.ts new file mode 100644 index 0000000000000..78d0fcd61fde4 --- /dev/null +++ b/x-pack/test/functional/services/uptime/synthetics_package.ts @@ -0,0 +1,176 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FtrProviderContext } from '../../ftr_provider_context'; +import { + PACKAGE_POLICY_SAVED_OBJECT_TYPE, + DeletePackagePoliciesRequest, + GetPackagePoliciesResponse, + GetFullAgentPolicyResponse, + GetPackagesResponse, + GetAgentPoliciesResponse, +} from '../../../../plugins/fleet/common'; + +const INGEST_API_ROOT = '/api/fleet'; +const INGEST_API_AGENT_POLICIES = `${INGEST_API_ROOT}/agent_policies`; +const INGEST_API_PACKAGE_POLICIES = `${INGEST_API_ROOT}/package_policies`; +const INGEST_API_PACKAGE_POLICIES_DELETE = `${INGEST_API_PACKAGE_POLICIES}/delete`; +const INGEST_API_EPM_PACKAGES = `${INGEST_API_ROOT}/epm/packages`; + +export function SyntheticsPackageProvider({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const log = getService('log'); + const retry = getService('retry'); + + const logSupertestApiErrorAndThrow = (message: string, error: any): never => { + const responseBody = error?.response?.body; + const responseText = error?.response?.text; + log.error(`Error occurred at ${Date.now()} | ${new Date().toISOString()}`); + log.error(JSON.stringify(responseBody || responseText, null, 2)); + log.error(error); + throw new Error(message); + }; + const retrieveSyntheticsPackageInfo = (() => { + // Retrieve information about the Synthetics package + // EPM does not currently have an API to get the "lastest" information for a page given its name, + // so we'll retrieve a list of packages and then find the package info in the list. + let apiRequest: Promise; + + return () => { + if (!apiRequest) { + log.info(`Setting up call to retrieve Synthetics package`); + + // Currently (as of 2020-june) the package registry used in CI is the public one and + // at times it encounters network connection issues. We use `retry.try` below to see if + // subsequent requests get through. + apiRequest = retry.try(() => { + return supertest + .get(INGEST_API_EPM_PACKAGES) + .set('kbn-xsrf', 'xxx') + .expect(200) + .catch((error) => { + return logSupertestApiErrorAndThrow(`Unable to retrieve packages via Ingest!`, error); + }) + .then((response: { body: GetPackagesResponse }) => { + const { body } = response; + const syntheticsPackageInfo = body.response.find( + (epmPackage) => epmPackage.name === 'synthetics' + ); + if (!syntheticsPackageInfo) { + throw new Error( + `Synthetics package was not in response from ${INGEST_API_EPM_PACKAGES}` + ); + } + return Promise.resolve(syntheticsPackageInfo); + }); + }); + } else { + log.info('Using cached retrieval of synthetics package'); + } + return apiRequest; + }; + })(); + + return { + /** + * Returns the synthetics package version for the currently installed package. This version can then + * be used to build URLs for Fleet pages or APIs + */ + async getSyntheticsPackageVersion() { + const syntheticsPackage = await retrieveSyntheticsPackageInfo()!; + + return syntheticsPackage?.version; + }, + + /** + * Retrieves the full Agent policy by id, which mirrors what the Elastic Agent would get + * once they checkin. + */ + async getFullAgentPolicy(agentPolicyId: string): Promise { + let fullAgentPolicy: GetFullAgentPolicyResponse['item']; + try { + const apiResponse: { body: GetFullAgentPolicyResponse } = await supertest + .get(`${INGEST_API_AGENT_POLICIES}/${agentPolicyId}/full`) + .expect(200); + + fullAgentPolicy = apiResponse.body.item; + } catch (error) { + return logSupertestApiErrorAndThrow('Unable to get full Agent policy', error); + } + + return fullAgentPolicy!; + }, + + /** + * Retrieves all the agent policies. + */ + async getAgentPolicyList(): Promise { + let agentPolicyList: GetAgentPoliciesResponse['items']; + try { + const apiResponse: { body: GetAgentPoliciesResponse } = await supertest + .get(INGEST_API_AGENT_POLICIES) + .expect(200); + + agentPolicyList = apiResponse.body.items; + } catch (error) { + return logSupertestApiErrorAndThrow('Unable to get full Agent policy list', error); + } + + return agentPolicyList!; + }, + + /** + * Deletes a policy (Package Policy) by using the policy name + * @param name + */ + async deletePolicyByName(name: string) { + const id = await this.getPackagePolicyIdByName(name); + + if (id) { + try { + const deletePackagePolicyData: DeletePackagePoliciesRequest['body'] = { + packagePolicyIds: [id], + }; + await supertest + .post(INGEST_API_PACKAGE_POLICIES_DELETE) + .set('kbn-xsrf', 'xxx') + .send(deletePackagePolicyData) + .expect(200); + } catch (error) { + logSupertestApiErrorAndThrow( + `Unable to delete Package Policy via Ingest! ${name}`, + error + ); + } + } + }, + + /** + * Gets the policy id (Package Policy) by using the policy name + * @param name + */ + async getPackagePolicyIdByName(name: string) { + const { + body: packagePoliciesResponse, + }: { body: GetPackagePoliciesResponse } = await supertest + .get(INGEST_API_PACKAGE_POLICIES) + .set('kbn-xsrf', 'xxx') + .query({ kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.name: ${name}` }) + .send() + .expect(200); + const packagePolicyList: GetPackagePoliciesResponse['items'] = packagePoliciesResponse.items; + + if (packagePolicyList.length > 1) { + throw new Error(`Found ${packagePolicyList.length} Policies - was expecting only one!`); + } + + if (packagePolicyList.length) { + return packagePolicyList[0].id; + } + }, + }; +} diff --git a/x-pack/test/functional/services/uptime/uptime.ts b/x-pack/test/functional/services/uptime/uptime.ts index b345be012968d..1f808d4e5939a 100644 --- a/x-pack/test/functional/services/uptime/uptime.ts +++ b/x-pack/test/functional/services/uptime/uptime.ts @@ -15,6 +15,7 @@ import { UptimeAlertsProvider } from './alerts'; import { UptimeMLAnomalyProvider } from './ml_anomaly'; import { UptimeCertProvider } from './certificates'; import { UptimeOverviewProvider } from './overview'; +import { SyntheticsPackageProvider } from './synthetics_package'; export function UptimeProvider(context: FtrProviderContext) { const common = UptimeCommonProvider(context); @@ -25,6 +26,7 @@ export function UptimeProvider(context: FtrProviderContext) { const ml = UptimeMLAnomalyProvider(context); const cert = UptimeCertProvider(context); const overview = UptimeOverviewProvider(context); + const syntheticsPackage = SyntheticsPackageProvider(context); return { common, @@ -35,5 +37,6 @@ export function UptimeProvider(context: FtrProviderContext) { ml, cert, overview, + syntheticsPackage, }; } diff --git a/x-pack/test/functional_basic/config.ts b/x-pack/test/functional_basic/config.ts index ce72362076da1..e1dac88436e4c 100644 --- a/x-pack/test/functional_basic/config.ts +++ b/x-pack/test/functional_basic/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const xpackFunctionalConfig = await readConfigFile(require.resolve('../functional/config.js')); diff --git a/x-pack/test/functional_basic/ftr_provider_context.d.ts b/x-pack/test/functional_basic/ftr_provider_context.d.ts index 0225c54768af5..66d4e37b795ca 100644 --- a/x-pack/test/functional_basic/ftr_provider_context.d.ts +++ b/x-pack/test/functional_basic/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from '../functional/page_objects'; import { services } from '../functional/services'; diff --git a/x-pack/test/functional_cors/config.ts b/x-pack/test/functional_cors/config.ts index 81870a948dc15..738285b4ff40f 100644 --- a/x-pack/test/functional_cors/config.ts +++ b/x-pack/test/functional_cors/config.ts @@ -7,7 +7,7 @@ import Url from 'url'; import Path from 'path'; -import type { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import type { FtrConfigProviderContext } from '@kbn/test'; import { kbnTestConfig } from '@kbn/test'; import { pageObjects } from '../functional/page_objects'; diff --git a/x-pack/test/functional_cors/ftr_provider_context.d.ts b/x-pack/test/functional_cors/ftr_provider_context.d.ts index b1301d9ee8c49..d6c0afa5ceffd 100644 --- a/x-pack/test/functional_cors/ftr_provider_context.d.ts +++ b/x-pack/test/functional_cors/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from '../functional/page_objects'; import { services } from './services'; diff --git a/x-pack/test/functional_embedded/config.firefox.ts b/x-pack/test/functional_embedded/config.firefox.ts index a8a16f5c59b9e..49359d37673de 100644 --- a/x-pack/test/functional_embedded/config.firefox.ts +++ b/x-pack/test/functional_embedded/config.firefox.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const chromeConfig = await readConfigFile(require.resolve('./config')); diff --git a/x-pack/test/functional_embedded/config.ts b/x-pack/test/functional_embedded/config.ts index 33656eb857f58..868d53ee17ee9 100644 --- a/x-pack/test/functional_embedded/config.ts +++ b/x-pack/test/functional_embedded/config.ts @@ -8,7 +8,7 @@ import Fs from 'fs'; import { resolve } from 'path'; import { CA_CERT_PATH, KBN_CERT_PATH, KBN_KEY_PATH } from '@kbn/dev-utils'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { pageObjects } from '../functional/page_objects'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/functional_embedded/ftr_provider_context.d.ts b/x-pack/test/functional_embedded/ftr_provider_context.d.ts index b1301d9ee8c49..d6c0afa5ceffd 100644 --- a/x-pack/test/functional_embedded/ftr_provider_context.d.ts +++ b/x-pack/test/functional_embedded/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from '../functional/page_objects'; import { services } from './services'; diff --git a/x-pack/test/functional_enterprise_search/base_config.ts b/x-pack/test/functional_enterprise_search/base_config.ts index 5687bd48c9bad..2c21ccf5c5c39 100644 --- a/x-pack/test/functional_enterprise_search/base_config.ts +++ b/x-pack/test/functional_enterprise_search/base_config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { services } from './services'; diff --git a/x-pack/test/functional_enterprise_search/ftr_provider_context.d.ts b/x-pack/test/functional_enterprise_search/ftr_provider_context.d.ts index ec28c00e72e47..24f5087ef7fe2 100644 --- a/x-pack/test/functional_enterprise_search/ftr_provider_context.d.ts +++ b/x-pack/test/functional_enterprise_search/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { services } from './services'; diff --git a/x-pack/test/functional_enterprise_search/with_host_configured.config.ts b/x-pack/test/functional_enterprise_search/with_host_configured.config.ts index 66e638b69f5b8..1da62ffe56a5b 100644 --- a/x-pack/test/functional_enterprise_search/with_host_configured.config.ts +++ b/x-pack/test/functional_enterprise_search/with_host_configured.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const baseConfig = await readConfigFile(require.resolve('./base_config')); diff --git a/x-pack/test/functional_enterprise_search/without_host_configured.config.ts b/x-pack/test/functional_enterprise_search/without_host_configured.config.ts index 6d9fe32312d20..f5af2bddd8531 100644 --- a/x-pack/test/functional_enterprise_search/without_host_configured.config.ts +++ b/x-pack/test/functional_enterprise_search/without_host_configured.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const baseConfig = await readConfigFile(require.resolve('./base_config')); diff --git a/x-pack/test/functional_vis_wizard/config.ts b/x-pack/test/functional_vis_wizard/config.ts index 643718d78df08..523b59b6ccd1c 100644 --- a/x-pack/test/functional_vis_wizard/config.ts +++ b/x-pack/test/functional_vis_wizard/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const xPackFunctionalConfig = await readConfigFile(require.resolve('../functional/config')); diff --git a/x-pack/test/functional_vis_wizard/ftr_provider_context.d.ts b/x-pack/test/functional_vis_wizard/ftr_provider_context.d.ts index 89681747cbb55..ab1e999222808 100644 --- a/x-pack/test/functional_vis_wizard/ftr_provider_context.d.ts +++ b/x-pack/test/functional_vis_wizard/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from '../functional/page_objects'; import { services } from '../functional/services'; diff --git a/x-pack/test/functional_with_es_ssl/config.ts b/x-pack/test/functional_with_es_ssl/config.ts index 91a349e1bf44a..3ed382053f561 100644 --- a/x-pack/test/functional_with_es_ssl/config.ts +++ b/x-pack/test/functional_with_es_ssl/config.ts @@ -8,7 +8,7 @@ import Fs from 'fs'; import { resolve, join } from 'path'; import { CA_CERT_PATH } from '@kbn/dev-utils'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; // .server-log is specifically not enabled diff --git a/x-pack/test/functional_with_es_ssl/ftr_provider_context.d.ts b/x-pack/test/functional_with_es_ssl/ftr_provider_context.d.ts index 576d296e72e88..821731a07f457 100644 --- a/x-pack/test/functional_with_es_ssl/ftr_provider_context.d.ts +++ b/x-pack/test/functional_with_es_ssl/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from '../functional/services'; import { pageObjects } from './page_objects'; diff --git a/x-pack/test/licensing_plugin/config.public.ts b/x-pack/test/licensing_plugin/config.public.ts index 0de536d7125ca..a9df9f6ad1e96 100644 --- a/x-pack/test/licensing_plugin/config.public.ts +++ b/x-pack/test/licensing_plugin/config.public.ts @@ -8,7 +8,7 @@ import path from 'path'; // @ts-expect-error https://github.com/elastic/kibana/issues/95679 import { KIBANA_ROOT } from '@kbn/test'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const commonConfig = await readConfigFile(require.resolve('./config')); diff --git a/x-pack/test/licensing_plugin/config.ts b/x-pack/test/licensing_plugin/config.ts index ccd9494052817..155d761020b29 100644 --- a/x-pack/test/licensing_plugin/config.ts +++ b/x-pack/test/licensing_plugin/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services, pageObjects } from './services'; const license = 'basic'; diff --git a/x-pack/test/licensing_plugin/services.ts b/x-pack/test/licensing_plugin/services.ts index eb5b22731718c..fe98c9f23d174 100644 --- a/x-pack/test/licensing_plugin/services.ts +++ b/x-pack/test/licensing_plugin/services.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services as functionalTestServices } from '../functional/services'; import { services as kibanaApiIntegrationServices } from '../api_integration/services'; diff --git a/x-pack/test/lists_api_integration/common/config.ts b/x-pack/test/lists_api_integration/common/config.ts index 693155d376b53..24b47472d7945 100644 --- a/x-pack/test/lists_api_integration/common/config.ts +++ b/x-pack/test/lists_api_integration/common/config.ts @@ -7,7 +7,7 @@ import path from 'path'; import { CA_CERT_PATH } from '@kbn/dev-utils'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; interface CreateTestConfigOptions { diff --git a/x-pack/test/lists_api_integration/common/ftr_provider_context.d.ts b/x-pack/test/lists_api_integration/common/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/lists_api_integration/common/ftr_provider_context.d.ts +++ b/x-pack/test/lists_api_integration/common/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/lists_api_integration/utils.ts b/x-pack/test/lists_api_integration/utils.ts index 0512cede0a84f..29846a79d6b02 100644 --- a/x-pack/test/lists_api_integration/utils.ts +++ b/x-pack/test/lists_api_integration/utils.ts @@ -9,12 +9,12 @@ import { SuperTest } from 'supertest'; import supertestAsPromised from 'supertest-as-promised'; import type { KibanaClient } from '@elastic/elasticsearch/api/kibana'; +import { Type } from '@kbn/securitysolution-io-ts-list-types'; import { getImportListItemAsBuffer } from '../../plugins/lists/common/schemas/request/import_list_item_schema.mock'; import { ListItemSchema, ExceptionListSchema, ExceptionListItemSchema, - Type, } from '../../plugins/lists/common/schemas'; import { ListSchema } from '../../plugins/lists/common'; import { LIST_INDEX, LIST_ITEM_URL } from '../../plugins/lists/common/constants'; diff --git a/x-pack/test/load/config.ts b/x-pack/test/load/config.ts index f8de5c28b8a10..54789b56d9912 100644 --- a/x-pack/test/load/config.ts +++ b/x-pack/test/load/config.ts @@ -7,7 +7,7 @@ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { GatlingTestRunner } from './runner'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/observability_api_integration/common/config.ts b/x-pack/test/observability_api_integration/common/config.ts index 748b6ef7215e6..83249182084f3 100644 --- a/x-pack/test/observability_api_integration/common/config.ts +++ b/x-pack/test/observability_api_integration/common/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; interface Settings { license: 'basic' | 'trial'; diff --git a/x-pack/test/plugin_api_integration/config.ts b/x-pack/test/plugin_api_integration/config.ts index 87f8b77028bda..09bec3330c390 100644 --- a/x-pack/test/plugin_api_integration/config.ts +++ b/x-pack/test/plugin_api_integration/config.ts @@ -7,7 +7,7 @@ import path from 'path'; import fs from 'fs'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/plugin_api_integration/ftr_provider_context.d.ts b/x-pack/test/plugin_api_integration/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/plugin_api_integration/ftr_provider_context.d.ts +++ b/x-pack/test/plugin_api_integration/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/plugin_api_perf/ftr_provider_context.d.ts b/x-pack/test/plugin_api_perf/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/plugin_api_perf/ftr_provider_context.d.ts +++ b/x-pack/test/plugin_api_perf/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/plugin_functional/config.ts b/x-pack/test/plugin_functional/config.ts index 104d11eb87f7c..8b0ad12891dc3 100644 --- a/x-pack/test/plugin_functional/config.ts +++ b/x-pack/test/plugin_functional/config.ts @@ -9,7 +9,7 @@ import { resolve } from 'path'; import fs from 'fs'; // @ts-expect-error https://github.com/elastic/kibana/issues/95679 import { KIBANA_ROOT } from '@kbn/test'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; import { pageObjects } from './page_objects'; diff --git a/x-pack/test/plugin_functional/ftr_provider_context.d.ts b/x-pack/test/plugin_functional/ftr_provider_context.d.ts index 2dce44a533405..13bd4b46607c4 100644 --- a/x-pack/test/plugin_functional/ftr_provider_context.d.ts +++ b/x-pack/test/plugin_functional/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; import { pageObjects } from './page_objects'; diff --git a/x-pack/test/reporting_api_integration/ftr_provider_context.d.ts b/x-pack/test/reporting_api_integration/ftr_provider_context.d.ts index 671866cad6ff5..647664d640466 100644 --- a/x-pack/test/reporting_api_integration/ftr_provider_context.d.ts +++ b/x-pack/test/reporting_api_integration/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; export type FtrProviderContext = GenericFtrProviderContext; diff --git a/x-pack/test/reporting_api_integration/reporting_and_security.config.ts b/x-pack/test/reporting_api_integration/reporting_and_security.config.ts index 623799c84d860..0d1839c7a138f 100644 --- a/x-pack/test/reporting_api_integration/reporting_and_security.config.ts +++ b/x-pack/test/reporting_api_integration/reporting_and_security.config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { resolve } from 'path'; import { ReportingAPIProvider } from './services'; diff --git a/x-pack/test/reporting_api_integration/reporting_and_security/download_csv_dashboard.ts b/x-pack/test/reporting_api_integration/reporting_and_security/download_csv_dashboard.ts index 7f642f171b9fc..626cd217bde5f 100644 --- a/x-pack/test/reporting_api_integration/reporting_and_security/download_csv_dashboard.ts +++ b/x-pack/test/reporting_api_integration/reporting_and_security/download_csv_dashboard.ts @@ -31,7 +31,8 @@ export default function ({ getService }: FtrProviderContext) { }, }; - describe('CSV Generation from SearchSource', () => { + // FAILING ES PROMOTION: https://github.com/elastic/kibana/issues/99915 + describe.skip('CSV Generation from SearchSource', () => { before(async () => { await kibanaServer.uiSettings.update({ 'csv:quoteValues': false, diff --git a/x-pack/test/reporting_api_integration/reporting_without_security.config.ts b/x-pack/test/reporting_api_integration/reporting_without_security.config.ts index b962ab30876a5..dfd79916b5ce0 100644 --- a/x-pack/test/reporting_api_integration/reporting_without_security.config.ts +++ b/x-pack/test/reporting_api_integration/reporting_without_security.config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const apiConfig = await readConfigFile(require.resolve('./reporting_and_security.config')); diff --git a/x-pack/test/reporting_functional/ftr_provider_context.d.ts b/x-pack/test/reporting_functional/ftr_provider_context.d.ts index 58ebd71086130..e66e69e5ab2f7 100644 --- a/x-pack/test/reporting_functional/ftr_provider_context.d.ts +++ b/x-pack/test/reporting_functional/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from '../functional/page_objects'; import { services } from './services'; diff --git a/x-pack/test/reporting_functional/reporting_and_deprecated_security.config.ts b/x-pack/test/reporting_functional/reporting_and_deprecated_security.config.ts index 214667ff71c0d..a65755e97b0c9 100644 --- a/x-pack/test/reporting_functional/reporting_and_deprecated_security.config.ts +++ b/x-pack/test/reporting_functional/reporting_and_deprecated_security.config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { resolve } from 'path'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/reporting_functional/reporting_and_security.config.ts b/x-pack/test/reporting_functional/reporting_and_security.config.ts index 1f9ec5754e0bd..536695b4c6dc9 100644 --- a/x-pack/test/reporting_functional/reporting_and_security.config.ts +++ b/x-pack/test/reporting_functional/reporting_and_security.config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { resolve } from 'path'; import { ReportingAPIProvider } from '../reporting_api_integration/services'; import { ReportingFunctionalProvider } from './services'; diff --git a/x-pack/test/reporting_functional/reporting_without_security.config.ts b/x-pack/test/reporting_functional/reporting_without_security.config.ts index b88c611543953..0269f57bf08cb 100644 --- a/x-pack/test/reporting_functional/reporting_without_security.config.ts +++ b/x-pack/test/reporting_functional/reporting_without_security.config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { resolve } from 'path'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/saved_object_api_integration/common/config.ts b/x-pack/test/saved_object_api_integration/common/config.ts index ee219e9d246a7..f83afb4db2412 100644 --- a/x-pack/test/saved_object_api_integration/common/config.ts +++ b/x-pack/test/saved_object_api_integration/common/config.ts @@ -8,7 +8,7 @@ import path from 'path'; import { REPO_ROOT } from '@kbn/utils'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/saved_object_api_integration/common/ftr_provider_context.d.ts b/x-pack/test/saved_object_api_integration/common/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/saved_object_api_integration/common/ftr_provider_context.d.ts +++ b/x-pack/test/saved_object_api_integration/common/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/config.ts b/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/config.ts index e7b015ff92296..08ba10b64e579 100644 --- a/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/config.ts +++ b/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/config.ts @@ -6,7 +6,7 @@ */ import path from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; // eslint-disable-next-line import/no-default-export diff --git a/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/services.ts b/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/services.ts index 1d26b3dd35c96..194d6ec533066 100644 --- a/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/services.ts +++ b/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/services.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services as apiIntegrationServices } from '../../../api_integration/services'; export const services = { diff --git a/x-pack/test/saved_object_tagging/api_integration/tagging_api/config.ts b/x-pack/test/saved_object_tagging/api_integration/tagging_api/config.ts index 11f776356df69..ebdb055bd5e89 100644 --- a/x-pack/test/saved_object_tagging/api_integration/tagging_api/config.ts +++ b/x-pack/test/saved_object_tagging/api_integration/tagging_api/config.ts @@ -6,7 +6,7 @@ */ import path from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; // eslint-disable-next-line import/no-default-export diff --git a/x-pack/test/saved_object_tagging/api_integration/tagging_api/services.ts b/x-pack/test/saved_object_tagging/api_integration/tagging_api/services.ts index 1d26b3dd35c96..194d6ec533066 100644 --- a/x-pack/test/saved_object_tagging/api_integration/tagging_api/services.ts +++ b/x-pack/test/saved_object_tagging/api_integration/tagging_api/services.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services as apiIntegrationServices } from '../../../api_integration/services'; export const services = { diff --git a/x-pack/test/saved_object_tagging/functional/config.ts b/x-pack/test/saved_object_tagging/functional/config.ts index ccb55d37f5fa0..0044063e18c69 100644 --- a/x-pack/test/saved_object_tagging/functional/config.ts +++ b/x-pack/test/saved_object_tagging/functional/config.ts @@ -6,7 +6,7 @@ */ import path from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services, pageObjects } from './ftr_provider_context'; // eslint-disable-next-line import/no-default-export diff --git a/x-pack/test/saved_object_tagging/functional/ftr_provider_context.ts b/x-pack/test/saved_object_tagging/functional/ftr_provider_context.ts index 849dca0989335..643f34a59f69c 100644 --- a/x-pack/test/saved_object_tagging/functional/ftr_provider_context.ts +++ b/x-pack/test/saved_object_tagging/functional/ftr_provider_context.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from '../../functional/services'; import { pageObjects } from '../../functional/page_objects'; diff --git a/x-pack/test/saved_objects_field_count/config.ts b/x-pack/test/saved_objects_field_count/config.ts index ab9c88ae86330..8144bac35ec7b 100644 --- a/x-pack/test/saved_objects_field_count/config.ts +++ b/x-pack/test/saved_objects_field_count/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { testRunner } from './runner'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/search_sessions_integration/config.ts b/x-pack/test/search_sessions_integration/config.ts index 831257738f64c..1e2d648712098 100644 --- a/x-pack/test/search_sessions_integration/config.ts +++ b/x-pack/test/search_sessions_integration/config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from '../functional/services'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/search_sessions_integration/ftr_provider_context.d.ts b/x-pack/test/search_sessions_integration/ftr_provider_context.d.ts index c65eeb91fe5b9..8ce17281223e1 100644 --- a/x-pack/test/search_sessions_integration/ftr_provider_context.d.ts +++ b/x-pack/test/search_sessions_integration/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from '../functional/page_objects'; import { services } from '../functional/services'; diff --git a/x-pack/test/security_api_integration/anonymous.config.ts b/x-pack/test/security_api_integration/anonymous.config.ts index ab2573822d440..80ac45507de73 100644 --- a/x-pack/test/security_api_integration/anonymous.config.ts +++ b/x-pack/test/security_api_integration/anonymous.config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const kibanaAPITestsConfig = await readConfigFile( diff --git a/x-pack/test/security_api_integration/anonymous_es_anonymous.config.ts b/x-pack/test/security_api_integration/anonymous_es_anonymous.config.ts index 25fb8154dd8d4..60691769729fa 100644 --- a/x-pack/test/security_api_integration/anonymous_es_anonymous.config.ts +++ b/x-pack/test/security_api_integration/anonymous_es_anonymous.config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const anonymousAPITestsConfig = await readConfigFile(require.resolve('./anonymous.config.ts')); diff --git a/x-pack/test/security_api_integration/audit.config.ts b/x-pack/test/security_api_integration/audit.config.ts index 60b1c0bf1fa80..02b3870c18f89 100644 --- a/x-pack/test/security_api_integration/audit.config.ts +++ b/x-pack/test/security_api_integration/audit.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const xPackAPITestsConfig = await readConfigFile(require.resolve('../api_integration/config.ts')); diff --git a/x-pack/test/security_api_integration/ftr_provider_context.d.ts b/x-pack/test/security_api_integration/ftr_provider_context.d.ts index 671866cad6ff5..647664d640466 100644 --- a/x-pack/test/security_api_integration/ftr_provider_context.d.ts +++ b/x-pack/test/security_api_integration/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; export type FtrProviderContext = GenericFtrProviderContext; diff --git a/x-pack/test/security_api_integration/kerberos.config.ts b/x-pack/test/security_api_integration/kerberos.config.ts index c3f647aadc6d1..7dba77e61999e 100644 --- a/x-pack/test/security_api_integration/kerberos.config.ts +++ b/x-pack/test/security_api_integration/kerberos.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/security_api_integration/kerberos_anonymous_access.config.ts b/x-pack/test/security_api_integration/kerberos_anonymous_access.config.ts index 40ec36e51f702..355f0e90bcd91 100644 --- a/x-pack/test/security_api_integration/kerberos_anonymous_access.config.ts +++ b/x-pack/test/security_api_integration/kerberos_anonymous_access.config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const kerberosAPITestsConfig = await readConfigFile(require.resolve('./kerberos.config.ts')); diff --git a/x-pack/test/security_api_integration/login_selector.config.ts b/x-pack/test/security_api_integration/login_selector.config.ts index f9ef0903b39aa..a21bc0d58733e 100644 --- a/x-pack/test/security_api_integration/login_selector.config.ts +++ b/x-pack/test/security_api_integration/login_selector.config.ts @@ -8,7 +8,7 @@ import { readFileSync } from 'fs'; import { resolve } from 'path'; import { CA_CERT_PATH, KBN_CERT_PATH, KBN_KEY_PATH } from '@kbn/dev-utils'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const kibanaAPITestsConfig = await readConfigFile( diff --git a/x-pack/test/security_api_integration/oidc.config.ts b/x-pack/test/security_api_integration/oidc.config.ts index 05fbaa4122818..a475d77aa568b 100644 --- a/x-pack/test/security_api_integration/oidc.config.ts +++ b/x-pack/test/security_api_integration/oidc.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/security_api_integration/oidc_implicit_flow.config.ts b/x-pack/test/security_api_integration/oidc_implicit_flow.config.ts index 685b71358846e..3b9edcbec6826 100644 --- a/x-pack/test/security_api_integration/oidc_implicit_flow.config.ts +++ b/x-pack/test/security_api_integration/oidc_implicit_flow.config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { const oidcAPITestsConfig = await readConfigFile(require.resolve('./oidc.config.ts')); diff --git a/x-pack/test/security_api_integration/pki.config.ts b/x-pack/test/security_api_integration/pki.config.ts index c284ddc800327..d920a4375753c 100644 --- a/x-pack/test/security_api_integration/pki.config.ts +++ b/x-pack/test/security_api_integration/pki.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { CA_CERT_PATH, KBN_CERT_PATH, KBN_KEY_PATH } from '@kbn/dev-utils'; import { services } from './services'; diff --git a/x-pack/test/security_api_integration/saml.config.ts b/x-pack/test/security_api_integration/saml.config.ts index a3e5c4a3419c8..c8de50008c3bb 100644 --- a/x-pack/test/security_api_integration/saml.config.ts +++ b/x-pack/test/security_api_integration/saml.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/security_api_integration/session_idle.config.ts b/x-pack/test/security_api_integration/session_idle.config.ts index 92549b8369365..77d91f6df3cef 100644 --- a/x-pack/test/security_api_integration/session_idle.config.ts +++ b/x-pack/test/security_api_integration/session_idle.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; // the default export of config files must be a config provider diff --git a/x-pack/test/security_api_integration/session_invalidate.config.ts b/x-pack/test/security_api_integration/session_invalidate.config.ts index 82510062035a9..7d69ca50c0320 100644 --- a/x-pack/test/security_api_integration/session_invalidate.config.ts +++ b/x-pack/test/security_api_integration/session_invalidate.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; // the default export of config files must be a config provider diff --git a/x-pack/test/security_api_integration/session_lifespan.config.ts b/x-pack/test/security_api_integration/session_lifespan.config.ts index 1dbcfbf96d551..b692f10bad5a6 100644 --- a/x-pack/test/security_api_integration/session_lifespan.config.ts +++ b/x-pack/test/security_api_integration/session_lifespan.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; // the default export of config files must be a config provider diff --git a/x-pack/test/security_api_integration/token.config.ts b/x-pack/test/security_api_integration/token.config.ts index 170d98bf5efa4..54efd77ca8ae9 100644 --- a/x-pack/test/security_api_integration/token.config.ts +++ b/x-pack/test/security_api_integration/token.config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; export default async function ({ readConfigFile }: FtrConfigProviderContext) { diff --git a/x-pack/test/security_functional/ftr_provider_context.d.ts b/x-pack/test/security_functional/ftr_provider_context.d.ts index 0225c54768af5..66d4e37b795ca 100644 --- a/x-pack/test/security_functional/ftr_provider_context.d.ts +++ b/x-pack/test/security_functional/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from '../functional/page_objects'; import { services } from '../functional/services'; diff --git a/x-pack/test/security_functional/login_selector.config.ts b/x-pack/test/security_functional/login_selector.config.ts index 6f7a2a8b3de70..e2ddf8dacb79c 100644 --- a/x-pack/test/security_functional/login_selector.config.ts +++ b/x-pack/test/security_functional/login_selector.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from '../functional/services'; import { pageObjects } from '../functional/page_objects'; diff --git a/x-pack/test/security_functional/oidc.config.ts b/x-pack/test/security_functional/oidc.config.ts index 056d7b8197c9a..db8799ba1acf7 100644 --- a/x-pack/test/security_functional/oidc.config.ts +++ b/x-pack/test/security_functional/oidc.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from '../functional/services'; import { pageObjects } from '../functional/page_objects'; diff --git a/x-pack/test/security_functional/saml.config.ts b/x-pack/test/security_functional/saml.config.ts index 50948ce6d411e..a983e2747239c 100644 --- a/x-pack/test/security_functional/saml.config.ts +++ b/x-pack/test/security_functional/saml.config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from '../functional/services'; import { pageObjects } from '../functional/page_objects'; diff --git a/x-pack/test/security_solution_cypress/cli_config.ts b/x-pack/test/security_solution_cypress/cli_config.ts index 2fc32a5210813..443c3dd423409 100644 --- a/x-pack/test/security_solution_cypress/cli_config.ts +++ b/x-pack/test/security_solution_cypress/cli_config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { SecuritySolutionCypressCliTestRunner } from './runner'; diff --git a/x-pack/test/security_solution_cypress/config.firefox.ts b/x-pack/test/security_solution_cypress/config.firefox.ts index 5d11c6d9364a1..9c9f2c2314a31 100644 --- a/x-pack/test/security_solution_cypress/config.firefox.ts +++ b/x-pack/test/security_solution_cypress/config.firefox.ts @@ -7,7 +7,7 @@ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { CA_CERT_PATH } from '@kbn/dev-utils'; diff --git a/x-pack/test/security_solution_cypress/config.ts b/x-pack/test/security_solution_cypress/config.ts index e096bafc9e262..95743369de0d7 100644 --- a/x-pack/test/security_solution_cypress/config.ts +++ b/x-pack/test/security_solution_cypress/config.ts @@ -7,7 +7,7 @@ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { CA_CERT_PATH } from '@kbn/dev-utils'; diff --git a/x-pack/test/security_solution_cypress/ftr_provider_context.d.ts b/x-pack/test/security_solution_cypress/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/security_solution_cypress/ftr_provider_context.d.ts +++ b/x-pack/test/security_solution_cypress/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/security_solution_cypress/visual_config.ts b/x-pack/test/security_solution_cypress/visual_config.ts index 489dd1e626221..b6808a4c35638 100644 --- a/x-pack/test/security_solution_cypress/visual_config.ts +++ b/x-pack/test/security_solution_cypress/visual_config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { SecuritySolutionCypressVisualTestRunner } from './runner'; 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 bd8ce806609b3..4c40cb005e8c4 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 @@ -21,7 +21,8 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const testSubjects = getService('testSubjects'); const policyTestResources = getService('policyTestResources'); - describe('When on the Endpoint Policy Details Page', function () { + // Failing: See https://github.com/elastic/kibana/issues/100236 + describe.skip('When on the Endpoint Policy Details Page', function () { describe('with an invalid policy id', () => { it('should display an error', async () => { await pageObjects.policy.navigateToPolicyDetails('invalid-id'); diff --git a/x-pack/test/security_solution_endpoint/config.ts b/x-pack/test/security_solution_endpoint/config.ts index 77a63acc389e2..188cccac9301b 100644 --- a/x-pack/test/security_solution_endpoint/config.ts +++ b/x-pack/test/security_solution_endpoint/config.ts @@ -6,7 +6,7 @@ */ import { resolve } from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { services } from './services'; import { diff --git a/x-pack/test/security_solution_endpoint/ftr_provider_context.d.ts b/x-pack/test/security_solution_endpoint/ftr_provider_context.d.ts index ec28c00e72e47..24f5087ef7fe2 100644 --- a/x-pack/test/security_solution_endpoint/ftr_provider_context.d.ts +++ b/x-pack/test/security_solution_endpoint/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { services } from './services'; diff --git a/x-pack/test/security_solution_endpoint_api_int/config.ts b/x-pack/test/security_solution_endpoint_api_int/config.ts index a2eec01046161..d53365a8b6ec6 100644 --- a/x-pack/test/security_solution_endpoint_api_int/config.ts +++ b/x-pack/test/security_solution_endpoint_api_int/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { createEndpointDockerConfig, getRegistryUrlAsArray } from './registry'; import { services } from './services'; diff --git a/x-pack/test/security_solution_endpoint_api_int/ftr_provider_context.d.ts b/x-pack/test/security_solution_endpoint_api_int/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/security_solution_endpoint_api_int/ftr_provider_context.d.ts +++ b/x-pack/test/security_solution_endpoint_api_int/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/spaces_api_integration/common/config.ts b/x-pack/test/spaces_api_integration/common/config.ts index 2daebba801200..d1e4dae76b636 100644 --- a/x-pack/test/spaces_api_integration/common/config.ts +++ b/x-pack/test/spaces_api_integration/common/config.ts @@ -7,7 +7,7 @@ import path from 'path'; import { REPO_ROOT } from '@kbn/utils'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; interface CreateTestConfigOptions { license: string; diff --git a/x-pack/test/spaces_api_integration/common/ftr_provider_context.d.ts b/x-pack/test/spaces_api_integration/common/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/spaces_api_integration/common/ftr_provider_context.d.ts +++ b/x-pack/test/spaces_api_integration/common/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/ui_capabilities/common/config.ts b/x-pack/test/ui_capabilities/common/config.ts index 0c40df181ffdc..9c0ce92755e8e 100644 --- a/x-pack/test/ui_capabilities/common/config.ts +++ b/x-pack/test/ui_capabilities/common/config.ts @@ -6,7 +6,7 @@ */ import path from 'path'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/ui_capabilities/common/ftr_provider_context.d.ts b/x-pack/test/ui_capabilities/common/ftr_provider_context.d.ts index d612023be9160..aa56557c09df8 100644 --- a/x-pack/test/ui_capabilities/common/ftr_provider_context.d.ts +++ b/x-pack/test/ui_capabilities/common/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/upgrade/config.ts b/x-pack/test/upgrade/config.ts index 86555335ba47b..472b83fe7a934 100644 --- a/x-pack/test/upgrade/config.ts +++ b/x-pack/test/upgrade/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { ReportingAPIProvider } from './reporting_services'; diff --git a/x-pack/test/upgrade/ftr_provider_context.d.ts b/x-pack/test/upgrade/ftr_provider_context.d.ts index ec28c00e72e47..24f5087ef7fe2 100644 --- a/x-pack/test/upgrade/ftr_provider_context.d.ts +++ b/x-pack/test/upgrade/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { services } from './services'; diff --git a/x-pack/test/usage_collection/config.ts b/x-pack/test/usage_collection/config.ts index df1d1d9fd21f7..beb934219422a 100644 --- a/x-pack/test/usage_collection/config.ts +++ b/x-pack/test/usage_collection/config.ts @@ -7,7 +7,7 @@ import { resolve } from 'path'; import fs from 'fs'; -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; import { pageObjects } from './page_objects'; diff --git a/x-pack/test/usage_collection/ftr_provider_context.d.ts b/x-pack/test/usage_collection/ftr_provider_context.d.ts index 2dce44a533405..13bd4b46607c4 100644 --- a/x-pack/test/usage_collection/ftr_provider_context.d.ts +++ b/x-pack/test/usage_collection/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { services } from './services'; import { pageObjects } from './page_objects'; diff --git a/x-pack/test/visual_regression/config.ts b/x-pack/test/visual_regression/config.ts index 5d36f200d149f..c211918ef8e52 100644 --- a/x-pack/test/visual_regression/config.ts +++ b/x-pack/test/visual_regression/config.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; +import { FtrConfigProviderContext } from '@kbn/test'; import { services } from './services'; diff --git a/x-pack/test/visual_regression/ftr_provider_context.d.ts b/x-pack/test/visual_regression/ftr_provider_context.d.ts index ec28c00e72e47..24f5087ef7fe2 100644 --- a/x-pack/test/visual_regression/ftr_provider_context.d.ts +++ b/x-pack/test/visual_regression/ftr_provider_context.d.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { GenericFtrProviderContext } from '@kbn/test/types/ftr'; +import { GenericFtrProviderContext } from '@kbn/test'; import { pageObjects } from './page_objects'; import { services } from './services';