From f1a2e6f25179bdf249626d7ed408abf250322e84 Mon Sep 17 00:00:00 2001 From: Brian Seeders Date: Mon, 17 May 2021 15:53:20 -0400 Subject: [PATCH 01/19] skip flaky suite (#100236) --- .../security_solution_endpoint/apps/endpoint/policy_details.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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'); From 7f9364ac8ac42399a86961d239964be04429649b Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Mon, 17 May 2021 21:04:35 +0100 Subject: [PATCH 02/19] [ML] Fixing use_null setting in advanced job wizard (#100028) * [ML] Fixing use_null setting in advanced job wizard * fixing types * fixing false checks for detector fields Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> --- .../job_creator/advanced_job_creator.ts | 23 ++++++++++++++----- .../common/job_creator/util/general.ts | 5 ++-- .../advanced_detector_modal.tsx | 1 + .../advanced_view/metric_selection.tsx | 7 ++++-- 4 files changed, 26 insertions(+), 10 deletions(-) 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(); From 6d4cca29a7e1d3e85536cf424e2c15a2f37ca251 Mon Sep 17 00:00:00 2001 From: Dominique Clarke Date: Mon, 17 May 2021 16:44:30 -0400 Subject: [PATCH 03/19] [Uptime] [Synthetics Integration] Add functional tests for Synthetics Integration (#100161) * add functional tests for synthetics fleet package --- .../components/fleet_package/combo_box.tsx | 3 +- .../fleet_package/custom_fields.tsx | 8 + .../fleet_package/http_advanced_fields.tsx | 12 + .../index_response_body_field.tsx | 2 +- .../fleet_package/request_body_field.tsx | 4 + .../fleet_package/tcp_advanced_fields.tsx | 11 +- .../components/fleet_package/tls_fields.tsx | 5 + x-pack/test/functional/apps/uptime/index.ts | 1 + .../apps/uptime/synthetics_integration.ts | 442 ++++++++++++++++++ x-pack/test/functional/config.js | 3 + x-pack/test/functional/page_objects/index.ts | 2 + .../synthetics_integration_page.ts | 384 +++++++++++++++ .../services/uptime/synthetics_package.ts | 176 +++++++ .../test/functional/services/uptime/uptime.ts | 3 + 14 files changed, 1052 insertions(+), 4 deletions(-) create mode 100644 x-pack/test/functional/apps/uptime/synthetics_integration.ts create mode 100644 x-pack/test/functional/page_objects/synthetics_integration_page.ts create mode 100644 x-pack/test/functional/services/uptime/synthetics_package.ts 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/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/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/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/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, }; } From e15b887e4376ec3431eddedc9dab80ca305779e3 Mon Sep 17 00:00:00 2001 From: Frank Hassanabad Date: Mon, 17 May 2021 23:28:06 -0600 Subject: [PATCH 04/19] [Security Solutions] Replaces most deprecated io-ts alerting and list types (#100234) ## Summary Replaces most of the deprecated io-ts alerting and list types within securitysolution as part of Phase 3 of 4 phases outlined in earlier PR's such as https://github.com/elastic/kibana/pull/99260 ### Checklist - [x] [Unit or functional tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html) were updated or added to match the most common scenarios --- .../src/get_index_aliases/index.ts | 7 +- .../src/get_index_count/index.ts | 7 +- .../src/index.ts | 3 + .../src/read_index/index.ts | 7 +- .../src/from/index.ts | 3 + .../src/index.ts | 2 + .../src/language/index.ts | 3 + .../src/machine_learning_job_id/index.ts | 19 + .../src/max_signals/index.ts | 3 + .../src/risk_score/index.ts | 8 + .../src/risk_score_mapping/index.ts | 8 +- .../src/threat/index.ts | 3 + .../src/threat_subtechnique/index.ts | 2 + .../src/threat_technique/index.ts | 2 + .../src/type/index.ts | 22 + .../src/index.ts | 2 - .../src/type/index.ts | 1 + .../src/default_version_number/index.test.ts | 0 .../src/default_version_number/index.ts | 0 .../src/index.ts | 2 + .../src/version/index.ts | 5 +- .../exceptions/build_exceptions_filter.ts | 6 +- .../plugins/lists/common/exceptions/utils.ts | 2 +- .../lists/common/schemas/common/schemas.ts | 18 - .../request/create_exception_list_schema.ts | 8 +- .../schemas/request/create_list_schema.ts | 8 +- .../schemas/request/patch_list_schema.ts | 3 +- .../request/update_exception_list_schema.ts | 3 +- .../schemas/request/update_list_schema.ts | 3 +- .../schemas/response/exception_list_schema.ts | 2 +- .../common/schemas/response/list_schema.ts | 2 +- x-pack/plugins/lists/common/shared_exports.ts | 5 +- .../builder/exception_items_renderer.tsx | 2 +- .../exceptions/components/builder/helpers.ts | 2 +- x-pack/plugins/lists/public/index.ts | 6 +- .../elastic_query/index_es_list_schema.ts | 2 +- .../elastic_response/search_es_list_schema.ts | 2 +- .../exceptions_list_so_schema.ts | 2 +- .../create_endoint_event_filters_list.ts | 3 +- .../exception_lists/create_endpoint_list.ts | 3 +- .../create_endpoint_trusted_apps_list.ts | 3 +- .../exception_lists/create_exception_list.ts | 3 +- .../exception_list_client_types.ts | 4 +- .../exception_lists/update_exception_list.ts | 2 +- .../items/write_lines_to_bulk_list_items.ts | 2 +- .../server/services/lists/create_list.ts | 2 +- .../lists/create_list_if_it_does_not_exist.ts | 2 +- .../services/lists/list_client_types.ts | 3 +- .../server/services/lists/update_list.ts | 3 +- .../common/add_remove_id_to_item.test.ts | 77 --- .../common/add_remove_id_to_item.ts | 50 -- .../detection_engine/get_query_filter.ts | 3 +- .../schemas/common/schemas.ts | 452 +----------------- .../request/add_prepackaged_rules_schema.ts | 77 ++- .../add_prepackged_rules_schema.test.ts | 3 +- .../request/create_rules_bulk_schema.test.ts | 4 +- .../create_signals_migration_schema.ts | 2 +- .../request/export_rules_schema.test.ts | 3 +- .../schemas/request/export_rules_schema.ts | 5 +- .../schemas/request/find_rules_schema.test.ts | 3 +- .../schemas/request/find_rules_schema.ts | 3 +- .../get_signals_migration_status_schema.ts | 2 +- .../request/import_rules_schema.test.ts | 3 +- .../schemas/request/import_rules_schema.ts | 83 ++-- .../request/patch_rules_bulk_schema.test.ts | 4 +- .../request/patch_rules_schema.test.ts | 3 +- .../schemas/request/patch_rules_schema.ts | 50 +- .../request/query_rules_bulk_schema.test.ts | 4 +- .../request/query_rules_schema.test.ts | 3 +- .../query_signals_index_schema.test.ts | 3 +- .../request/query_signals_index_schema.ts | 2 +- .../schemas/request/rule_schemas.test.ts | 3 +- .../schemas/request/rule_schemas.ts | 27 +- .../request/set_signal_status_schema.test.ts | 3 +- .../request/update_rules_bulk_schema.test.ts | 4 +- .../schemas/response/error_schema.test.ts | 3 +- .../response/import_rules_schema.test.ts | 3 +- .../response/prepackaged_rules_schema.test.ts | 3 +- .../prepackaged_rules_status_schema.test.ts | 3 +- .../response/rules_bulk_schema.test.ts | 3 +- .../schemas/response/rules_schema.test.ts | 5 +- .../schemas/response/rules_schema.ts | 52 +- .../type_timeline_only_schema.test.ts | 3 +- .../response/type_timeline_only_schema.ts | 3 +- .../types/deafult_boolean_true.test.ts | 51 -- .../schemas/types/deafult_from_string.test.ts | 42 -- .../types/default_actions_array.test.ts | 57 --- .../schemas/types/default_actions_array.ts | 23 - .../schemas/types/default_array.test.ts | 81 ---- .../schemas/types/default_array.ts | 27 -- .../types/default_boolean_false.test.ts | 51 -- .../schemas/types/default_boolean_false.ts | 22 - .../schemas/types/default_boolean_true.ts | 22 - .../types/default_empty_string.test.ts | 42 -- .../schemas/types/default_empty_string.ts | 22 - .../types/default_export_file_name.test.ts | 42 -- .../schemas/types/default_export_file_name.ts | 22 - .../schemas/types/default_from_string.ts | 26 - .../types/default_interval_string.test.ts | 42 -- .../schemas/types/default_interval_string.ts | 22 - .../types/default_language_string.test.ts | 43 -- .../schemas/types/default_language_string.ts | 23 - .../types/default_max_signals_number.test.ts | 65 --- .../types/default_max_signals_number.ts | 27 -- .../schemas/types/default_page.test.ts | 84 ---- .../schemas/types/default_page.ts | 32 -- .../schemas/types/default_per_page.test.ts | 84 ---- .../schemas/types/default_per_page.ts | 32 -- .../types/default_risk_score_mapping_array.ts | 27 -- .../types/default_severity_mapping_array.ts | 27 -- .../types/default_string_array.test.ts | 51 -- .../schemas/types/default_string_array.ts | 23 - .../default_string_boolean_false.test.ts | 100 ---- .../types/default_string_boolean_false.ts | 34 -- .../types/default_threat_array.test.ts | 65 --- .../schemas/types/default_threat_array.ts | 23 - .../types/default_throttle_null.test.ts | 43 -- .../schemas/types/default_throttle_null.ts | 23 - .../schemas/types/default_to_string.test.ts | 42 -- .../schemas/types/default_to_string.ts | 22 - .../schemas/types/default_uuid.test.ts | 42 -- .../schemas/types/default_uuid.ts | 26 - .../types/default_version_number.test.ts | 64 --- .../schemas/types/default_version_number.ts | 25 - .../detection_engine/schemas/types/index.ts | 40 -- .../schemas/types/iso_date_string.test.ts | 55 --- .../schemas/types/iso_date_string.ts | 38 -- .../schemas/types/lists.mock.ts | 2 +- .../schemas/types/lists.test.ts | 134 ------ .../detection_engine/schemas/types/lists.ts | 30 -- .../schemas/types/lists_default_array.test.ts | 64 --- .../schemas/types/lists_default_array.ts | 24 - .../schemas/types/non_empty_array.test.ts | 95 ---- .../schemas/types/non_empty_array.ts | 32 -- .../schemas/types/non_empty_string.test.ts | 55 --- .../schemas/types/non_empty_string.ts | 29 -- .../schemas/types/normalized_ml_job_id.ts | 36 -- .../schemas/types/only_false_allowed.test.ts | 53 -- .../schemas/types/only_false_allowed.ts | 33 -- .../schemas/types/positive_integer.ts | 26 - ...positive_integer_greater_than_zero.test.ts | 55 --- .../positive_integer_greater_than_zero.ts | 26 - .../schemas/types/postive_integer.test.ts | 53 -- .../types/references_default_array.test.ts | 51 -- .../schemas/types/references_default_array.ts | 22 - .../schemas/types/risk_score.test.ts | 60 --- .../schemas/types/risk_score.ts | 28 -- .../schemas/types/threat.mock.ts | 2 +- .../schemas/types/threat_mapping.test.ts | 236 --------- .../schemas/types/threat_mapping.ts | 214 --------- .../schemas/types/uuid.test.ts | 42 -- .../detection_engine/schemas/types/uuid.ts | 30 -- .../common/detection_engine/utils.ts | 3 +- .../common/exact_check.test.ts | 177 ------- .../security_solution/common/exact_check.ts | 94 ---- .../common/format_errors.test.ts | 188 -------- .../security_solution/common/format_errors.ts | 35 -- .../plugins/security_solution/common/index.ts | 2 - .../common/machine_learning/helpers.ts | 2 +- .../common/shared_exports.ts | 20 - .../common/shared_imports.ts | 3 - .../security_solution/common/test_utils.ts | 61 --- .../common/types/timeline/index.ts | 2 +- .../security_solution/common/validate.test.ts | 49 -- .../security_solution/common/validate.ts | 55 --- .../autocomplete/field_value_lists.test.tsx | 6 +- .../autocomplete/field_value_lists.tsx | 2 +- .../common/components/autocomplete/helpers.ts | 2 +- .../exceptions/add_exception_modal/index.tsx | 7 +- .../exceptions/edit_exception_modal/index.tsx | 7 +- .../components/exceptions/error_callout.tsx | 2 +- .../common/components/exceptions/types.ts | 13 +- .../exceptions/use_add_exception.test.tsx | 4 +- .../exceptions/use_add_exception.tsx | 2 +- ...tch_or_create_rule_exception_list.test.tsx | 3 +- ...se_fetch_or_create_rule_exception_list.tsx | 4 +- .../exception_item/exception_details.tsx | 4 +- .../viewer/exception_item/index.tsx | 4 +- .../viewer/exceptions_viewer_items.tsx | 4 +- .../components/exceptions/viewer/helpers.tsx | 4 +- .../exceptions/viewer/index.test.tsx | 4 +- .../components/exceptions/viewer/index.tsx | 2 +- .../components/exceptions/viewer/reducer.ts | 6 +- .../common/components/links/index.test.tsx | 2 +- .../markdown_editor/renderer.test.tsx | 2 +- .../threat_match/entry_delete_button.test.tsx | 2 +- .../components/threat_match/helpers.test.tsx | 2 +- .../components/threat_match/helpers.tsx | 8 +- .../common/components/threat_match/index.tsx | 2 +- .../components/threat_match/reducer.test.ts | 2 +- .../common/components/threat_match/types.ts | 2 +- .../rules/description_step/helpers.tsx | 4 +- .../rules/description_step/index.tsx | 3 +- .../rules/description_step/types.ts | 2 +- .../components/rules/mitre/helpers.ts | 2 +- .../components/rules/mitre/index.tsx | 2 +- .../rules/mitre/subtechnique_fields.tsx | 5 +- .../rules/mitre/technique_fields.tsx | 5 +- .../components/rules/query_preview/helpers.ts | 2 +- .../components/rules/query_preview/index.tsx | 2 +- .../components/rules/query_preview/reducer.ts | 2 +- .../rules/risk_score_mapping/index.tsx | 2 +- .../rules/select_rule_type/index.tsx | 2 +- .../rules/severity_mapping/index.tsx | 10 +- .../components/rules/step_about_rule/data.tsx | 2 +- .../detection_engine/rules/transforms.ts | 2 +- .../detection_engine/rules/types.ts | 27 +- .../rules/use_dissasociate_exception_list.tsx | 2 +- .../detections/mitre/valid_threat_mock.ts | 2 +- .../rules/create/helpers.test.ts | 4 +- .../detection_engine/rules/create/helpers.ts | 20 +- .../pages/detection_engine/rules/helpers.tsx | 12 +- .../pages/detection_engine/rules/types.ts | 20 +- .../public/lists_plugin_deps.ts | 10 - .../network/components/port/index.test.tsx | 2 +- .../source_destination/index.test.tsx | 2 +- .../source_destination_ip.test.tsx | 2 +- .../certificate_fingerprint/index.test.tsx | 2 +- .../components/ja3_fingerprint/index.test.tsx | 2 +- .../components/netflow/index.test.tsx | 2 +- .../body/renderers/get_row_renderer.test.tsx | 2 +- .../suricata/suricata_details.test.tsx | 2 +- .../suricata/suricata_row_renderer.test.tsx | 2 +- .../system/generic_row_renderer.test.tsx | 2 +- .../body/renderers/zeek/zeek_details.test.tsx | 2 +- .../renderers/zeek/zeek_row_renderer.test.tsx | 2 +- .../renderers/zeek/zeek_signature.test.tsx | 2 +- .../server/endpoint/lib/artifacts/lists.ts | 2 +- .../server/endpoint/lib/artifacts/manifest.ts | 2 +- .../endpoint/routes/trusted_apps/mapping.ts | 2 +- .../endpoint/schemas/artifacts/lists.ts | 2 +- .../services/artifacts/manifest_client.ts | 2 +- .../errors/bad_request_error.ts | 8 - .../index/create_bootstrap_index.ts | 34 -- .../index/delete_all_index.ts | 51 -- .../detection_engine/index/delete_policy.ts | 23 - .../detection_engine/index/delete_template.ts | 21 - .../index/get_index_exists.test.ts | 61 --- .../index/get_index_exists.ts | 34 -- .../index/get_policy_exists.ts | 33 -- .../index/get_template_exists.ts | 22 - .../lib/detection_engine/index/set_policy.ts | 25 - .../detection_engine/index/set_template.ts | 24 - .../create_migration_saved_object.ts | 2 +- .../migrations/finalize_migration.test.ts | 4 +- .../migrations/finalize_migration.ts | 2 +- .../find_migration_saved_objects.ts | 2 +- .../get_migration_saved_objects_by_id.ts | 2 +- .../migrations/saved_objects_schema.ts | 2 +- .../update_migration_saved_object.ts | 2 +- .../routes/index/create_index_route.ts | 15 +- .../routes/index/delete_index_route.ts | 17 +- .../routes/index/get_index_version.ts | 2 +- .../routes/index/read_index_route.ts | 5 +- .../privileges/read_privileges_route.ts | 4 +- .../rules/add_prepackaged_rules_route.ts | 6 +- .../routes/rules/create_rules_bulk_route.ts | 4 +- .../routes/rules/create_rules_route.ts | 5 +- .../routes/rules/delete_rules_bulk_route.ts | 2 +- .../routes/rules/delete_rules_route.ts | 4 +- .../routes/rules/export_rules_route.ts | 3 +- .../routes/rules/find_rules_route.ts | 4 +- .../routes/rules/find_rules_status_route.ts | 4 +- .../get_prepackaged_rules_status_route.ts | 6 +- .../routes/rules/import_rules_route.ts | 6 +- .../routes/rules/patch_rules_bulk_route.ts | 2 +- .../routes/rules/patch_rules_route.ts | 4 +- .../routes/rules/read_rules_route.ts | 4 +- .../routes/rules/update_rules_bulk_route.ts | 2 +- .../routes/rules/update_rules_route.ts | 4 +- .../routes/rules/utils.test.ts | 2 +- .../detection_engine/routes/rules/validate.ts | 2 +- .../create_signals_migration_route.test.ts | 10 +- .../signals/create_signals_migration_route.ts | 6 +- .../signals/delete_signals_migration_route.ts | 4 +- .../finalize_signals_migration_route.ts | 5 +- .../get_signals_migration_status_route.ts | 4 +- .../signals/open_close_signals_route.ts | 4 +- .../routes/signals/query_signals_route.ts | 3 +- .../routes/tags/read_tags_route.ts | 4 +- .../lib/detection_engine/routes/utils.test.ts | 93 +--- .../lib/detection_engine/routes/utils.ts | 43 +- .../create_rules_stream_from_ndjson.test.ts | 2 +- .../rules/create_rules_stream_from_ndjson.ts | 5 +- .../rules/get_prepackaged_rules.ts | 5 +- .../lib/detection_engine/rules/patch_rules.ts | 2 +- .../lib/detection_engine/rules/types.ts | 62 +-- .../lib/detection_engine/rules/utils.ts | 42 +- .../detection_engine/schemas/rule_schemas.ts | 27 +- .../detection_engine/signals/filters/types.ts | 3 +- .../detection_engine/signals/get_filter.ts | 6 +- .../build_risk_score_from_mapping.test.ts | 5 +- .../mappings/build_risk_score_from_mapping.ts | 7 +- .../build_severity_from_mapping.test.ts | 6 +- .../mappings/build_severity_from_mapping.ts | 5 +- .../signals/signal_rule_alert_type.ts | 2 +- .../build_threat_mapping_filter.mock.ts | 2 +- .../build_threat_mapping_filter.test.ts | 5 +- .../build_threat_mapping_filter.ts | 2 +- .../signals/threat_mapping/types.ts | 10 +- .../lib/detection_engine/signals/utils.ts | 2 +- .../server/lib/detection_engine/types.ts | 43 +- .../server/lib/machine_learning/authz.ts | 3 +- .../clean_draft_timelines/index.ts | 4 +- .../get_draft_timelines/index.ts | 4 +- .../lib/timeline/routes/notes/persist_note.ts | 3 +- .../pinned_events/persist_pinned_event.ts | 3 +- .../install_prepackaged_timelines/index.ts | 5 +- .../timelines/create_timelines/index.ts | 3 +- .../timelines/delete_timelines/index.ts | 4 +- .../timelines/export_timelines/index.ts | 3 +- .../routes/timelines/get_timeline/index.ts | 3 +- .../routes/timelines/get_timelines/index.ts | 3 +- .../create_timelines_stream_from_ndjson.ts | 2 +- .../timelines/import_timelines/helpers.ts | 2 +- .../timelines/import_timelines/index.ts | 3 +- .../routes/timelines/patch_timelines/index.ts | 3 +- .../timelines/persist_favorite/index.ts | 3 +- .../server/lib/timeline/utils/common.ts | 28 +- .../build_validation/route_validation.ts | 3 +- .../read_stream/create_stream_from_ndjson.ts | 5 +- .../detection_engine_api_integration/utils.ts | 2 +- x-pack/test/lists_api_integration/utils.ts | 2 +- 323 files changed, 719 insertions(+), 5578 deletions(-) rename x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_aliases.ts => packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts (80%) rename x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_count.ts => packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts (71%) rename x-pack/plugins/security_solution/server/lib/detection_engine/index/read_index.ts => packages/kbn-securitysolution-es-utils/src/read_index/index.ts (55%) create mode 100644 packages/kbn-securitysolution-io-ts-alerting-types/src/machine_learning_job_id/index.ts create mode 100644 packages/kbn-securitysolution-io-ts-alerting-types/src/type/index.ts rename packages/{kbn-securitysolution-io-ts-list-types => kbn-securitysolution-io-ts-types}/src/default_version_number/index.test.ts (100%) rename packages/{kbn-securitysolution-io-ts-list-types => kbn-securitysolution-io-ts-types}/src/default_version_number/index.ts (100%) rename packages/{kbn-securitysolution-io-ts-list-types => kbn-securitysolution-io-ts-types}/src/version/index.ts (78%) delete mode 100644 x-pack/plugins/security_solution/common/add_remove_id_to_item.test.ts delete mode 100644 x-pack/plugins/security_solution/common/add_remove_id_to_item.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_boolean_true.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_from_string.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_array.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_array.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_true.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_from_string.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_risk_score_mapping_array.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_severity_mapping_array.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/index.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/iso_date_string.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/iso_date_string.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists_default_array.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists_default_array.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_array.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_array.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/normalized_ml_job_id.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/only_false_allowed.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/only_false_allowed.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer_greater_than_zero.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer_greater_than_zero.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/postive_integer.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/risk_score.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/risk_score.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/threat_mapping.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/threat_mapping.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/uuid.test.ts delete mode 100644 x-pack/plugins/security_solution/common/detection_engine/schemas/types/uuid.ts delete mode 100644 x-pack/plugins/security_solution/common/exact_check.test.ts delete mode 100644 x-pack/plugins/security_solution/common/exact_check.ts delete mode 100644 x-pack/plugins/security_solution/common/format_errors.test.ts delete mode 100644 x-pack/plugins/security_solution/common/format_errors.ts delete mode 100644 x-pack/plugins/security_solution/common/shared_exports.ts delete mode 100644 x-pack/plugins/security_solution/common/test_utils.ts delete mode 100644 x-pack/plugins/security_solution/common/validate.test.ts delete mode 100644 x-pack/plugins/security_solution/common/validate.ts delete mode 100644 x-pack/plugins/security_solution/public/lists_plugin_deps.ts delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/errors/bad_request_error.ts delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/index/create_bootstrap_index.ts delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/index/delete_all_index.ts delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/index/delete_policy.ts delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/index/delete_template.ts delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_exists.test.ts delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/index/get_index_exists.ts delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/index/get_policy_exists.ts delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/index/get_template_exists.ts delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/index/set_policy.ts delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/index/set_template.ts 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/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/security_solution/common/add_remove_id_to_item.test.ts b/x-pack/plugins/security_solution/common/add_remove_id_to_item.test.ts deleted file mode 100644 index 0bd88adda7264..0000000000000 --- a/x-pack/plugins/security_solution/common/add_remove_id_to_item.test.ts +++ /dev/null @@ -1,77 +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 { addIdToItem, removeIdFromItem } from './add_remove_id_to_item'; - -jest.mock('uuid', () => ({ - 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/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/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/errors/bad_request_error.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/errors/bad_request_error.ts deleted file mode 100644 index c68e7845953f6..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/errors/bad_request_error.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export class BadRequestError extends Error {} 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/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/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'; From 6bb55f824e59a307598efa2fb2683e1016239deb Mon Sep 17 00:00:00 2001 From: Frank Hassanabad Date: Tue, 18 May 2021 01:24:12 -0600 Subject: [PATCH 05/19] Reduce limits of security solutions to max + 15kb (#100247) ## Summary With recent package changes and fixes we are down to 61kb for page load bundle. General rules are max kilobytes + 15kb for buffer so that would mean we should lower it to be 76kb. Resolves #95870 --- packages/kbn-optimizer/limits.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 15abf24339ccb69b2c2c185c4a5de2472195be82 Mon Sep 17 00:00:00 2001 From: Marta Bondyra Date: Tue, 18 May 2021 10:13:39 +0200 Subject: [PATCH 06/19] [Lens] Debounce axis name inputs mob programming (#100108) --- .../dimension_panel/dimension_editor.tsx | 42 +++------------ .../definitions/ranges/ranges.test.tsx | 11 ++++ .../shared_components/label_input.tsx | 15 ++---- .../indexpattern_datasource/query_input.tsx | 12 ++--- .../lens/public/pie_visualization/toolbar.tsx | 13 ++--- .../shared_components/debounced_value.ts | 52 +++++++++++++++++++ .../lens/public/shared_components/index.ts | 1 + .../axis_settings_popover.tsx | 14 +++-- 8 files changed, 89 insertions(+), 71 deletions(-) create mode 100644 x-pack/plugins/lens/public/shared_components/debounced_value.ts 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/axis_settings_popover.tsx b/x-pack/plugins/lens/public/xy_visualization/axis_settings_popover.tsx index d9c60ae666484..d995e1a055e68 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 from 'react'; import { EuiFlexGroup, EuiFlexItem, @@ -17,7 +17,7 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { XYLayerConfig, AxesSettingsConfig } from './types'; -import { ToolbarPopover } from '../shared_components'; +import { ToolbarPopover, useDebouncedValue } from '../shared_components'; import { isHorizontalChart } from './state_helpers'; import { EuiIconAxisBottom } from '../assets/axis_bottom'; import { EuiIconAxisLeft } from '../assets/axis_left'; @@ -149,15 +149,13 @@ 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: title, handleInputChange: onTitleChange } = useDebouncedValue({ + value: axisTitle || '', + onChange: updateTitleState, + }); return ( Date: Tue, 18 May 2021 12:33:16 +0200 Subject: [PATCH 07/19] Migrate from Joi to @kbn/config-schema in "home" and "features" plugins (#100201) * add a link for issue to remove circular deps * features: migrate from joi to config-schema * update tests * migrate home tutorials to config-schema * migrate home dataset validation to config schema * remove unnecessary type. we cannot guarantee this is a valid SO * address Pierres comments --- src/plugins/home/server/services/index.ts | 1 - .../lib/sample_dataset_registry_types.ts | 56 +--- .../sample_data/lib/sample_dataset_schema.ts | 92 ++++-- .../services/sample_data/routes/install.ts | 10 +- .../sample_data/sample_data_registry.ts | 9 +- .../home/server/services/tutorials/index.ts | 1 - .../services/tutorials/lib/tutorial_schema.ts | 220 +++++++------ .../tutorials/lib/tutorials_registry_types.ts | 90 +----- .../tutorials/tutorials_registry.test.ts | 2 +- .../services/tutorials/tutorials_registry.ts | 9 +- .../usage_collector/get_usage_collector.ts | 4 +- x-pack/plugins/apm/server/plugin.ts | 1 + .../feature_registry.test.ts.snap | 20 +- .../server/feature_privilege_iterator.js | 1 + .../features/server/feature_registry.test.ts | 33 +- .../plugins/features/server/feature_schema.ts | 306 +++++++++++------- 16 files changed, 440 insertions(+), 415 deletions(-) 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/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/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) => { From 3c166a14724800623206844404117e088a800c3f Mon Sep 17 00:00:00 2001 From: Joe Reuter Date: Tue, 18 May 2021 12:36:35 +0200 Subject: [PATCH 08/19] [Lens] Specify Y axis extent (#99203) --- .../__snapshots__/expression.test.tsx.snap | 49 ++++ .../__snapshots__/to_expression.test.ts.snap | 40 +++ .../xy_visualization/axes_configuration.ts | 18 +- .../axis_settings_popover.test.tsx | 23 ++ .../axis_settings_popover.tsx | 227 +++++++++++++++++- .../xy_visualization/expression.test.tsx | 140 +++++++++++ .../public/xy_visualization/expression.tsx | 82 +++++-- .../lens/public/xy_visualization/index.ts | 2 + .../xy_visualization/to_expression.test.ts | 5 + .../public/xy_visualization/to_expression.ts | 44 ++++ .../lens/public/xy_visualization/types.ts | 52 ++++ .../xy_visualization/xy_config_panel.test.tsx | 84 +++++++ .../xy_visualization/xy_config_panel.tsx | 92 ++++++- .../public/xy_visualization/xy_suggestions.ts | 3 + 14 files changed, 834 insertions(+), 27 deletions(-) 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 d995e1a055e68..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 from 'react'; +import React, { useEffect, useState } from 'react'; import { EuiFlexGroup, EuiFlexItem, @@ -14,9 +14,13 @@ import { EuiSpacer, EuiFieldText, IconType, + EuiFormRow, + EuiButtonGroup, + htmlIdGenerator, + EuiFieldNumber, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { XYLayerConfig, AxesSettingsConfig } from './types'; +import { XYLayerConfig, AxesSettingsConfig, AxisExtentConfig } from './types'; import { ToolbarPopover, useDebouncedValue } from '../shared_components'; import { isHorizontalChart } from './state_helpers'; import { EuiIconAxisBottom } from '../assets/axis_bottom'; @@ -24,6 +28,7 @@ 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,10 +165,45 @@ export const AxisSettingsPopover: React.FunctionComponent { const isHorizontal = layers?.length ? isHorizontalChart(layers) : false; const config = popoverConfig(axis, isHorizontal); + 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, @@ -234,6 +286,177 @@ export const AxisSettingsPopover: React.FunctionComponent )} + {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, From 574b4559e7402e6fe6890277736b1ea91fae18d3 Mon Sep 17 00:00:00 2001 From: Thom Heymann <190132+thomheymann@users.noreply.github.com> Date: Tue, 18 May 2021 11:37:18 +0100 Subject: [PATCH 09/19] Simplify deleting spaces (#99960) * Simplify deleting spaces * Fixed i18n * Fix functional tests * Update x-pack/plugins/spaces/public/management/spaces_management_app.tsx Co-authored-by: Larry Gregory * Fix snapshots Co-authored-by: Larry Gregory Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> --- .../confirm_delete_modal.test.tsx.snap | 93 ----- .../confirm_delete_modal.scss | 3 - .../confirm_delete_modal.test.tsx | 83 +++-- .../confirm_delete_modal.tsx | 317 ++++++------------ .../edit_space/delete_spaces_button.tsx | 43 +-- ...sx.snap => spaces_grid_page.test.tsx.snap} | 0 ...ges.test.tsx => spaces_grid_page.test.tsx} | 0 .../spaces_grid/spaces_grid_page.tsx | 49 +-- .../management/spaces_management_app.tsx | 52 +-- .../translations/translations/ja-JP.json | 12 - .../translations/translations/zh-CN.json | 13 - x-pack/test/accessibility/apps/spaces.ts | 4 - .../page_objects/space_selector_page.ts | 4 - 13 files changed, 201 insertions(+), 472 deletions(-) delete mode 100644 x-pack/plugins/spaces/public/management/components/confirm_delete_modal/__snapshots__/confirm_delete_modal.test.tsx.snap delete mode 100644 x-pack/plugins/spaces/public/management/components/confirm_delete_modal/confirm_delete_modal.scss rename x-pack/plugins/spaces/public/management/spaces_grid/__snapshots__/{spaces_grid_pages.test.tsx.snap => spaces_grid_page.test.tsx.snap} (100%) rename x-pack/plugins/spaces/public/management/spaces_grid/{spaces_grid_pages.test.tsx => spaces_grid_page.test.tsx} (100%) 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 c46b59bce2f8e..a2615ae9713a2 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -22650,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": "キャンセル", @@ -22721,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": " (表示されているすべての機能) ", @@ -22738,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": "スペースに名前を付けてアバターをカスタマイズします。", @@ -22773,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": "識別子", @@ -22783,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 90aa517c68232..a6cf8e5ddb865 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -23009,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": "取消", @@ -23082,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": " (所有可见功能) ", @@ -23099,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": "命名您的工作区并定制其头像。", @@ -23134,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": "标识符", @@ -23144,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/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/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'); } From 5c3527d8a63deefd4fc3ef2d4b5e7381f6c34422 Mon Sep 17 00:00:00 2001 From: Uladzislau Lasitsa Date: Tue, 18 May 2021 15:28:10 +0300 Subject: [PATCH 10/19] [XY axis] Improve expression with explicit params (#98897) * Removed visconfig and using explicit params instead in xy_plugin * Fix CI * Fix i18n * Fix unit test * Fix some remarks * move expressions into separate chunk * fix CI * Update label.ts Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> Co-authored-by: Alexey Antonov --- .../public/__snapshots__/to_ast.test.ts.snap | 2 +- src/plugins/vis_type_xy/common/index.ts | 13 +- .../public/__snapshots__/to_ast.test.ts.snap | 63 +++- .../public/editor/common_config.tsx | 6 +- .../expression_functions/category_axis.ts | 116 ++++++++ .../public/expression_functions/index.ts | 18 ++ .../public/expression_functions/label.ts | 89 ++++++ .../expression_functions/series_param.ts | 128 ++++++++ .../expression_functions/threshold_line.ts | 86 ++++++ .../expression_functions/time_marker.ts | 82 ++++++ .../public/expression_functions/value_axis.ts | 79 +++++ .../public/expression_functions/vis_scale.ts | 98 +++++++ .../expression_functions/xy_dimension.ts | 85 ++++++ .../public/expression_functions/xy_vis_fn.ts | 273 ++++++++++++++++++ src/plugins/vis_type_xy/public/plugin.ts | 17 +- .../public/sample_vis.test.mocks.ts | 6 + src/plugins/vis_type_xy/public/to_ast.test.ts | 2 +- src/plugins/vis_type_xy/public/to_ast.ts | 148 +++++++++- .../vis_type_xy/public/types/config.ts | 2 +- .../vis_type_xy/public/types/constants.ts | 89 +++--- src/plugins/vis_type_xy/public/types/index.ts | 2 +- src/plugins/vis_type_xy/public/types/param.ts | 65 ++++- .../utils/render_all_series.test.mocks.ts | 8 +- .../vis_type_xy/public/vis_renderer.tsx | 9 +- src/plugins/vis_type_xy/public/xy_vis_fn.ts | 77 ----- 25 files changed, 1389 insertions(+), 174 deletions(-) create mode 100644 src/plugins/vis_type_xy/public/expression_functions/category_axis.ts create mode 100644 src/plugins/vis_type_xy/public/expression_functions/index.ts create mode 100644 src/plugins/vis_type_xy/public/expression_functions/label.ts create mode 100644 src/plugins/vis_type_xy/public/expression_functions/series_param.ts create mode 100644 src/plugins/vis_type_xy/public/expression_functions/threshold_line.ts create mode 100644 src/plugins/vis_type_xy/public/expression_functions/time_marker.ts create mode 100644 src/plugins/vis_type_xy/public/expression_functions/value_axis.ts create mode 100644 src/plugins/vis_type_xy/public/expression_functions/vis_scale.ts create mode 100644 src/plugins/vis_type_xy/public/expression_functions/xy_dimension.ts create mode 100644 src/plugins/vis_type_xy/public/expression_functions/xy_vis_fn.ts delete mode 100644 src/plugins/vis_type_xy/public/xy_vis_fn.ts diff --git a/src/plugins/vis_type_vislib/public/__snapshots__/to_ast.test.ts.snap b/src/plugins/vis_type_vislib/public/__snapshots__/to_ast.test.ts.snap index c3ffc0dd08412..3ca2834a54fca 100644 --- a/src/plugins/vis_type_vislib/public/__snapshots__/to_ast.test.ts.snap +++ b/src/plugins/vis_type_vislib/public/__snapshots__/to_ast.test.ts.snap @@ -8,7 +8,7 @@ Object { "area", ], "visConfig": Array [ - "{\\"type\\":\\"area\\",\\"grid\\":{\\"categoryLines\\":false,\\"style\\":{\\"color\\":\\"#eee\\"}},\\"categoryAxes\\":[{\\"id\\":\\"CategoryAxis-1\\",\\"type\\":\\"category\\",\\"position\\":\\"bottom\\",\\"show\\":true,\\"style\\":{},\\"scale\\":{\\"type\\":\\"linear\\"},\\"labels\\":{\\"show\\":true,\\"truncate\\":100},\\"title\\":{}}],\\"valueAxes\\":[{\\"id\\":\\"ValueAxis-1\\",\\"name\\":\\"LeftAxis-1\\",\\"type\\":\\"value\\",\\"position\\":\\"left\\",\\"show\\":true,\\"style\\":{},\\"scale\\":{\\"type\\":\\"linear\\",\\"mode\\":\\"normal\\"},\\"labels\\":{\\"show\\":true,\\"rotate\\":0,\\"filter\\":false,\\"truncate\\":100},\\"title\\":{\\"text\\":\\"Sum of total_quantity\\"}}],\\"seriesParams\\":[{\\"show\\":\\"true\\",\\"type\\":\\"area\\",\\"mode\\":\\"stacked\\",\\"data\\":{\\"label\\":\\"Sum of total_quantity\\",\\"id\\":\\"1\\"},\\"drawLinesBetweenPoints\\":true,\\"showCircles\\":true,\\"interpolate\\":\\"linear\\",\\"valueAxis\\":\\"ValueAxis-1\\"}],\\"addTooltip\\":true,\\"addLegend\\":true,\\"legendPosition\\":\\"top\\",\\"times\\":[],\\"addTimeMarker\\":false,\\"thresholdLine\\":{\\"show\\":false,\\"value\\":10,\\"width\\":1,\\"style\\":\\"full\\",\\"color\\":\\"#E7664C\\"},\\"labels\\":{},\\"dimensions\\":{\\"x\\":{\\"accessor\\":1,\\"format\\":{\\"id\\":\\"date\\",\\"params\\":{\\"pattern\\":\\"HH:mm:ss.SSS\\"}},\\"params\\":{}},\\"y\\":[{\\"accessor\\":0,\\"format\\":{\\"id\\":\\"number\\",\\"params\\":{\\"parsedUrl\\":{\\"origin\\":\\"http://localhost:5801\\",\\"pathname\\":\\"/app/visualize\\",\\"basePath\\":\\"\\"}}},\\"params\\":{}}],\\"series\\":[{\\"accessor\\":2,\\"format\\":{\\"id\\":\\"terms\\",\\"params\\":{\\"id\\":\\"string\\",\\"otherBucketLabel\\":\\"Other\\",\\"missingBucketLabel\\":\\"Missing\\",\\"parsedUrl\\":{\\"origin\\":\\"http://localhost:5801\\",\\"pathname\\":\\"/app/visualize\\",\\"basePath\\":\\"\\"}}},\\"params\\":{}}]}}", + "{\\"type\\":\\"area\\",\\"grid\\":{\\"categoryLines\\":false,\\"style\\":{\\"color\\":\\"#eee\\"}},\\"categoryAxes\\":[{\\"id\\":\\"CategoryAxis-1\\",\\"type\\":\\"category\\",\\"position\\":\\"bottom\\",\\"show\\":true,\\"style\\":{},\\"scale\\":{\\"type\\":\\"linear\\"},\\"labels\\":{\\"show\\":true,\\"truncate\\":100},\\"title\\":{}}],\\"valueAxes\\":[{\\"id\\":\\"ValueAxis-1\\",\\"name\\":\\"LeftAxis-1\\",\\"type\\":\\"value\\",\\"position\\":\\"left\\",\\"show\\":true,\\"style\\":{},\\"scale\\":{\\"type\\":\\"linear\\",\\"mode\\":\\"normal\\"},\\"labels\\":{\\"show\\":true,\\"rotate\\":0,\\"filter\\":false,\\"truncate\\":100},\\"title\\":{\\"text\\":\\"Sum of total_quantity\\"}}],\\"seriesParams\\":[{\\"show\\":\\"true\\",\\"type\\":\\"area\\",\\"mode\\":\\"stacked\\",\\"data\\":{\\"label\\":\\"Sum of total_quantity\\",\\"id\\":\\"1\\"},\\"drawLinesBetweenPoints\\":true,\\"showCircles\\":true,\\"interpolate\\":\\"linear\\",\\"valueAxis\\":\\"ValueAxis-1\\"}],\\"addTooltip\\":true,\\"addLegend\\":true,\\"legendPosition\\":\\"top\\",\\"times\\":[],\\"addTimeMarker\\":false,\\"thresholdLine\\":{\\"show\\":false,\\"value\\":10,\\"width\\":1,\\"style\\":\\"full\\",\\"color\\":\\"#E7664C\\"},\\"palette\\":{\\"name\\":\\"default\\"},\\"labels\\":{},\\"dimensions\\":{\\"x\\":{\\"accessor\\":1,\\"format\\":{\\"id\\":\\"date\\",\\"params\\":{\\"pattern\\":\\"HH:mm:ss.SSS\\"}},\\"params\\":{}},\\"y\\":[{\\"accessor\\":0,\\"format\\":{\\"id\\":\\"number\\",\\"params\\":{\\"parsedUrl\\":{\\"origin\\":\\"http://localhost:5801\\",\\"pathname\\":\\"/app/visualize\\",\\"basePath\\":\\"\\"}}},\\"params\\":{}}],\\"series\\":[{\\"accessor\\":2,\\"format\\":{\\"id\\":\\"terms\\",\\"params\\":{\\"id\\":\\"string\\",\\"otherBucketLabel\\":\\"Other\\",\\"missingBucketLabel\\":\\"Missing\\",\\"parsedUrl\\":{\\"origin\\":\\"http://localhost:5801\\",\\"pathname\\":\\"/app/visualize\\",\\"basePath\\":\\"\\"}}},\\"params\\":{}}]}}", ], }, "getArgument": [Function], diff --git a/src/plugins/vis_type_xy/common/index.ts b/src/plugins/vis_type_xy/common/index.ts index 903adb53eb403..a80946f7c62fa 100644 --- a/src/plugins/vis_type_xy/common/index.ts +++ b/src/plugins/vis_type_xy/common/index.ts @@ -6,17 +6,14 @@ * Side Public License, v 1. */ -import { $Values } from '@kbn/utility-types'; - /** * Type of charts able to render */ -export const ChartType = Object.freeze({ - Line: 'line' as const, - Area: 'area' as const, - Histogram: 'histogram' as const, -}); -export type ChartType = $Values; +export enum ChartType { + Line = 'line', + Area = 'area', + Histogram = 'histogram', +} /** * Type of xy visualizations diff --git a/src/plugins/vis_type_xy/public/__snapshots__/to_ast.test.ts.snap b/src/plugins/vis_type_xy/public/__snapshots__/to_ast.test.ts.snap index e6665c26a2815..7c21e699216bc 100644 --- a/src/plugins/vis_type_xy/public/__snapshots__/to_ast.test.ts.snap +++ b/src/plugins/vis_type_xy/public/__snapshots__/to_ast.test.ts.snap @@ -4,11 +4,70 @@ exports[`xy vis toExpressionAst function should match basic snapshot 1`] = ` Object { "addArgument": [Function], "arguments": Object { + "addLegend": Array [ + true, + ], + "addTimeMarker": Array [ + false, + ], + "addTooltip": Array [ + true, + ], + "categoryAxes": Array [ + Object { + "toAst": [Function], + }, + ], + "chartType": Array [ + "area", + ], + "gridCategoryLines": Array [ + false, + ], + "labels": Array [ + Object { + "toAst": [Function], + }, + ], + "legendPosition": Array [ + "top", + ], + "palette": Array [ + "default", + ], + "seriesDimension": Array [ + Object { + "toAst": [Function], + }, + ], + "seriesParams": Array [ + Object { + "toAst": [Function], + }, + ], + "thresholdLine": Array [ + Object { + "toAst": [Function], + }, + ], + "times": Array [], "type": Array [ "area", ], - "visConfig": Array [ - "{\\"type\\":\\"area\\",\\"grid\\":{\\"categoryLines\\":false,\\"style\\":{\\"color\\":\\"#eee\\"}},\\"categoryAxes\\":[{\\"id\\":\\"CategoryAxis-1\\",\\"type\\":\\"category\\",\\"position\\":\\"bottom\\",\\"show\\":true,\\"style\\":{},\\"scale\\":{\\"type\\":\\"linear\\"},\\"labels\\":{\\"show\\":true,\\"truncate\\":100},\\"title\\":{}}],\\"valueAxes\\":[{\\"id\\":\\"ValueAxis-1\\",\\"name\\":\\"LeftAxis-1\\",\\"type\\":\\"value\\",\\"position\\":\\"left\\",\\"show\\":true,\\"style\\":{},\\"scale\\":{\\"type\\":\\"linear\\",\\"mode\\":\\"normal\\"},\\"labels\\":{\\"show\\":true,\\"rotate\\":0,\\"filter\\":false,\\"truncate\\":100},\\"title\\":{\\"text\\":\\"Sum of total_quantity\\"}}],\\"seriesParams\\":[{\\"show\\":\\"true\\",\\"type\\":\\"area\\",\\"mode\\":\\"stacked\\",\\"data\\":{\\"label\\":\\"Sum of total_quantity\\",\\"id\\":\\"1\\"},\\"drawLinesBetweenPoints\\":true,\\"showCircles\\":true,\\"interpolate\\":\\"linear\\",\\"valueAxis\\":\\"ValueAxis-1\\"}],\\"addTooltip\\":true,\\"addLegend\\":true,\\"legendPosition\\":\\"top\\",\\"times\\":[],\\"addTimeMarker\\":false,\\"thresholdLine\\":{\\"show\\":false,\\"value\\":10,\\"width\\":1,\\"style\\":\\"full\\",\\"color\\":\\"#E7664C\\"},\\"labels\\":{},\\"dimensions\\":{\\"x\\":{\\"accessor\\":1,\\"format\\":{\\"id\\":\\"date\\",\\"params\\":{\\"pattern\\":\\"HH:mm:ss.SSS\\"}},\\"params\\":{}},\\"y\\":[{\\"accessor\\":0,\\"format\\":{\\"id\\":\\"number\\",\\"params\\":{\\"parsedUrl\\":{\\"origin\\":\\"http://localhost:5801\\",\\"pathname\\":\\"/app/visualize\\",\\"basePath\\":\\"\\"}}},\\"params\\":{}}],\\"series\\":[{\\"accessor\\":2,\\"format\\":{\\"id\\":\\"terms\\",\\"params\\":{\\"id\\":\\"string\\",\\"otherBucketLabel\\":\\"Other\\",\\"missingBucketLabel\\":\\"Missing\\",\\"parsedUrl\\":{\\"origin\\":\\"http://localhost:5801\\",\\"pathname\\":\\"/app/visualize\\",\\"basePath\\":\\"\\"}}},\\"params\\":{}}]}}", + "valueAxes": Array [ + Object { + "toAst": [Function], + }, + ], + "xDimension": Array [ + Object { + "toAst": [Function], + }, + ], + "yDimension": Array [ + Object { + "toAst": [Function], + }, ], }, "getArgument": [Function], diff --git a/src/plugins/vis_type_xy/public/editor/common_config.tsx b/src/plugins/vis_type_xy/public/editor/common_config.tsx index 1e4ac7df0082c..1815d9cfc429d 100644 --- a/src/plugins/vis_type_xy/public/editor/common_config.tsx +++ b/src/plugins/vis_type_xy/public/editor/common_config.tsx @@ -9,11 +9,11 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; -import { VisEditorOptionsProps } from '../../../visualizations/public'; +import type { VisEditorOptionsProps } from '../../../visualizations/public'; -import { VisParams } from '../types'; +import type { VisParams } from '../types'; import { MetricsAxisOptions, PointSeriesOptions } from './components/options'; -import { ValidationWrapper } from './components/common'; +import { ValidationWrapper } from './components/common/validation_wrapper'; export function getOptionTabs(showElasticChartsOptions = false) { return [ diff --git a/src/plugins/vis_type_xy/public/expression_functions/category_axis.ts b/src/plugins/vis_type_xy/public/expression_functions/category_axis.ts new file mode 100644 index 0000000000000..30215d8feb8a3 --- /dev/null +++ b/src/plugins/vis_type_xy/public/expression_functions/category_axis.ts @@ -0,0 +1,116 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18n } from '@kbn/i18n'; +import type { + ExpressionFunctionDefinition, + Datatable, + ExpressionValueBoxed, +} from '../../../expressions/public'; +import type { CategoryAxis } from '../types'; +import type { ExpressionValueScale } from './vis_scale'; +import type { ExpressionValueLabel } from './label'; + +export interface Arguments extends Omit { + title?: string; + scale: ExpressionValueScale; + labels: ExpressionValueLabel; +} + +export type ExpressionValueCategoryAxis = ExpressionValueBoxed< + 'category_axis', + { + id: CategoryAxis['id']; + show: CategoryAxis['show']; + position: CategoryAxis['position']; + axisType: CategoryAxis['type']; + title: { + text?: string; + }; + labels: CategoryAxis['labels']; + scale: CategoryAxis['scale']; + } +>; + +export const categoryAxis = (): ExpressionFunctionDefinition< + 'categoryaxis', + Datatable | null, + Arguments, + ExpressionValueCategoryAxis +> => ({ + name: 'categoryaxis', + help: i18n.translate('visTypeXy.function.categoryAxis.help', { + defaultMessage: 'Generates category axis object', + }), + type: 'category_axis', + args: { + id: { + types: ['string'], + help: i18n.translate('visTypeXy.function.categoryAxis.id.help', { + defaultMessage: 'Id of category axis', + }), + required: true, + }, + show: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.categoryAxis.show.help', { + defaultMessage: 'Show the category axis', + }), + required: true, + }, + position: { + types: ['string'], + help: i18n.translate('visTypeXy.function.categoryAxis.position.help', { + defaultMessage: 'Position of the category axis', + }), + required: true, + }, + type: { + types: ['string'], + help: i18n.translate('visTypeXy.function.categoryAxis.type.help', { + defaultMessage: 'Type of the category axis. Can be category or value', + }), + required: true, + }, + title: { + types: ['string'], + help: i18n.translate('visTypeXy.function.categoryAxis.title.help', { + defaultMessage: 'Title of the category axis', + }), + }, + scale: { + types: ['vis_scale'], + help: i18n.translate('visTypeXy.function.categoryAxis.scale.help', { + defaultMessage: 'Scale config', + }), + }, + labels: { + types: ['label'], + help: i18n.translate('visTypeXy.function.categoryAxis.labels.help', { + defaultMessage: 'Axis label config', + }), + }, + }, + fn: (context, args) => { + return { + type: 'category_axis', + id: args.id, + show: args.show, + position: args.position, + axisType: args.type, + title: { + text: args.title, + }, + scale: { + ...args.scale, + type: args.scale.scaleType, + }, + labels: args.labels, + }; + }, +}); diff --git a/src/plugins/vis_type_xy/public/expression_functions/index.ts b/src/plugins/vis_type_xy/public/expression_functions/index.ts new file mode 100644 index 0000000000000..4e7db57ee65d7 --- /dev/null +++ b/src/plugins/vis_type_xy/public/expression_functions/index.ts @@ -0,0 +1,18 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export { visTypeXyVisFn } from './xy_vis_fn'; + +export { categoryAxis, ExpressionValueCategoryAxis } from './category_axis'; +export { timeMarker, ExpressionValueTimeMarker } from './time_marker'; +export { valueAxis, ExpressionValueValueAxis } from './value_axis'; +export { seriesParam, ExpressionValueSeriesParam } from './series_param'; +export { thresholdLine, ExpressionValueThresholdLine } from './threshold_line'; +export { label, ExpressionValueLabel } from './label'; +export { visScale, ExpressionValueScale } from './vis_scale'; +export { xyDimension, ExpressionValueXYDimension } from './xy_dimension'; diff --git a/src/plugins/vis_type_xy/public/expression_functions/label.ts b/src/plugins/vis_type_xy/public/expression_functions/label.ts new file mode 100644 index 0000000000000..934278d13cff0 --- /dev/null +++ b/src/plugins/vis_type_xy/public/expression_functions/label.ts @@ -0,0 +1,89 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18n } from '@kbn/i18n'; +import type { Labels } from '../../../charts/public'; +import type { + ExpressionFunctionDefinition, + Datatable, + ExpressionValueBoxed, +} from '../../../expressions/public'; + +export type ExpressionValueLabel = ExpressionValueBoxed< + 'label', + { + color?: Labels['color']; + filter?: Labels['filter']; + overwriteColor?: Labels['overwriteColor']; + rotate?: Labels['rotate']; + show?: Labels['show']; + truncate?: Labels['truncate']; + } +>; + +export const label = (): ExpressionFunctionDefinition< + 'label', + Datatable | null, + Labels, + ExpressionValueLabel +> => ({ + name: 'label', + help: i18n.translate('visTypeXy.function.label.help', { + defaultMessage: 'Generates label object', + }), + type: 'label', + args: { + color: { + types: ['string'], + help: i18n.translate('visTypeXy.function.label.color.help', { + defaultMessage: 'Color of label', + }), + }, + filter: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.label.filter.help', { + defaultMessage: 'Hides overlapping labels and duplicates on axis', + }), + }, + overwriteColor: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.label.overwriteColor.help', { + defaultMessage: 'Overwrite color', + }), + }, + rotate: { + types: ['number'], + help: i18n.translate('visTypeXy.function.label.rotate.help', { + defaultMessage: 'Rotate angle', + }), + }, + show: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.label.show.help', { + defaultMessage: 'Show label', + }), + }, + truncate: { + types: ['number', 'null'], + help: i18n.translate('visTypeXy.function.label.truncate.help', { + defaultMessage: 'The number of symbols before truncating', + }), + }, + }, + fn: (context, args) => { + return { + type: 'label', + color: args.color, + filter: args.hasOwnProperty('filter') ? args.filter : undefined, + overwriteColor: args.overwriteColor, + rotate: args.rotate, + show: args.show, + truncate: args.truncate, + }; + }, +}); diff --git a/src/plugins/vis_type_xy/public/expression_functions/series_param.ts b/src/plugins/vis_type_xy/public/expression_functions/series_param.ts new file mode 100644 index 0000000000000..402187cea6586 --- /dev/null +++ b/src/plugins/vis_type_xy/public/expression_functions/series_param.ts @@ -0,0 +1,128 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18n } from '@kbn/i18n'; +import type { + ExpressionFunctionDefinition, + Datatable, + ExpressionValueBoxed, +} from '../../../expressions/public'; +import type { SeriesParam } from '../types'; + +export interface Arguments extends Omit { + label: string; + id: string; +} + +export type ExpressionValueSeriesParam = ExpressionValueBoxed< + 'series_param', + { + data: { label: string; id: string }; + drawLinesBetweenPoints?: boolean; + interpolate?: SeriesParam['interpolate']; + lineWidth?: number; + mode: SeriesParam['mode']; + show: boolean; + showCircles: boolean; + seriesParamType: SeriesParam['type']; + valueAxis: string; + } +>; + +export const seriesParam = (): ExpressionFunctionDefinition< + 'seriesparam', + Datatable, + Arguments, + ExpressionValueSeriesParam +> => ({ + name: 'seriesparam', + help: i18n.translate('visTypeXy.function.seriesparam.help', { + defaultMessage: 'Generates series param object', + }), + type: 'series_param', + inputTypes: ['datatable'], + args: { + label: { + types: ['string'], + help: i18n.translate('visTypeXy.function.seriesParam.label.help', { + defaultMessage: 'Name of series param', + }), + required: true, + }, + id: { + types: ['string'], + help: i18n.translate('visTypeXy.function.seriesParam.id.help', { + defaultMessage: 'Id of series param', + }), + required: true, + }, + drawLinesBetweenPoints: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.seriesParam.drawLinesBetweenPoints.help', { + defaultMessage: 'Draw lines between points', + }), + }, + interpolate: { + types: ['string'], + help: i18n.translate('visTypeXy.function.seriesParam.interpolate.help', { + defaultMessage: 'Interpolate mode. Can be linear, cardinal or step-after', + }), + }, + show: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.seriesParam.show.help', { + defaultMessage: 'Show param', + }), + required: true, + }, + lineWidth: { + types: ['number'], + help: i18n.translate('visTypeXy.function.seriesParam.lineWidth.help', { + defaultMessage: 'Width of line', + }), + }, + mode: { + types: ['string'], + help: i18n.translate('visTypeXy.function.seriesParam.mode.help', { + defaultMessage: 'Chart mode. Can be stacked or percentage', + }), + }, + showCircles: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.seriesParam.showCircles.help', { + defaultMessage: 'Show circles', + }), + }, + type: { + types: ['string'], + help: i18n.translate('visTypeXy.function.seriesParam.type.help', { + defaultMessage: 'Chart type. Can be line, area or histogram', + }), + }, + valueAxis: { + types: ['string'], + help: i18n.translate('visTypeXy.function.seriesParam.valueAxis.help', { + defaultMessage: 'Name of value axis', + }), + }, + }, + fn: (context, args) => { + return { + type: 'series_param', + data: { label: args.label, id: args.id }, + drawLinesBetweenPoints: args.drawLinesBetweenPoints, + interpolate: args.interpolate, + lineWidth: args.lineWidth, + mode: args.mode, + show: args.show, + showCircles: args.showCircles, + seriesParamType: args.type, + valueAxis: args.valueAxis, + }; + }, +}); diff --git a/src/plugins/vis_type_xy/public/expression_functions/threshold_line.ts b/src/plugins/vis_type_xy/public/expression_functions/threshold_line.ts new file mode 100644 index 0000000000000..8c01e37503985 --- /dev/null +++ b/src/plugins/vis_type_xy/public/expression_functions/threshold_line.ts @@ -0,0 +1,86 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18n } from '@kbn/i18n'; +import type { + ExpressionFunctionDefinition, + Datatable, + ExpressionValueBoxed, +} from '../../../expressions/public'; +import type { ThresholdLine } from '../types'; + +export type ExpressionValueThresholdLine = ExpressionValueBoxed< + 'threshold_line', + { + show: ThresholdLine['show']; + value: ThresholdLine['value']; + width: ThresholdLine['width']; + style: ThresholdLine['style']; + color: ThresholdLine['color']; + } +>; + +export const thresholdLine = (): ExpressionFunctionDefinition< + 'thresholdline', + Datatable | null, + ThresholdLine, + ExpressionValueThresholdLine +> => ({ + name: 'thresholdline', + help: i18n.translate('visTypeXy.function.thresholdLine.help', { + defaultMessage: 'Generates threshold line object', + }), + type: 'threshold_line', + args: { + show: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.thresholdLine.show.help', { + defaultMessage: 'Show threshould line', + }), + required: true, + }, + value: { + types: ['number', 'null'], + help: i18n.translate('visTypeXy.function.thresholdLine.value.help', { + defaultMessage: 'Threshold value', + }), + required: true, + }, + width: { + types: ['number', 'null'], + help: i18n.translate('visTypeXy.function.thresholdLine.width.help', { + defaultMessage: 'Width of threshold line', + }), + required: true, + }, + style: { + types: ['string'], + help: i18n.translate('visTypeXy.function.thresholdLine.style.help', { + defaultMessage: 'Style of threshold line. Can be full, dashed or dot-dashed', + }), + required: true, + }, + color: { + types: ['string'], + help: i18n.translate('visTypeXy.function.thresholdLine.color.help', { + defaultMessage: 'Color of threshold line', + }), + required: true, + }, + }, + fn: (context, args) => { + return { + type: 'threshold_line', + show: args.show, + value: args.value, + width: args.width, + style: args.style, + color: args.color, + }; + }, +}); diff --git a/src/plugins/vis_type_xy/public/expression_functions/time_marker.ts b/src/plugins/vis_type_xy/public/expression_functions/time_marker.ts new file mode 100644 index 0000000000000..3d9f609292c00 --- /dev/null +++ b/src/plugins/vis_type_xy/public/expression_functions/time_marker.ts @@ -0,0 +1,82 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18n } from '@kbn/i18n'; +import type { + ExpressionFunctionDefinition, + Datatable, + ExpressionValueBoxed, +} from '../../../expressions/public'; +import type { TimeMarker } from '../types'; + +export type ExpressionValueTimeMarker = ExpressionValueBoxed< + 'time_marker', + { + time: string; + class?: string; + color?: string; + opacity?: number; + width?: number; + } +>; + +export const timeMarker = (): ExpressionFunctionDefinition< + 'timemarker', + Datatable | null, + TimeMarker, + ExpressionValueTimeMarker +> => ({ + name: 'timemarker', + help: i18n.translate('visTypeXy.function.timemarker.help', { + defaultMessage: 'Generates time marker object', + }), + type: 'time_marker', + args: { + time: { + types: ['string'], + help: i18n.translate('visTypeXy.function.timeMarker.time.help', { + defaultMessage: 'Exact Time', + }), + required: true, + }, + class: { + types: ['string'], + help: i18n.translate('visTypeXy.function.timeMarker.class.help', { + defaultMessage: 'Css class name', + }), + }, + color: { + types: ['string'], + help: i18n.translate('visTypeXy.function.timeMarker.color.help', { + defaultMessage: 'Color of time marker', + }), + }, + opacity: { + types: ['number'], + help: i18n.translate('visTypeXy.function.timeMarker.opacity.help', { + defaultMessage: 'Opacity of time marker', + }), + }, + width: { + types: ['number'], + help: i18n.translate('visTypeXy.function.timeMarker.width.help', { + defaultMessage: 'Width of time marker', + }), + }, + }, + fn: (context, args) => { + return { + type: 'time_marker', + time: args.time, + class: args.class, + color: args.color, + opacity: args.opacity, + width: args.width, + }; + }, +}); diff --git a/src/plugins/vis_type_xy/public/expression_functions/value_axis.ts b/src/plugins/vis_type_xy/public/expression_functions/value_axis.ts new file mode 100644 index 0000000000000..510ec9bc605d2 --- /dev/null +++ b/src/plugins/vis_type_xy/public/expression_functions/value_axis.ts @@ -0,0 +1,79 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18n } from '@kbn/i18n'; +import type { ExpressionValueCategoryAxis } from './category_axis'; +import type { CategoryAxis } from '../types'; +import type { + ExpressionFunctionDefinition, + Datatable, + ExpressionValueBoxed, +} from '../../../expressions/public'; + +interface Arguments { + name: string; + axisParams: ExpressionValueCategoryAxis; +} + +export type ExpressionValueValueAxis = ExpressionValueBoxed< + 'value_axis', + { + name: string; + id: string; + show: boolean; + position: CategoryAxis['position']; + axisType: CategoryAxis['type']; + title: { + text?: string; + }; + labels: CategoryAxis['labels']; + scale: CategoryAxis['scale']; + } +>; + +export const valueAxis = (): ExpressionFunctionDefinition< + 'valueaxis', + Datatable | null, + Arguments, + ExpressionValueValueAxis +> => ({ + name: 'valueaxis', + help: i18n.translate('visTypeXy.function.valueaxis.help', { + defaultMessage: 'Generates value axis object', + }), + type: 'value_axis', + args: { + name: { + types: ['string'], + help: i18n.translate('visTypeXy.function.valueAxis.name.help', { + defaultMessage: 'Name of value axis', + }), + required: true, + }, + axisParams: { + types: ['category_axis'], + help: i18n.translate('visTypeXy.function.valueAxis.axisParams.help', { + defaultMessage: 'Value axis params', + }), + required: true, + }, + }, + fn: (context, args) => { + return { + type: 'value_axis', + name: args.name, + id: args.axisParams.id, + show: args.axisParams.show, + position: args.axisParams.position, + axisType: args.axisParams.axisType, + title: args.axisParams.title, + scale: args.axisParams.scale, + labels: args.axisParams.labels, + }; + }, +}); diff --git a/src/plugins/vis_type_xy/public/expression_functions/vis_scale.ts b/src/plugins/vis_type_xy/public/expression_functions/vis_scale.ts new file mode 100644 index 0000000000000..fadf3d80a6e81 --- /dev/null +++ b/src/plugins/vis_type_xy/public/expression_functions/vis_scale.ts @@ -0,0 +1,98 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18n } from '@kbn/i18n'; +import type { + ExpressionFunctionDefinition, + Datatable, + ExpressionValueBoxed, +} from '../../../expressions/public'; +import type { Scale } from '../types'; + +export type ExpressionValueScale = ExpressionValueBoxed< + 'vis_scale', + { + boundsMargin?: Scale['boundsMargin']; + defaultYExtents?: Scale['defaultYExtents']; + max?: Scale['max']; + min?: Scale['min']; + mode?: Scale['mode']; + setYExtents?: Scale['setYExtents']; + scaleType: Scale['type']; + } +>; + +export const visScale = (): ExpressionFunctionDefinition< + 'visscale', + Datatable | null, + Scale, + ExpressionValueScale +> => ({ + name: 'visscale', + help: i18n.translate('visTypeXy.function.scale.help', { + defaultMessage: 'Generates scale object', + }), + type: 'vis_scale', + args: { + boundsMargin: { + types: ['number', 'string'], + help: i18n.translate('visTypeXy.function.scale.boundsMargin.help', { + defaultMessage: 'Margin of bounds', + }), + }, + defaultYExtents: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.scale.defaultYExtents.help', { + defaultMessage: 'Flag which allows to scale to data bounds', + }), + }, + setYExtents: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.scale.setYExtents.help', { + defaultMessage: 'Flag which allows to set your own extents', + }), + }, + max: { + types: ['number', 'null'], + help: i18n.translate('visTypeXy.function.scale.max.help', { + defaultMessage: 'Max value', + }), + }, + min: { + types: ['number', 'null'], + help: i18n.translate('visTypeXy.function.scale.min.help', { + defaultMessage: 'Min value', + }), + }, + mode: { + types: ['string'], + help: i18n.translate('visTypeXy.function.scale.mode.help', { + defaultMessage: 'Scale mode. Can be normal, percentage, wiggle or silhouette', + }), + }, + type: { + types: ['string'], + help: i18n.translate('visTypeXy.function.scale.type.help', { + defaultMessage: 'Scale type. Can be linear, log or square root', + }), + required: true, + }, + }, + fn: (context, args) => { + return { + type: 'vis_scale', + boundsMargin: args.boundsMargin, + defaultYExtents: args.defaultYExtents, + setYExtents: args.setYExtents, + max: args.max, + min: args.min, + mode: args.mode, + scaleType: args.type, + }; + }, +}); diff --git a/src/plugins/vis_type_xy/public/expression_functions/xy_dimension.ts b/src/plugins/vis_type_xy/public/expression_functions/xy_dimension.ts new file mode 100644 index 0000000000000..ecbc3640c035b --- /dev/null +++ b/src/plugins/vis_type_xy/public/expression_functions/xy_dimension.ts @@ -0,0 +1,85 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18n } from '@kbn/i18n'; +import type { ExpressionValueVisDimension } from '../../../visualizations/public'; +import type { + ExpressionFunctionDefinition, + Datatable, + ExpressionValueBoxed, +} from '../../../expressions/public'; +import type { Dimension } from '../types'; + +interface Arguments { + visDimension: ExpressionValueVisDimension; + params: string; + aggType: string; + label: string; +} + +export type ExpressionValueXYDimension = ExpressionValueBoxed< + 'xy_dimension', + { + label: string; + aggType: string; + params: Dimension['params']; + accessor: number; + format: Dimension['format']; + } +>; + +export const xyDimension = (): ExpressionFunctionDefinition< + 'xydimension', + Datatable | null, + Arguments, + ExpressionValueXYDimension +> => ({ + name: 'xydimension', + help: i18n.translate('visTypeXy.function.xydimension.help', { + defaultMessage: 'Generates xy dimension object', + }), + type: 'xy_dimension', + args: { + visDimension: { + types: ['vis_dimension'], + help: i18n.translate('visTypeXy.function.xyDimension.visDimension.help', { + defaultMessage: 'Dimension object config', + }), + required: true, + }, + label: { + types: ['string'], + help: i18n.translate('visTypeXy.function.xyDimension.label.help', { + defaultMessage: 'Label', + }), + }, + aggType: { + types: ['string'], + help: i18n.translate('visTypeXy.function.xyDimension.aggType.help', { + defaultMessage: 'Aggregation type', + }), + }, + params: { + types: ['string'], + default: '"{}"', + help: i18n.translate('visTypeXy.function.xyDimension.params.help', { + defaultMessage: 'Params', + }), + }, + }, + fn: (context, args) => { + return { + type: 'xy_dimension', + label: args.label, + aggType: args.aggType, + params: JSON.parse(args.params!), + accessor: args.visDimension.accessor as number, + format: args.visDimension.format, + }; + }, +}); diff --git a/src/plugins/vis_type_xy/public/expression_functions/xy_vis_fn.ts b/src/plugins/vis_type_xy/public/expression_functions/xy_vis_fn.ts new file mode 100644 index 0000000000000..b8b8c0e8b8cca --- /dev/null +++ b/src/plugins/vis_type_xy/public/expression_functions/xy_vis_fn.ts @@ -0,0 +1,273 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18n } from '@kbn/i18n'; + +import type { ExpressionFunctionDefinition, Datatable, Render } from '../../../expressions/public'; +import type { ChartType } from '../../common'; +import type { VisParams, XYVisConfig } from '../types'; + +export const visName = 'xy_vis'; +export interface RenderValue { + visData: Datatable; + visType: ChartType; + visConfig: VisParams; + syncColors: boolean; +} + +export type VisTypeXyExpressionFunctionDefinition = ExpressionFunctionDefinition< + typeof visName, + Datatable, + XYVisConfig, + Render +>; + +export const visTypeXyVisFn = (): VisTypeXyExpressionFunctionDefinition => ({ + name: visName, + type: 'render', + context: { + types: ['datatable'], + }, + help: i18n.translate('visTypeXy.functions.help', { + defaultMessage: 'XY visualization', + }), + args: { + type: { + types: ['string'], + default: '""', + help: 'xy vis type', + }, + chartType: { + types: ['string'], + help: i18n.translate('visTypeXy.function.args.args.chartType.help', { + defaultMessage: 'Type of a chart. Can be line, area or histogram', + }), + }, + addTimeMarker: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.args.addTimeMarker.help', { + defaultMessage: 'Show time marker', + }), + }, + addLegend: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.args.addLegend.help', { + defaultMessage: 'Show chart legend', + }), + }, + addTooltip: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.args.addTooltip.help', { + defaultMessage: 'Show tooltip on hover', + }), + }, + legendPosition: { + types: ['string'], + help: i18n.translate('visTypeXy.function.args.legendPosition.help', { + defaultMessage: 'Position the legend on top, bottom, left, right of the chart', + }), + }, + categoryAxes: { + types: ['category_axis'], + help: i18n.translate('visTypeXy.function.args.categoryAxes.help', { + defaultMessage: 'Category axis config', + }), + multi: true, + }, + thresholdLine: { + types: ['threshold_line'], + help: i18n.translate('visTypeXy.function.args.thresholdLine.help', { + defaultMessage: 'Threshold line config', + }), + }, + labels: { + types: ['label'], + help: i18n.translate('visTypeXy.function.args.labels.help', { + defaultMessage: 'Chart labels config', + }), + }, + orderBucketsBySum: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.args.orderBucketsBySum.help', { + defaultMessage: 'Order buckets by sum', + }), + }, + seriesParams: { + types: ['series_param'], + help: i18n.translate('visTypeXy.function.args.seriesParams.help', { + defaultMessage: 'Series param config', + }), + multi: true, + }, + valueAxes: { + types: ['value_axis'], + help: i18n.translate('visTypeXy.function.args.valueAxes.help', { + defaultMessage: 'Value axis config', + }), + multi: true, + }, + radiusRatio: { + types: ['number'], + help: i18n.translate('visTypeXy.function.args.radiusRatio.help', { + defaultMessage: 'Dot size ratio', + }), + }, + gridCategoryLines: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.args.gridCategoryLines.help', { + defaultMessage: 'Show grid category lines in chart', + }), + }, + gridValueAxis: { + types: ['string'], + help: i18n.translate('visTypeXy.function.args.gridValueAxis.help', { + defaultMessage: 'Name of value axis for which we show grid', + }), + }, + isVislibVis: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.args.isVislibVis.help', { + defaultMessage: + 'Flag to indicate old vislib visualizations. Used for backwards compatibility including colors', + }), + }, + detailedTooltip: { + types: ['boolean'], + help: i18n.translate('visTypeXy.function.args.detailedTooltip.help', { + defaultMessage: 'Show detailed tooltip', + }), + }, + fittingFunction: { + types: ['string'], + help: i18n.translate('visTypeXy.function.args.fittingFunction.help', { + defaultMessage: 'Name of fitting function', + }), + }, + times: { + types: ['time_marker'], + help: i18n.translate('visTypeXy.function.args.times.help', { + defaultMessage: 'Time marker config', + }), + multi: true, + }, + palette: { + types: ['string'], + help: i18n.translate('visTypeXy.function.args.palette.help', { + defaultMessage: 'Defines the chart palette name', + }), + }, + xDimension: { + types: ['xy_dimension', 'null'], + help: i18n.translate('visTypeXy.function.args.xDimension.help', { + defaultMessage: 'X axis dimension config', + }), + }, + yDimension: { + types: ['xy_dimension'], + help: i18n.translate('visTypeXy.function.args.yDimension.help', { + defaultMessage: 'Y axis dimension config', + }), + multi: true, + }, + zDimension: { + types: ['xy_dimension'], + help: i18n.translate('visTypeXy.function.args.zDimension.help', { + defaultMessage: 'Z axis dimension config', + }), + multi: true, + }, + widthDimension: { + types: ['xy_dimension'], + help: i18n.translate('visTypeXy.function.args.widthDimension.help', { + defaultMessage: 'Width dimension config', + }), + multi: true, + }, + seriesDimension: { + types: ['xy_dimension'], + help: i18n.translate('visTypeXy.function.args.seriesDimension.help', { + defaultMessage: 'Series dimension config', + }), + multi: true, + }, + splitRowDimension: { + types: ['xy_dimension'], + help: i18n.translate('visTypeXy.function.args.splitRowDimension.help', { + defaultMessage: 'Split by row dimension config', + }), + multi: true, + }, + splitColumnDimension: { + types: ['xy_dimension'], + help: i18n.translate('visTypeXy.function.args.splitColumnDimension.help', { + defaultMessage: 'Split by column dimension config', + }), + multi: true, + }, + }, + fn(context, args, handlers) { + const visType = args.chartType; + const visConfig = { + type: args.chartType, + addLegend: args.addLegend, + addTooltip: args.addTooltip, + legendPosition: args.legendPosition, + addTimeMarker: args.addTimeMarker, + categoryAxes: args.categoryAxes.map((categoryAxis) => ({ + ...categoryAxis, + type: categoryAxis.axisType, + })), + orderBucketsBySum: args.orderBucketsBySum, + labels: args.labels, + thresholdLine: args.thresholdLine, + valueAxes: args.valueAxes.map((valueAxis) => ({ ...valueAxis, type: valueAxis.axisType })), + grid: { + categoryLines: args.gridCategoryLines, + valueAxis: args.gridValueAxis, + }, + seriesParams: args.seriesParams.map((seriesParam) => ({ + ...seriesParam, + type: seriesParam.seriesParamType, + })), + radiusRatio: args.radiusRatio, + times: args.times, + isVislibVis: args.isVislibVis, + detailedTooltip: args.detailedTooltip, + palette: { + type: 'palette', + name: args.palette, + }, + fittingFunction: args.fittingFunction, + dimensions: { + x: args.xDimension, + y: args.yDimension, + z: args.zDimension, + width: args.widthDimension, + series: args.seriesDimension, + splitRow: args.splitRowDimension, + splitColumn: args.splitColumnDimension, + }, + } as VisParams; + + if (handlers?.inspectorAdapters?.tables) { + handlers.inspectorAdapters.tables.logDatatable('default', context); + } + + return { + type: 'render', + as: visName, + value: { + context, + visType, + visConfig, + visData: context, + syncColors: handlers?.isSyncColorsEnabled?.() ?? false, + }, + }; + }, +}); diff --git a/src/plugins/vis_type_xy/public/plugin.ts b/src/plugins/vis_type_xy/public/plugin.ts index d414da8f6dc97..7bdb4f78bc631 100644 --- a/src/plugins/vis_type_xy/public/plugin.ts +++ b/src/plugins/vis_type_xy/public/plugin.ts @@ -12,8 +12,6 @@ import { VisualizationsSetup, VisualizationsStart } from '../../visualizations/p import { ChartsPluginSetup } from '../../charts/public'; import { DataPublicPluginStart } from '../../data/public'; import { UsageCollectionSetup } from '../../usage_collection/public'; - -import { createVisTypeXyVisFn } from './xy_vis_fn'; import { setDataActions, setFormatService, @@ -23,10 +21,13 @@ import { setPalettesService, setTrackUiMetric, } from './services'; + import { visTypesDefinitions } from './vis_types'; import { LEGACY_CHARTS_LIBRARY } from '../common'; import { xyVisRenderer } from './vis_renderer'; +import * as expressionFunctions from './expression_functions'; + // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface VisTypeXyPluginSetup {} // eslint-disable-next-line @typescript-eslint/no-empty-interface @@ -66,8 +67,18 @@ export class VisTypeXyPlugin setUISettings(core.uiSettings); setThemeService(charts.theme); setPalettesService(charts.palettes); - [createVisTypeXyVisFn].forEach(expressions.registerFunction); + expressions.registerRenderer(xyVisRenderer); + expressions.registerFunction(expressionFunctions.visTypeXyVisFn); + expressions.registerFunction(expressionFunctions.categoryAxis); + expressions.registerFunction(expressionFunctions.timeMarker); + expressions.registerFunction(expressionFunctions.valueAxis); + expressions.registerFunction(expressionFunctions.seriesParam); + expressions.registerFunction(expressionFunctions.thresholdLine); + expressions.registerFunction(expressionFunctions.label); + expressions.registerFunction(expressionFunctions.visScale); + expressions.registerFunction(expressionFunctions.xyDimension); + visTypesDefinitions.forEach(visualizations.createBaseVisualization); } diff --git a/src/plugins/vis_type_xy/public/sample_vis.test.mocks.ts b/src/plugins/vis_type_xy/public/sample_vis.test.mocks.ts index c425eb71117e8..e15f9c4207702 100644 --- a/src/plugins/vis_type_xy/public/sample_vis.test.mocks.ts +++ b/src/plugins/vis_type_xy/public/sample_vis.test.mocks.ts @@ -1414,6 +1414,9 @@ export const sampleAreaVis = { color: '#E7664C', }, labels: {}, + palette: { + name: 'default', + }, }, }, editorConfig: { @@ -1575,6 +1578,9 @@ export const sampleAreaVis = { style: 'full', color: '#E7664C', }, + palette: { + name: 'default', + }, labels: {}, dimensions: { x: { diff --git a/src/plugins/vis_type_xy/public/to_ast.test.ts b/src/plugins/vis_type_xy/public/to_ast.test.ts index 22e2d5f1cd9cc..4437986eff5f7 100644 --- a/src/plugins/vis_type_xy/public/to_ast.test.ts +++ b/src/plugins/vis_type_xy/public/to_ast.test.ts @@ -42,7 +42,7 @@ describe('xy vis toExpressionAst function', () => { it('should match basic snapshot', () => { toExpressionAst(vis, params); - const [, builtExpression] = (buildExpression as jest.Mock).mock.calls[0][0]; + const [, builtExpression] = (buildExpression as jest.Mock).mock.calls.pop()[0]; expect(builtExpression).toMatchSnapshot(); }); diff --git a/src/plugins/vis_type_xy/public/to_ast.ts b/src/plugins/vis_type_xy/public/to_ast.ts index 84331af3a5329..c0a0ee566a445 100644 --- a/src/plugins/vis_type_xy/public/to_ast.ts +++ b/src/plugins/vis_type_xy/public/to_ast.ts @@ -11,13 +11,122 @@ import moment from 'moment'; import { VisToExpressionAst, getVisSchemas } from '../../visualizations/public'; import { buildExpression, buildExpressionFunction } from '../../expressions/public'; import { BUCKET_TYPES } from '../../data/public'; +import { Labels } from '../../charts/public'; -import { DateHistogramParams, Dimensions, HistogramParams, VisParams } from './types'; -import { visName, VisTypeXyExpressionFunctionDefinition } from './xy_vis_fn'; +import { + DateHistogramParams, + Dimensions, + Dimension, + HistogramParams, + VisParams, + CategoryAxis, + SeriesParam, + ThresholdLine, + ValueAxis, + Scale, + TimeMarker, +} from './types'; +import { visName, VisTypeXyExpressionFunctionDefinition } from './expression_functions/xy_vis_fn'; import { XyVisType } from '../common'; import { getEsaggsFn } from './to_ast_esaggs'; import { TimeRangeBounds } from '../../data/common'; +const prepareLabel = (data: Labels) => { + const label = buildExpressionFunction('label', { + ...data, + }); + + return buildExpression([label]); +}; + +const prepareScale = (data: Scale) => { + const scale = buildExpressionFunction('visscale', { + ...data, + }); + + return buildExpression([scale]); +}; + +const prepareThresholdLine = (data: ThresholdLine) => { + const thresholdLine = buildExpressionFunction('thresholdline', { + ...data, + }); + + return buildExpression([thresholdLine]); +}; + +const prepareTimeMarker = (data: TimeMarker) => { + const timeMarker = buildExpressionFunction('timemarker', { + ...data, + }); + + return buildExpression([timeMarker]); +}; + +const prepareCategoryAxis = (data: CategoryAxis) => { + const categoryAxis = buildExpressionFunction('categoryaxis', { + id: data.id, + show: data.show, + position: data.position, + type: data.type, + title: data.title.text, + scale: prepareScale(data.scale), + labels: prepareLabel(data.labels), + }); + + return buildExpression([categoryAxis]); +}; + +const prepareValueAxis = (data: ValueAxis) => { + const categoryAxis = buildExpressionFunction('valueaxis', { + name: data.name, + axisParams: prepareCategoryAxis({ + ...data, + }), + }); + + return buildExpression([categoryAxis]); +}; + +const prepareSeriesParam = (data: SeriesParam) => { + const seriesParam = buildExpressionFunction('seriesparam', { + label: data.data.label, + id: data.data.id, + drawLinesBetweenPoints: data.drawLinesBetweenPoints, + interpolate: data.interpolate, + lineWidth: data.lineWidth, + mode: data.mode, + show: data.show, + showCircles: data.showCircles, + type: data.type, + valueAxis: data.valueAxis, + }); + + return buildExpression([seriesParam]); +}; + +const prepareVisDimension = (data: Dimension) => { + const visDimension = buildExpressionFunction('visdimension', { accessor: data.accessor }); + + if (data.format) { + visDimension.addArgument('format', data.format.id); + visDimension.addArgument('formatParams', JSON.stringify(data.format.params)); + } + + return buildExpression([visDimension]); +}; + +const prepareXYDimension = (data: Dimension) => { + const xyDimension = buildExpressionFunction('xydimension', { + params: JSON.stringify(data.params), + aggType: data.aggType, + label: data.label, + visDimension: prepareVisDimension(data), + }); + + return buildExpression([xyDimension]); +}; + export const toExpressionAst: VisToExpressionAst = async (vis, params) => { const schemas = getVisSchemas(vis, params); const dimensions: Dimensions = { @@ -62,15 +171,13 @@ export const toExpressionAst: VisToExpressionAst = async (vis, params } } - const visConfig = { ...vis.params }; - (dimensions.y || []).forEach((yDimension) => { const yAgg = responseAggs[yDimension.accessor]; - const seriesParam = (visConfig.seriesParams || []).find( + const seriesParam = (vis.params.seriesParams || []).find( (param: any) => param.data.id === yAgg.id ); if (seriesParam) { - const usedValueAxis = (visConfig.valueAxes || []).find( + const usedValueAxis = (vis.params.valueAxes || []).find( (valueAxis: any) => valueAxis.id === seriesParam.valueAxis ); if (usedValueAxis?.scale.mode === 'percentage') { @@ -79,11 +186,34 @@ export const toExpressionAst: VisToExpressionAst = async (vis, params } }); - visConfig.dimensions = dimensions; - const visTypeXy = buildExpressionFunction(visName, { type: vis.type.name as XyVisType, - visConfig: JSON.stringify(visConfig), + chartType: vis.params.type, + addTimeMarker: vis.params.addTimeMarker, + addLegend: vis.params.addLegend, + addTooltip: vis.params.addTooltip, + legendPosition: vis.params.legendPosition, + orderBucketsBySum: vis.params.orderBucketsBySum, + categoryAxes: vis.params.categoryAxes.map(prepareCategoryAxis), + valueAxes: vis.params.valueAxes.map(prepareValueAxis), + seriesParams: vis.params.seriesParams.map(prepareSeriesParam), + labels: prepareLabel(vis.params.labels), + thresholdLine: prepareThresholdLine(vis.params.thresholdLine), + gridCategoryLines: vis.params.grid.categoryLines, + gridValueAxis: vis.params.grid.valueAxis, + radiusRatio: vis.params.radiusRatio, + isVislibVis: vis.params.isVislibVis, + detailedTooltip: vis.params.detailedTooltip, + fittingFunction: vis.params.fittingFunction, + times: vis.params.times.map(prepareTimeMarker), + palette: vis.params.palette.name, + xDimension: dimensions.x ? prepareXYDimension(dimensions.x) : null, + yDimension: dimensions.y.map(prepareXYDimension), + zDimension: dimensions.z?.map(prepareXYDimension), + widthDimension: dimensions.width?.map(prepareXYDimension), + seriesDimension: dimensions.series?.map(prepareXYDimension), + splitRowDimension: dimensions.splitRow?.map(prepareXYDimension), + splitColumnDimension: dimensions.splitColumn?.map(prepareXYDimension), }); const ast = buildExpression([getEsaggsFn(vis), visTypeXy]); diff --git a/src/plugins/vis_type_xy/public/types/config.ts b/src/plugins/vis_type_xy/public/types/config.ts index d5c5bfe004191..f025a36a82410 100644 --- a/src/plugins/vis_type_xy/public/types/config.ts +++ b/src/plugins/vis_type_xy/public/types/config.ts @@ -20,7 +20,7 @@ import { YDomainRange, } from '@elastic/charts'; -import { Dimension, Scale, ThresholdLine } from './param'; +import type { Dimension, Scale, ThresholdLine } from './param'; export interface Column { id: string | null; diff --git a/src/plugins/vis_type_xy/public/types/constants.ts b/src/plugins/vis_type_xy/public/types/constants.ts index 5c2f23b76aa96..05ed0783d4c68 100644 --- a/src/plugins/vis_type_xy/public/types/constants.ts +++ b/src/plugins/vis_type_xy/public/types/constants.ts @@ -6,52 +6,43 @@ * Side Public License, v 1. */ -import { $Values } from '@kbn/utility-types'; - -export const ChartMode = Object.freeze({ - Normal: 'normal' as const, - Stacked: 'stacked' as const, -}); -export type ChartMode = $Values; - -export const InterpolationMode = Object.freeze({ - Linear: 'linear' as const, - Cardinal: 'cardinal' as const, - StepAfter: 'step-after' as const, -}); -export type InterpolationMode = $Values; - -export const AxisType = Object.freeze({ - Category: 'category' as const, - Value: 'value' as const, -}); -export type AxisType = $Values; - -export const ScaleType = Object.freeze({ - Linear: 'linear' as const, - Log: 'log' as const, - SquareRoot: 'square root' as const, -}); -export type ScaleType = $Values; - -export const AxisMode = Object.freeze({ - Normal: 'normal' as const, - Percentage: 'percentage' as const, - Wiggle: 'wiggle' as const, - Silhouette: 'silhouette' as const, -}); -export type AxisMode = $Values; - -export const ThresholdLineStyle = Object.freeze({ - Full: 'full' as const, - Dashed: 'dashed' as const, - DotDashed: 'dot-dashed' as const, -}); -export type ThresholdLineStyle = $Values; - -export const ColorMode = Object.freeze({ - Background: 'Background' as const, - Labels: 'Labels' as const, - None: 'None' as const, -}); -export type ColorMode = $Values; +export enum ChartMode { + Normal = 'normal', + Stacked = 'stacked', +} + +export enum InterpolationMode { + Linear = 'linear', + Cardinal = 'cardinal', + StepAfter = 'step-after', +} + +export enum AxisType { + Category = 'category', + Value = 'value', +} + +export enum ScaleType { + Linear = 'linear', + Log = 'log', + SquareRoot = 'square root', +} + +export enum AxisMode { + Normal = 'normal', + Percentage = 'percentage', + Wiggle = 'wiggle', + Silhouette = 'silhouette', +} + +export enum ThresholdLineStyle { + Full = 'full', + Dashed = 'dashed', + DotDashed = 'dot-dashed', +} + +export enum ColorMode { + Background = 'Background', + Labels = 'Labels', + None = 'None', +} diff --git a/src/plugins/vis_type_xy/public/types/index.ts b/src/plugins/vis_type_xy/public/types/index.ts index d612e9fcf5f6f..6abbdfabaa956 100644 --- a/src/plugins/vis_type_xy/public/types/index.ts +++ b/src/plugins/vis_type_xy/public/types/index.ts @@ -9,4 +9,4 @@ export * from './constants'; export * from './config'; export * from './param'; -export * from './vis_type'; +export type { VisTypeNames, XyVisTypeDefinition } from './vis_type'; diff --git a/src/plugins/vis_type_xy/public/types/param.ts b/src/plugins/vis_type_xy/public/types/param.ts index 69b6daf077a32..f90899620126a 100644 --- a/src/plugins/vis_type_xy/public/types/param.ts +++ b/src/plugins/vis_type_xy/public/types/param.ts @@ -6,13 +6,21 @@ * Side Public License, v 1. */ -import { Fit, Position } from '@elastic/charts'; - -import { Style, Labels, PaletteOutput } from '../../../charts/public'; -import { SchemaConfig } from '../../../visualizations/public'; - -import { ChartType } from '../../common'; -import { +import type { Fit, Position } from '@elastic/charts'; +import type { Style, Labels, PaletteOutput } from '../../../charts/public'; +import type { SchemaConfig } from '../../../visualizations/public'; +import type { ChartType, XyVisType } from '../../common'; +import type { + ExpressionValueCategoryAxis, + ExpressionValueSeriesParam, + ExpressionValueValueAxis, + ExpressionValueLabel, + ExpressionValueThresholdLine, + ExpressionValueTimeMarker, + ExpressionValueXYDimension, +} from '../expression_functions'; + +import type { ChartMode, AxisMode, AxisType, @@ -47,7 +55,7 @@ export interface CategoryAxis { * remove with vis_type_vislib * https://github.com/elastic/kibana/issues/56143 */ - style: Partial